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 |
---|---|---|---|---|---|---|---|---|---|---|---|
SurePetcareBinarySensor.async_will_remove_from_hass | (self) | Disconnect dispatcher listener when removed. | Disconnect dispatcher listener when removed. | async def async_will_remove_from_hass(self) -> None:
"""Disconnect dispatcher listener when removed."""
if self._async_unsub_dispatcher_connect:
self._async_unsub_dispatcher_connect() | [
"async",
"def",
"async_will_remove_from_hass",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_async_unsub_dispatcher_connect",
":",
"self",
".",
"_async_unsub_dispatcher_connect",
"(",
")"
] | [
129,
4
] | [
132,
50
] | python | en | ['en', 'en', 'en'] | True |
Hub.__init__ | (self, _id: int, spc: SurePetcareAPI) | Initialize a Sure Petcare Hub. | Initialize a Sure Petcare Hub. | def __init__(self, _id: int, spc: SurePetcareAPI) -> None:
"""Initialize a Sure Petcare Hub."""
super().__init__(_id, spc, DEVICE_CLASS_CONNECTIVITY, SureProductID.HUB) | [
"def",
"__init__",
"(",
"self",
",",
"_id",
":",
"int",
",",
"spc",
":",
"SurePetcareAPI",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"_id",
",",
"spc",
",",
"DEVICE_CLASS_CONNECTIVITY",
",",
"SureProductID",
".",
"HUB",
")"
] | [
138,
4
] | [
140,
80
] | python | ro | ['ro', 'ro', 'it'] | True |
Hub.available | (self) | Return true if entity is available. | Return true if entity is available. | def available(self) -> bool:
"""Return true if entity is available."""
return bool(self._state["online"]) | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"_state",
"[",
"\"online\"",
"]",
")"
] | [
143,
4
] | [
145,
42
] | python | en | ['en', 'en', 'en'] | True |
Hub.is_on | (self) | Return true if entity is online. | Return true if entity is online. | def is_on(self) -> bool:
"""Return true if entity is online."""
return self.available | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"available"
] | [
148,
4
] | [
150,
29
] | python | en | ['en', 'fy', 'en'] | True |
Hub.device_state_attributes | (self) | Return the state attributes of the device. | Return the state attributes of the device. | def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes of the device."""
attributes = None
if self._state:
attributes = {
"led_mode": int(self._state["led_mode"]),
"pairing_mode": bool(self._state["pairing_mode"]),
}
return attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"attributes",
"=",
"None",
"if",
"self",
".",
"_state",
":",
"attributes",
"=",
"{",
"\"led_mode\"",
":",
"int",
"(",
"self",
".",
"_state",
"[",
"\"led_mode\"",
"]",
")",
",",
"\"pairing_mode\"",
":",
"bool",
"(",
"self",
".",
"_state",
"[",
"\"pairing_mode\"",
"]",
")",
",",
"}",
"return",
"attributes"
] | [
153,
4
] | [
162,
25
] | python | en | ['en', 'en', 'en'] | True |
Pet.__init__ | (self, _id: int, spc: SurePetcareAPI) | Initialize a Sure Petcare Pet. | Initialize a Sure Petcare Pet. | def __init__(self, _id: int, spc: SurePetcareAPI) -> None:
"""Initialize a Sure Petcare Pet."""
super().__init__(_id, spc, DEVICE_CLASS_PRESENCE, SureProductID.PET) | [
"def",
"__init__",
"(",
"self",
",",
"_id",
":",
"int",
",",
"spc",
":",
"SurePetcareAPI",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"_id",
",",
"spc",
",",
"DEVICE_CLASS_PRESENCE",
",",
"SureProductID",
".",
"PET",
")"
] | [
168,
4
] | [
170,
76
] | python | ro | ['ro', 'ro', 'it'] | True |
Pet.is_on | (self) | Return true if entity is at home. | Return true if entity is at home. | def is_on(self) -> bool:
"""Return true if entity is at home."""
try:
return bool(SureLocationID(self._state["where"]) == SureLocationID.INSIDE)
except (KeyError, TypeError):
return False | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"try",
":",
"return",
"bool",
"(",
"SureLocationID",
"(",
"self",
".",
"_state",
"[",
"\"where\"",
"]",
")",
"==",
"SureLocationID",
".",
"INSIDE",
")",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"return",
"False"
] | [
173,
4
] | [
178,
24
] | python | en | ['en', 'en', 'en'] | True |
Pet.device_state_attributes | (self) | Return the state attributes of the device. | Return the state attributes of the device. | def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes of the device."""
attributes = None
if self._state:
attributes = {
"since": str(
datetime.fromisoformat(self._state["since"]).replace(tzinfo=None)
),
"where": SureLocationID(self._state["where"]).name.capitalize(),
}
return attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"attributes",
"=",
"None",
"if",
"self",
".",
"_state",
":",
"attributes",
"=",
"{",
"\"since\"",
":",
"str",
"(",
"datetime",
".",
"fromisoformat",
"(",
"self",
".",
"_state",
"[",
"\"since\"",
"]",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
")",
",",
"\"where\"",
":",
"SureLocationID",
"(",
"self",
".",
"_state",
"[",
"\"where\"",
"]",
")",
".",
"name",
".",
"capitalize",
"(",
")",
",",
"}",
"return",
"attributes"
] | [
181,
4
] | [
192,
25
] | python | en | ['en', 'en', 'en'] | True |
Pet.async_update | (self) | Get the latest data and update the state. | Get the latest data and update the state. | async def async_update(self) -> None:
"""Get the latest data and update the state."""
self._spc_data = self._spc.states[self._sure_type].get(self._id)
self._state = self._spc_data.get("position")
_LOGGER.debug("%s -> self._state: %s", self._name, self._state) | [
"async",
"def",
"async_update",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_spc_data",
"=",
"self",
".",
"_spc",
".",
"states",
"[",
"self",
".",
"_sure_type",
"]",
".",
"get",
"(",
"self",
".",
"_id",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_spc_data",
".",
"get",
"(",
"\"position\"",
")",
"_LOGGER",
".",
"debug",
"(",
"\"%s -> self._state: %s\"",
",",
"self",
".",
"_name",
",",
"self",
".",
"_state",
")"
] | [
194,
4
] | [
198,
71
] | python | en | ['en', 'en', 'en'] | True |
DeviceConnectivity.__init__ | (
self,
_id: int,
sure_type: SureProductID,
spc: SurePetcareAPI,
) | Initialize a Sure Petcare Device. | Initialize a Sure Petcare Device. | def __init__(
self,
_id: int,
sure_type: SureProductID,
spc: SurePetcareAPI,
) -> None:
"""Initialize a Sure Petcare Device."""
super().__init__(_id, spc, DEVICE_CLASS_CONNECTIVITY, sure_type) | [
"def",
"__init__",
"(",
"self",
",",
"_id",
":",
"int",
",",
"sure_type",
":",
"SureProductID",
",",
"spc",
":",
"SurePetcareAPI",
",",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"_id",
",",
"spc",
",",
"DEVICE_CLASS_CONNECTIVITY",
",",
"sure_type",
")"
] | [
204,
4
] | [
211,
72
] | python | ro | ['ro', 'ro', 'it'] | True |
DeviceConnectivity.name | (self) | Return the name of the device if any. | Return the name of the device if any. | def name(self) -> str:
"""Return the name of the device if any."""
return f"{self._name}_connectivity" | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{self._name}_connectivity\""
] | [
214,
4
] | [
216,
43
] | python | en | ['en', 'en', 'en'] | True |
DeviceConnectivity.unique_id | (self) | Return an unique ID. | Return an unique ID. | def unique_id(self) -> str:
"""Return an unique ID."""
return f"{self._spc_data['household_id']}-{self._id}-connectivity" | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{self._spc_data['household_id']}-{self._id}-connectivity\""
] | [
219,
4
] | [
221,
74
] | python | fr | ['fr', 'fr', 'en'] | True |
DeviceConnectivity.available | (self) | Return true if entity is available. | Return true if entity is available. | def available(self) -> bool:
"""Return true if entity is available."""
return bool(self._state) | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"_state",
")"
] | [
224,
4
] | [
226,
32
] | python | en | ['en', 'en', 'en'] | True |
DeviceConnectivity.is_on | (self) | Return true if entity is online. | Return true if entity is online. | def is_on(self) -> bool:
"""Return true if entity is online."""
return self.available | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"available"
] | [
229,
4
] | [
231,
29
] | python | en | ['en', 'fy', 'en'] | True |
DeviceConnectivity.device_state_attributes | (self) | Return the state attributes of the device. | Return the state attributes of the device. | def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes of the device."""
attributes = None
if self._state:
attributes = {
"device_rssi": f'{self._state["signal"]["device_rssi"]:.2f}',
"hub_rssi": f'{self._state["signal"]["hub_rssi"]:.2f}',
}
return attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"attributes",
"=",
"None",
"if",
"self",
".",
"_state",
":",
"attributes",
"=",
"{",
"\"device_rssi\"",
":",
"f'{self._state[\"signal\"][\"device_rssi\"]:.2f}'",
",",
"\"hub_rssi\"",
":",
"f'{self._state[\"signal\"][\"hub_rssi\"]:.2f}'",
",",
"}",
"return",
"attributes"
] | [
234,
4
] | [
243,
25
] | python | en | ['en', 'en', 'en'] | True |
zigpy_device_dt | (zigpy_device_mock) | Device tracker zigpy device. | Device tracker zigpy device. | def zigpy_device_dt(zigpy_device_mock):
"""Device tracker zigpy device."""
endpoints = {
1: {
"in_clusters": [
general.Basic.cluster_id,
general.PowerConfiguration.cluster_id,
general.Identify.cluster_id,
general.PollControl.cluster_id,
general.BinaryInput.cluster_id,
],
"out_clusters": [general.Identify.cluster_id, general.Ota.cluster_id],
"device_type": SMARTTHINGS_ARRIVAL_SENSOR_DEVICE_TYPE,
}
}
return zigpy_device_mock(endpoints) | [
"def",
"zigpy_device_dt",
"(",
"zigpy_device_mock",
")",
":",
"endpoints",
"=",
"{",
"1",
":",
"{",
"\"in_clusters\"",
":",
"[",
"general",
".",
"Basic",
".",
"cluster_id",
",",
"general",
".",
"PowerConfiguration",
".",
"cluster_id",
",",
"general",
".",
"Identify",
".",
"cluster_id",
",",
"general",
".",
"PollControl",
".",
"cluster_id",
",",
"general",
".",
"BinaryInput",
".",
"cluster_id",
",",
"]",
",",
"\"out_clusters\"",
":",
"[",
"general",
".",
"Identify",
".",
"cluster_id",
",",
"general",
".",
"Ota",
".",
"cluster_id",
"]",
",",
"\"device_type\"",
":",
"SMARTTHINGS_ARRIVAL_SENSOR_DEVICE_TYPE",
",",
"}",
"}",
"return",
"zigpy_device_mock",
"(",
"endpoints",
")"
] | [
25,
0
] | [
40,
39
] | python | cs | ['nl', 'cs', 'en'] | False |
test_device_tracker | (hass, zha_device_joined_restored, zigpy_device_dt) | Test zha device tracker platform. | Test zha device tracker platform. | async def test_device_tracker(hass, zha_device_joined_restored, zigpy_device_dt):
"""Test zha device tracker platform."""
zha_device = await zha_device_joined_restored(zigpy_device_dt)
cluster = zigpy_device_dt.endpoints.get(1).power
entity_id = await find_entity_id(DOMAIN, zha_device, hass)
assert entity_id is not None
assert hass.states.get(entity_id).state == STATE_HOME
await async_enable_traffic(hass, [zha_device], enabled=False)
# test that the device tracker was created and that it is unavailable
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
zigpy_device_dt.last_seen = time.time() - 120
next_update = dt_util.utcnow() + timedelta(seconds=30)
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
# allow traffic to flow through the gateway and device
await async_enable_traffic(hass, [zha_device])
# test that the state has changed from unavailable to not home
assert hass.states.get(entity_id).state == STATE_NOT_HOME
# turn state flip
await send_attributes_report(
hass, cluster, {0x0000: 0, 0x0020: 23, 0x0021: 200, 0x0001: 2}
)
zigpy_device_dt.last_seen = time.time() + 10
next_update = dt_util.utcnow() + timedelta(seconds=30)
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_HOME
entity = hass.data[DOMAIN].get_entity(entity_id)
assert entity.is_connected is True
assert entity.source_type == SOURCE_TYPE_ROUTER
assert entity.battery_level == 100
# test adding device tracker to the network and HA
await async_test_rejoin(hass, zigpy_device_dt, [cluster], (2,))
assert hass.states.get(entity_id).state == STATE_HOME | [
"async",
"def",
"test_device_tracker",
"(",
"hass",
",",
"zha_device_joined_restored",
",",
"zigpy_device_dt",
")",
":",
"zha_device",
"=",
"await",
"zha_device_joined_restored",
"(",
"zigpy_device_dt",
")",
"cluster",
"=",
"zigpy_device_dt",
".",
"endpoints",
".",
"get",
"(",
"1",
")",
".",
"power",
"entity_id",
"=",
"await",
"find_entity_id",
"(",
"DOMAIN",
",",
"zha_device",
",",
"hass",
")",
"assert",
"entity_id",
"is",
"not",
"None",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
".",
"state",
"==",
"STATE_HOME",
"await",
"async_enable_traffic",
"(",
"hass",
",",
"[",
"zha_device",
"]",
",",
"enabled",
"=",
"False",
")",
"# test that the device tracker was created and that it is unavailable",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
".",
"state",
"==",
"STATE_UNAVAILABLE",
"zigpy_device_dt",
".",
"last_seen",
"=",
"time",
".",
"time",
"(",
")",
"-",
"120",
"next_update",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"30",
")",
"async_fire_time_changed",
"(",
"hass",
",",
"next_update",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# allow traffic to flow through the gateway and device",
"await",
"async_enable_traffic",
"(",
"hass",
",",
"[",
"zha_device",
"]",
")",
"# test that the state has changed from unavailable to not home",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
".",
"state",
"==",
"STATE_NOT_HOME",
"# turn state flip",
"await",
"send_attributes_report",
"(",
"hass",
",",
"cluster",
",",
"{",
"0x0000",
":",
"0",
",",
"0x0020",
":",
"23",
",",
"0x0021",
":",
"200",
",",
"0x0001",
":",
"2",
"}",
")",
"zigpy_device_dt",
".",
"last_seen",
"=",
"time",
".",
"time",
"(",
")",
"+",
"10",
"next_update",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"30",
")",
"async_fire_time_changed",
"(",
"hass",
",",
"next_update",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
".",
"state",
"==",
"STATE_HOME",
"entity",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"get_entity",
"(",
"entity_id",
")",
"assert",
"entity",
".",
"is_connected",
"is",
"True",
"assert",
"entity",
".",
"source_type",
"==",
"SOURCE_TYPE_ROUTER",
"assert",
"entity",
".",
"battery_level",
"==",
"100",
"# test adding device tracker to the network and HA",
"await",
"async_test_rejoin",
"(",
"hass",
",",
"zigpy_device_dt",
",",
"[",
"cluster",
"]",
",",
"(",
"2",
",",
")",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
".",
"state",
"==",
"STATE_HOME"
] | [
43,
0
] | [
87,
57
] | python | br | ['br', 'ru-Latn', 'it'] | False |
to_dag | (C_in, gene, reduction, bn_affine=True) | generate discrete ops from gene | generate discrete ops from gene | def to_dag(C_in, gene, reduction, bn_affine=True):
""" generate discrete ops from gene """
dag = nn.ModuleList()
for edges in gene:
row = nn.ModuleList()
for op_name, s_idx in edges:
# reduction cell & from input nodes => stride = 2
stride = 2 if reduction and s_idx < 2 else 1
op = ops.OPS[op_name](C_in, stride, bn_affine)
if not isinstance(op, ops.Identity): # Identity does not use drop path
op = nn.Sequential(
op,
ops.DropPath_()
)
op.s_idx = s_idx
row.append(op)
dag.append(row)
return dag | [
"def",
"to_dag",
"(",
"C_in",
",",
"gene",
",",
"reduction",
",",
"bn_affine",
"=",
"True",
")",
":",
"dag",
"=",
"nn",
".",
"ModuleList",
"(",
")",
"for",
"edges",
"in",
"gene",
":",
"row",
"=",
"nn",
".",
"ModuleList",
"(",
")",
"for",
"op_name",
",",
"s_idx",
"in",
"edges",
":",
"# reduction cell & from input nodes => stride = 2",
"stride",
"=",
"2",
"if",
"reduction",
"and",
"s_idx",
"<",
"2",
"else",
"1",
"op",
"=",
"ops",
".",
"OPS",
"[",
"op_name",
"]",
"(",
"C_in",
",",
"stride",
",",
"bn_affine",
")",
"if",
"not",
"isinstance",
"(",
"op",
",",
"ops",
".",
"Identity",
")",
":",
"# Identity does not use drop path",
"op",
"=",
"nn",
".",
"Sequential",
"(",
"op",
",",
"ops",
".",
"DropPath_",
"(",
")",
")",
"op",
".",
"s_idx",
"=",
"s_idx",
"row",
".",
"append",
"(",
"op",
")",
"dag",
".",
"append",
"(",
"row",
")",
"return",
"dag"
] | [
20,
0
] | [
38,
14
] | python | en | ['en', 'co', 'en'] | True |
from_str | (s) | generate genotype from string
e.g. "Genotype(
normal=[[('sep_conv_3x3', 0), ('sep_conv_3x3', 1)],
[('sep_conv_3x3', 1), ('dil_conv_3x3', 2)],
[('sep_conv_3x3', 1), ('sep_conv_3x3', 2)],
[('sep_conv_3x3', 1), ('dil_conv_3x3', 4)]],
normal_concat=range(2, 6),
reduce=[[('max_pool_3x3', 0), ('max_pool_3x3', 1)],
[('max_pool_3x3', 0), ('skip_connect', 2)],
[('max_pool_3x3', 0), ('skip_connect', 2)],
[('max_pool_3x3', 0), ('skip_connect', 2)]],
reduce_concat=range(2, 6))"
| generate genotype from string
e.g. "Genotype(
normal=[[('sep_conv_3x3', 0), ('sep_conv_3x3', 1)],
[('sep_conv_3x3', 1), ('dil_conv_3x3', 2)],
[('sep_conv_3x3', 1), ('sep_conv_3x3', 2)],
[('sep_conv_3x3', 1), ('dil_conv_3x3', 4)]],
normal_concat=range(2, 6),
reduce=[[('max_pool_3x3', 0), ('max_pool_3x3', 1)],
[('max_pool_3x3', 0), ('skip_connect', 2)],
[('max_pool_3x3', 0), ('skip_connect', 2)],
[('max_pool_3x3', 0), ('skip_connect', 2)]],
reduce_concat=range(2, 6))"
| def from_str(s):
""" generate genotype from string
e.g. "Genotype(
normal=[[('sep_conv_3x3', 0), ('sep_conv_3x3', 1)],
[('sep_conv_3x3', 1), ('dil_conv_3x3', 2)],
[('sep_conv_3x3', 1), ('sep_conv_3x3', 2)],
[('sep_conv_3x3', 1), ('dil_conv_3x3', 4)]],
normal_concat=range(2, 6),
reduce=[[('max_pool_3x3', 0), ('max_pool_3x3', 1)],
[('max_pool_3x3', 0), ('skip_connect', 2)],
[('max_pool_3x3', 0), ('skip_connect', 2)],
[('max_pool_3x3', 0), ('skip_connect', 2)]],
reduce_concat=range(2, 6))"
"""
genotype = eval(s)
return genotype | [
"def",
"from_str",
"(",
"s",
")",
":",
"genotype",
"=",
"eval",
"(",
"s",
")",
"return",
"genotype"
] | [
41,
0
] | [
58,
19
] | python | en | ['en', 'en', 'en'] | True |
parse | (alpha, beta, k) |
parse continuous alpha to discrete gene.
alpha is ParameterList:
ParameterList [
Parameter(n_edges1, n_ops),
Parameter(n_edges2, n_ops),
...
]
beta is ParameterList:
ParameterList [
Parameter(n_edges1),
Parameter(n_edges2),
...
]
gene is list:
[
[('node1_ops_1', node_idx), ..., ('node1_ops_k', node_idx)],
[('node2_ops_1', node_idx), ..., ('node2_ops_k', node_idx)],
...
]
each node has two edges (k=2) in CNN.
|
parse continuous alpha to discrete gene.
alpha is ParameterList:
ParameterList [
Parameter(n_edges1, n_ops),
Parameter(n_edges2, n_ops),
...
] | def parse(alpha, beta, k):
"""
parse continuous alpha to discrete gene.
alpha is ParameterList:
ParameterList [
Parameter(n_edges1, n_ops),
Parameter(n_edges2, n_ops),
...
]
beta is ParameterList:
ParameterList [
Parameter(n_edges1),
Parameter(n_edges2),
...
]
gene is list:
[
[('node1_ops_1', node_idx), ..., ('node1_ops_k', node_idx)],
[('node2_ops_1', node_idx), ..., ('node2_ops_k', node_idx)],
...
]
each node has two edges (k=2) in CNN.
"""
gene = []
assert PRIMITIVES[-1] == 'none' # 'none' is implemented in mutator now
# 1) Convert the mixed op to discrete edge (single op) by choosing top-1 weight edge
# 2) Choose top-k edges per node by edge score (top-1 weight in edge)
# output the connect idx[(node_idx, connect_idx, op_idx).... () ()]
connect_idx = []
for edges, w in zip(alpha, beta):
# edges: Tensor(n_edges, n_ops)
edge_max, primitive_indices = torch.topk((w.view(-1, 1) * edges)[:, :-1], 1) # ignore 'none'
topk_edge_values, topk_edge_indices = torch.topk(edge_max.view(-1), k)
node_gene = []
node_idx = []
for edge_idx in topk_edge_indices:
prim_idx = primitive_indices[edge_idx]
prim = PRIMITIVES[prim_idx]
node_gene.append((prim, edge_idx.item()))
node_idx.append((edge_idx.item(), prim_idx.item()))
gene.append(node_gene)
connect_idx.append(node_idx)
return gene, connect_idx | [
"def",
"parse",
"(",
"alpha",
",",
"beta",
",",
"k",
")",
":",
"gene",
"=",
"[",
"]",
"assert",
"PRIMITIVES",
"[",
"-",
"1",
"]",
"==",
"'none'",
"# 'none' is implemented in mutator now",
"# 1) Convert the mixed op to discrete edge (single op) by choosing top-1 weight edge",
"# 2) Choose top-k edges per node by edge score (top-1 weight in edge)",
"# output the connect idx[(node_idx, connect_idx, op_idx).... () ()]",
"connect_idx",
"=",
"[",
"]",
"for",
"edges",
",",
"w",
"in",
"zip",
"(",
"alpha",
",",
"beta",
")",
":",
"# edges: Tensor(n_edges, n_ops)",
"edge_max",
",",
"primitive_indices",
"=",
"torch",
".",
"topk",
"(",
"(",
"w",
".",
"view",
"(",
"-",
"1",
",",
"1",
")",
"*",
"edges",
")",
"[",
":",
",",
":",
"-",
"1",
"]",
",",
"1",
")",
"# ignore 'none'",
"topk_edge_values",
",",
"topk_edge_indices",
"=",
"torch",
".",
"topk",
"(",
"edge_max",
".",
"view",
"(",
"-",
"1",
")",
",",
"k",
")",
"node_gene",
"=",
"[",
"]",
"node_idx",
"=",
"[",
"]",
"for",
"edge_idx",
"in",
"topk_edge_indices",
":",
"prim_idx",
"=",
"primitive_indices",
"[",
"edge_idx",
"]",
"prim",
"=",
"PRIMITIVES",
"[",
"prim_idx",
"]",
"node_gene",
".",
"append",
"(",
"(",
"prim",
",",
"edge_idx",
".",
"item",
"(",
")",
")",
")",
"node_idx",
".",
"append",
"(",
"(",
"edge_idx",
".",
"item",
"(",
")",
",",
"prim_idx",
".",
"item",
"(",
")",
")",
")",
"gene",
".",
"append",
"(",
"node_gene",
")",
"connect_idx",
".",
"append",
"(",
"node_idx",
")",
"return",
"gene",
",",
"connect_idx"
] | [
61,
0
] | [
109,
28
] | python | en | ['en', 'error', 'th'] | False |
parse_gumbel | (alpha, beta, k) |
parse continuous alpha to discrete gene.
alpha is ParameterList:
ParameterList [
Parameter(n_edges1, n_ops),
Parameter(n_edges2, n_ops),
...
]
beta is ParameterList:
ParameterList [
Parameter(n_edges1),
Parameter(n_edges2),
...
]
gene is list:
[
[('node1_ops_1', node_idx), ..., ('node1_ops_k', node_idx)],
[('node2_ops_1', node_idx), ..., ('node2_ops_k', node_idx)],
...
]
each node has two edges (k=2) in CNN.
|
parse continuous alpha to discrete gene.
alpha is ParameterList:
ParameterList [
Parameter(n_edges1, n_ops),
Parameter(n_edges2, n_ops),
...
] | def parse_gumbel(alpha, beta, k):
"""
parse continuous alpha to discrete gene.
alpha is ParameterList:
ParameterList [
Parameter(n_edges1, n_ops),
Parameter(n_edges2, n_ops),
...
]
beta is ParameterList:
ParameterList [
Parameter(n_edges1),
Parameter(n_edges2),
...
]
gene is list:
[
[('node1_ops_1', node_idx), ..., ('node1_ops_k', node_idx)],
[('node2_ops_1', node_idx), ..., ('node2_ops_k', node_idx)],
...
]
each node has two edges (k=2) in CNN.
"""
gene = []
assert PRIMITIVES[-1] == 'none' # assume last PRIMITIVE is 'none'
# 1) Convert the mixed op to discrete edge (single op) by choosing top-1 weight edge
# 2) Choose top-k edges per node by edge score (top-1 weight in edge)
# output the connect idx[(node_idx, connect_idx, op_idx).... () ()]
connect_idx = []
for edges, w in zip(alpha, beta):
# edges: Tensor(n_edges, n_ops)
discrete_a = F.gumbel_softmax(edges[:, :-1].reshape(-1), tau=1, hard=True)
for i in range(k-1):
discrete_a = discrete_a + F.gumbel_softmax(edges[:, :-1].reshape(-1), tau=1, hard=True)
discrete_a = discrete_a.reshape(-1, len(PRIMITIVES)-1)
reserved_edge = (discrete_a > 0).nonzero()
node_gene = []
node_idx = []
for i in range(reserved_edge.shape[0]):
edge_idx = reserved_edge[i][0].item()
prim_idx = reserved_edge[i][1].item()
prim = PRIMITIVES[prim_idx]
node_gene.append((prim, edge_idx))
node_idx.append((edge_idx, prim_idx))
gene.append(node_gene)
connect_idx.append(node_idx)
return gene, connect_idx | [
"def",
"parse_gumbel",
"(",
"alpha",
",",
"beta",
",",
"k",
")",
":",
"gene",
"=",
"[",
"]",
"assert",
"PRIMITIVES",
"[",
"-",
"1",
"]",
"==",
"'none'",
"# assume last PRIMITIVE is 'none'",
"# 1) Convert the mixed op to discrete edge (single op) by choosing top-1 weight edge",
"# 2) Choose top-k edges per node by edge score (top-1 weight in edge)",
"# output the connect idx[(node_idx, connect_idx, op_idx).... () ()]",
"connect_idx",
"=",
"[",
"]",
"for",
"edges",
",",
"w",
"in",
"zip",
"(",
"alpha",
",",
"beta",
")",
":",
"# edges: Tensor(n_edges, n_ops)",
"discrete_a",
"=",
"F",
".",
"gumbel_softmax",
"(",
"edges",
"[",
":",
",",
":",
"-",
"1",
"]",
".",
"reshape",
"(",
"-",
"1",
")",
",",
"tau",
"=",
"1",
",",
"hard",
"=",
"True",
")",
"for",
"i",
"in",
"range",
"(",
"k",
"-",
"1",
")",
":",
"discrete_a",
"=",
"discrete_a",
"+",
"F",
".",
"gumbel_softmax",
"(",
"edges",
"[",
":",
",",
":",
"-",
"1",
"]",
".",
"reshape",
"(",
"-",
"1",
")",
",",
"tau",
"=",
"1",
",",
"hard",
"=",
"True",
")",
"discrete_a",
"=",
"discrete_a",
".",
"reshape",
"(",
"-",
"1",
",",
"len",
"(",
"PRIMITIVES",
")",
"-",
"1",
")",
"reserved_edge",
"=",
"(",
"discrete_a",
">",
"0",
")",
".",
"nonzero",
"(",
")",
"node_gene",
"=",
"[",
"]",
"node_idx",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"reserved_edge",
".",
"shape",
"[",
"0",
"]",
")",
":",
"edge_idx",
"=",
"reserved_edge",
"[",
"i",
"]",
"[",
"0",
"]",
".",
"item",
"(",
")",
"prim_idx",
"=",
"reserved_edge",
"[",
"i",
"]",
"[",
"1",
"]",
".",
"item",
"(",
")",
"prim",
"=",
"PRIMITIVES",
"[",
"prim_idx",
"]",
"node_gene",
".",
"append",
"(",
"(",
"prim",
",",
"edge_idx",
")",
")",
"node_idx",
".",
"append",
"(",
"(",
"edge_idx",
",",
"prim_idx",
")",
")",
"gene",
".",
"append",
"(",
"node_gene",
")",
"connect_idx",
".",
"append",
"(",
"node_idx",
")",
"return",
"gene",
",",
"connect_idx"
] | [
112,
0
] | [
165,
28
] | python | en | ['en', 'error', 'th'] | False |
test_basic_usage | (hass, tmpdir) | Test we can setup and the service is registered. | Test we can setup and the service is registered. | async def test_basic_usage(hass, tmpdir):
"""Test we can setup and the service is registered."""
test_dir = tmpdir.mkdir("profiles")
await setup.async_setup_component(hass, "persistent_notification", {})
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(DOMAIN, SERVICE_START)
last_filename = None
def _mock_path(filename):
nonlocal last_filename
last_filename = f"{test_dir}/{filename}"
return last_filename
with patch("homeassistant.components.profiler.cProfile.Profile"), patch.object(
hass.config, "path", _mock_path
):
await hass.services.async_call(DOMAIN, SERVICE_START, {CONF_SECONDS: 0.000001})
await hass.async_block_till_done()
assert os.path.exists(last_filename)
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done() | [
"async",
"def",
"test_basic_usage",
"(",
"hass",
",",
"tmpdir",
")",
":",
"test_dir",
"=",
"tmpdir",
".",
"mkdir",
"(",
"\"profiles\"",
")",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"DOMAIN",
",",
"SERVICE_START",
")",
"last_filename",
"=",
"None",
"def",
"_mock_path",
"(",
"filename",
")",
":",
"nonlocal",
"last_filename",
"last_filename",
"=",
"f\"{test_dir}/{filename}\"",
"return",
"last_filename",
"with",
"patch",
"(",
"\"homeassistant.components.profiler.cProfile.Profile\"",
")",
",",
"patch",
".",
"object",
"(",
"hass",
".",
"config",
",",
"\"path\"",
",",
"_mock_path",
")",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_START",
",",
"{",
"CONF_SECONDS",
":",
"0.000001",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"last_filename",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
22,
0
] | [
51,
38
] | python | en | ['en', 'en', 'en'] | True |
test_memory_usage | (hass, tmpdir) | Test we can setup and the service is registered. | Test we can setup and the service is registered. | async def test_memory_usage(hass, tmpdir):
"""Test we can setup and the service is registered."""
test_dir = tmpdir.mkdir("profiles")
await setup.async_setup_component(hass, "persistent_notification", {})
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(DOMAIN, SERVICE_MEMORY)
last_filename = None
def _mock_path(filename):
nonlocal last_filename
last_filename = f"{test_dir}/{filename}"
return last_filename
with patch("homeassistant.components.profiler.hpy") as mock_hpy, patch.object(
hass.config, "path", _mock_path
):
await hass.services.async_call(DOMAIN, SERVICE_MEMORY, {CONF_SECONDS: 0.000001})
await hass.async_block_till_done()
mock_hpy.assert_called_once()
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done() | [
"async",
"def",
"test_memory_usage",
"(",
"hass",
",",
"tmpdir",
")",
":",
"test_dir",
"=",
"tmpdir",
".",
"mkdir",
"(",
"\"profiles\"",
")",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"DOMAIN",
",",
"SERVICE_MEMORY",
")",
"last_filename",
"=",
"None",
"def",
"_mock_path",
"(",
"filename",
")",
":",
"nonlocal",
"last_filename",
"last_filename",
"=",
"f\"{test_dir}/{filename}\"",
"return",
"last_filename",
"with",
"patch",
"(",
"\"homeassistant.components.profiler.hpy\"",
")",
"as",
"mock_hpy",
",",
"patch",
".",
"object",
"(",
"hass",
".",
"config",
",",
"\"path\"",
",",
"_mock_path",
")",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_MEMORY",
",",
"{",
"CONF_SECONDS",
":",
"0.000001",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"mock_hpy",
".",
"assert_called_once",
"(",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
54,
0
] | [
83,
38
] | python | en | ['en', 'en', 'en'] | True |
test_object_growth_logging | (hass, caplog) | Test we can setup and the service and we can dump objects to the log. | Test we can setup and the service and we can dump objects to the log. | async def test_object_growth_logging(hass, caplog):
"""Test we can setup and the service and we can dump objects to the log."""
await setup.async_setup_component(hass, "persistent_notification", {})
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(DOMAIN, SERVICE_START_LOG_OBJECTS)
assert hass.services.has_service(DOMAIN, SERVICE_STOP_LOG_OBJECTS)
await hass.services.async_call(
DOMAIN, SERVICE_START_LOG_OBJECTS, {CONF_SCAN_INTERVAL: 10}
)
await hass.async_block_till_done()
assert "Growth" in caplog.text
caplog.clear()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=11))
await hass.async_block_till_done()
assert "Growth" in caplog.text
await hass.services.async_call(DOMAIN, SERVICE_STOP_LOG_OBJECTS, {})
await hass.async_block_till_done()
caplog.clear()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=21))
await hass.async_block_till_done()
assert "Growth" not in caplog.text
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=31))
await hass.async_block_till_done()
assert "Growth" not in caplog.text | [
"async",
"def",
"test_object_growth_logging",
"(",
"hass",
",",
"caplog",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"DOMAIN",
",",
"SERVICE_START_LOG_OBJECTS",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"DOMAIN",
",",
"SERVICE_STOP_LOG_OBJECTS",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_START_LOG_OBJECTS",
",",
"{",
"CONF_SCAN_INTERVAL",
":",
"10",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Growth\"",
"in",
"caplog",
".",
"text",
"caplog",
".",
"clear",
"(",
")",
"async_fire_time_changed",
"(",
"hass",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"11",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Growth\"",
"in",
"caplog",
".",
"text",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_STOP_LOG_OBJECTS",
",",
"{",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"caplog",
".",
"clear",
"(",
")",
"async_fire_time_changed",
"(",
"hass",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"21",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Growth\"",
"not",
"in",
"caplog",
".",
"text",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"async_fire_time_changed",
"(",
"hass",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"31",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Growth\"",
"not",
"in",
"caplog",
".",
"text"
] | [
86,
0
] | [
124,
38
] | python | en | ['en', 'en', 'en'] | True |
test_dump_log_object | (hass, caplog) | Test we can setup and the service is registered and logging works. | Test we can setup and the service is registered and logging works. | async def test_dump_log_object(hass, caplog):
"""Test we can setup and the service is registered and logging works."""
await setup.async_setup_component(hass, "persistent_notification", {})
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(DOMAIN, SERVICE_DUMP_LOG_OBJECTS)
await hass.services.async_call(
DOMAIN, SERVICE_DUMP_LOG_OBJECTS, {CONF_TYPE: "MockConfigEntry"}
)
await hass.async_block_till_done()
assert "MockConfigEntry" in caplog.text
caplog.clear()
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done() | [
"async",
"def",
"test_dump_log_object",
"(",
"hass",
",",
"caplog",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"hass",
".",
"services",
".",
"has_service",
"(",
"DOMAIN",
",",
"SERVICE_DUMP_LOG_OBJECTS",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_DUMP_LOG_OBJECTS",
",",
"{",
"CONF_TYPE",
":",
"\"MockConfigEntry\"",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"MockConfigEntry\"",
"in",
"caplog",
".",
"text",
"caplog",
".",
"clear",
"(",
")",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
127,
0
] | [
148,
38
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry, async_add_entities) | Add an solarEdge entry. | Add an solarEdge entry. | async def async_setup_entry(hass, entry, async_add_entities):
"""Add an solarEdge entry."""
# Add the needed sensors to hass
api = solaredge.Solaredge(entry.data[CONF_API_KEY])
# Check if api can be reached and site is active
try:
response = await hass.async_add_executor_job(
api.get_details, entry.data[CONF_SITE_ID]
)
if response["details"]["status"].lower() != "active":
_LOGGER.error("SolarEdge site is not active")
return
_LOGGER.debug("Credentials correct and site is active")
except KeyError:
_LOGGER.error("Missing details data in SolarEdge response")
return
except (ConnectTimeout, HTTPError):
_LOGGER.error("Could not retrieve details from SolarEdge API")
return
sensor_factory = SolarEdgeSensorFactory(entry.title, entry.data[CONF_SITE_ID], api)
entities = []
for sensor_key in SENSOR_TYPES:
sensor = sensor_factory.create_sensor(sensor_key)
if sensor is not None:
entities.append(sensor)
async_add_entities(entities) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
")",
":",
"# Add the needed sensors to hass",
"api",
"=",
"solaredge",
".",
"Solaredge",
"(",
"entry",
".",
"data",
"[",
"CONF_API_KEY",
"]",
")",
"# Check if api can be reached and site is active",
"try",
":",
"response",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"api",
".",
"get_details",
",",
"entry",
".",
"data",
"[",
"CONF_SITE_ID",
"]",
")",
"if",
"response",
"[",
"\"details\"",
"]",
"[",
"\"status\"",
"]",
".",
"lower",
"(",
")",
"!=",
"\"active\"",
":",
"_LOGGER",
".",
"error",
"(",
"\"SolarEdge site is not active\"",
")",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Credentials correct and site is active\"",
")",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing details data in SolarEdge response\"",
")",
"return",
"except",
"(",
"ConnectTimeout",
",",
"HTTPError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not retrieve details from SolarEdge API\"",
")",
"return",
"sensor_factory",
"=",
"SolarEdgeSensorFactory",
"(",
"entry",
".",
"title",
",",
"entry",
".",
"data",
"[",
"CONF_SITE_ID",
"]",
",",
"api",
")",
"entities",
"=",
"[",
"]",
"for",
"sensor_key",
"in",
"SENSOR_TYPES",
":",
"sensor",
"=",
"sensor_factory",
".",
"create_sensor",
"(",
"sensor_key",
")",
"if",
"sensor",
"is",
"not",
"None",
":",
"entities",
".",
"append",
"(",
"sensor",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
25,
0
] | [
52,
32
] | python | en | ['en', 'cy', 'en'] | True |
SolarEdgeSensorFactory.__init__ | (self, platform_name, site_id, api) | Initialize the factory. | Initialize the factory. | def __init__(self, platform_name, site_id, api):
"""Initialize the factory."""
self.platform_name = platform_name
details = SolarEdgeDetailsDataService(api, site_id)
overview = SolarEdgeOverviewDataService(api, site_id)
inventory = SolarEdgeInventoryDataService(api, site_id)
flow = SolarEdgePowerFlowDataService(api, site_id)
energy = SolarEdgeEnergyDetailsService(api, site_id)
self.services = {"site_details": (SolarEdgeDetailsSensor, details)}
for key in [
"lifetime_energy",
"energy_this_year",
"energy_this_month",
"energy_today",
"current_power",
]:
self.services[key] = (SolarEdgeOverviewSensor, overview)
for key in ["meters", "sensors", "gateways", "batteries", "inverters"]:
self.services[key] = (SolarEdgeInventorySensor, inventory)
for key in ["power_consumption", "solar_power", "grid_power", "storage_power"]:
self.services[key] = (SolarEdgePowerFlowSensor, flow)
for key in ["storage_level"]:
self.services[key] = (SolarEdgeStorageLevelSensor, flow)
for key in [
"purchased_power",
"production_power",
"feedin_power",
"consumption_power",
"selfconsumption_power",
]:
self.services[key] = (SolarEdgeEnergyDetailsSensor, energy) | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"site_id",
",",
"api",
")",
":",
"self",
".",
"platform_name",
"=",
"platform_name",
"details",
"=",
"SolarEdgeDetailsDataService",
"(",
"api",
",",
"site_id",
")",
"overview",
"=",
"SolarEdgeOverviewDataService",
"(",
"api",
",",
"site_id",
")",
"inventory",
"=",
"SolarEdgeInventoryDataService",
"(",
"api",
",",
"site_id",
")",
"flow",
"=",
"SolarEdgePowerFlowDataService",
"(",
"api",
",",
"site_id",
")",
"energy",
"=",
"SolarEdgeEnergyDetailsService",
"(",
"api",
",",
"site_id",
")",
"self",
".",
"services",
"=",
"{",
"\"site_details\"",
":",
"(",
"SolarEdgeDetailsSensor",
",",
"details",
")",
"}",
"for",
"key",
"in",
"[",
"\"lifetime_energy\"",
",",
"\"energy_this_year\"",
",",
"\"energy_this_month\"",
",",
"\"energy_today\"",
",",
"\"current_power\"",
",",
"]",
":",
"self",
".",
"services",
"[",
"key",
"]",
"=",
"(",
"SolarEdgeOverviewSensor",
",",
"overview",
")",
"for",
"key",
"in",
"[",
"\"meters\"",
",",
"\"sensors\"",
",",
"\"gateways\"",
",",
"\"batteries\"",
",",
"\"inverters\"",
"]",
":",
"self",
".",
"services",
"[",
"key",
"]",
"=",
"(",
"SolarEdgeInventorySensor",
",",
"inventory",
")",
"for",
"key",
"in",
"[",
"\"power_consumption\"",
",",
"\"solar_power\"",
",",
"\"grid_power\"",
",",
"\"storage_power\"",
"]",
":",
"self",
".",
"services",
"[",
"key",
"]",
"=",
"(",
"SolarEdgePowerFlowSensor",
",",
"flow",
")",
"for",
"key",
"in",
"[",
"\"storage_level\"",
"]",
":",
"self",
".",
"services",
"[",
"key",
"]",
"=",
"(",
"SolarEdgeStorageLevelSensor",
",",
"flow",
")",
"for",
"key",
"in",
"[",
"\"purchased_power\"",
",",
"\"production_power\"",
",",
"\"feedin_power\"",
",",
"\"consumption_power\"",
",",
"\"selfconsumption_power\"",
",",
"]",
":",
"self",
".",
"services",
"[",
"key",
"]",
"=",
"(",
"SolarEdgeEnergyDetailsSensor",
",",
"energy",
")"
] | [
58,
4
] | [
95,
71
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeSensorFactory.create_sensor | (self, sensor_key) | Create and return a sensor based on the sensor_key. | Create and return a sensor based on the sensor_key. | def create_sensor(self, sensor_key):
"""Create and return a sensor based on the sensor_key."""
sensor_class, service = self.services[sensor_key]
return sensor_class(self.platform_name, sensor_key, service) | [
"def",
"create_sensor",
"(",
"self",
",",
"sensor_key",
")",
":",
"sensor_class",
",",
"service",
"=",
"self",
".",
"services",
"[",
"sensor_key",
"]",
"return",
"sensor_class",
"(",
"self",
".",
"platform_name",
",",
"sensor_key",
",",
"service",
")"
] | [
97,
4
] | [
101,
68
] | python | en | ['en', 'haw', 'en'] | True |
SolarEdgeSensor.__init__ | (self, platform_name, sensor_key, data_service) | Initialize the sensor. | Initialize the sensor. | def __init__(self, platform_name, sensor_key, data_service):
"""Initialize the sensor."""
self.platform_name = platform_name
self.sensor_key = sensor_key
self.data_service = data_service
self._state = None
self._unit_of_measurement = SENSOR_TYPES[self.sensor_key][2]
self._icon = SENSOR_TYPES[self.sensor_key][3] | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
":",
"self",
".",
"platform_name",
"=",
"platform_name",
"self",
".",
"sensor_key",
"=",
"sensor_key",
"self",
".",
"data_service",
"=",
"data_service",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_unit_of_measurement",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"2",
"]",
"self",
".",
"_icon",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"3",
"]"
] | [
107,
4
] | [
116,
53
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeSensor.name | (self) | Return the name. | Return the name. | def name(self):
"""Return the name."""
return "{} ({})".format(self.platform_name, SENSOR_TYPES[self.sensor_key][1]) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"\"{} ({})\"",
".",
"format",
"(",
"self",
".",
"platform_name",
",",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"1",
"]",
")"
] | [
119,
4
] | [
121,
85
] | python | en | ['en', 'ig', 'en'] | True |
SolarEdgeSensor.unit_of_measurement | (self) | Return the unit of measurement. | Return the unit of measurement. | def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
124,
4
] | [
126,
40
] | python | en | ['en', 'la', 'en'] | True |
SolarEdgeSensor.icon | (self) | Return the sensor icon. | Return the sensor icon. | def icon(self):
"""Return the sensor icon."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
129,
4
] | [
131,
25
] | python | en | ['en', 'fa', 'en'] | True |
SolarEdgeSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
134,
4
] | [
136,
26
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeOverviewSensor.__init__ | (self, platform_name, sensor_key, data_service) | Initialize the overview sensor. | Initialize the overview sensor. | def __init__(self, platform_name, sensor_key, data_service):
"""Initialize the overview sensor."""
super().__init__(platform_name, sensor_key, data_service)
self._json_key = SENSOR_TYPES[self.sensor_key][0] | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
"self",
".",
"_json_key",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"0",
"]"
] | [
142,
4
] | [
146,
57
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeOverviewSensor.update | (self) | Get the latest data from the sensor and update the state. | Get the latest data from the sensor and update the state. | def update(self):
"""Get the latest data from the sensor and update the state."""
self.data_service.update()
self._state = self.data_service.data.get(self._json_key) | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"data_service",
".",
"update",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"data_service",
".",
"data",
".",
"get",
"(",
"self",
".",
"_json_key",
")"
] | [
148,
4
] | [
151,
64
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeDetailsSensor.__init__ | (self, platform_name, sensor_key, data_service) | Initialize the details sensor. | Initialize the details sensor. | def __init__(self, platform_name, sensor_key, data_service):
"""Initialize the details sensor."""
super().__init__(platform_name, sensor_key, data_service)
self._attributes = {} | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
"self",
".",
"_attributes",
"=",
"{",
"}"
] | [
157,
4
] | [
161,
29
] | python | en | ['en', 'fr', 'en'] | True |
SolarEdgeDetailsSensor.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"
] | [
164,
4
] | [
166,
31
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeDetailsSensor.update | (self) | Get the latest details and update state and attributes. | Get the latest details and update state and attributes. | def update(self):
"""Get the latest details and update state and attributes."""
self.data_service.update()
self._state = self.data_service.data
self._attributes = self.data_service.attributes | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"data_service",
".",
"update",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"data_service",
".",
"data",
"self",
".",
"_attributes",
"=",
"self",
".",
"data_service",
".",
"attributes"
] | [
168,
4
] | [
172,
55
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeInventorySensor.__init__ | (self, platform_name, sensor_key, data_service) | Initialize the inventory sensor. | Initialize the inventory sensor. | def __init__(self, platform_name, sensor_key, data_service):
"""Initialize the inventory sensor."""
super().__init__(platform_name, sensor_key, data_service)
self._json_key = SENSOR_TYPES[self.sensor_key][0]
self._attributes = {} | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
"self",
".",
"_json_key",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"0",
"]",
"self",
".",
"_attributes",
"=",
"{",
"}"
] | [
178,
4
] | [
184,
29
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeInventorySensor.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"
] | [
187,
4
] | [
189,
31
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeInventorySensor.update | (self) | Get the latest inventory data and update state and attributes. | Get the latest inventory data and update state and attributes. | def update(self):
"""Get the latest inventory data and update state and attributes."""
self.data_service.update()
self._state = self.data_service.data.get(self._json_key)
self._attributes = self.data_service.attributes.get(self._json_key) | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"data_service",
".",
"update",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"data_service",
".",
"data",
".",
"get",
"(",
"self",
".",
"_json_key",
")",
"self",
".",
"_attributes",
"=",
"self",
".",
"data_service",
".",
"attributes",
".",
"get",
"(",
"self",
".",
"_json_key",
")"
] | [
191,
4
] | [
195,
75
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeEnergyDetailsSensor.__init__ | (self, platform_name, sensor_key, data_service) | Initialize the power flow sensor. | Initialize the power flow sensor. | def __init__(self, platform_name, sensor_key, data_service):
"""Initialize the power flow sensor."""
super().__init__(platform_name, sensor_key, data_service)
self._json_key = SENSOR_TYPES[self.sensor_key][0]
self._attributes = {} | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
"self",
".",
"_json_key",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"0",
"]",
"self",
".",
"_attributes",
"=",
"{",
"}"
] | [
201,
4
] | [
207,
29
] | python | en | ['en', 'pl', 'en'] | True |
SolarEdgeEnergyDetailsSensor.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"
] | [
210,
4
] | [
212,
31
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeEnergyDetailsSensor.update | (self) | Get the latest inventory data and update state and attributes. | Get the latest inventory data and update state and attributes. | def update(self):
"""Get the latest inventory data and update state and attributes."""
self.data_service.update()
self._state = self.data_service.data.get(self._json_key)
self._attributes = self.data_service.attributes.get(self._json_key)
self._unit_of_measurement = self.data_service.unit | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"data_service",
".",
"update",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"data_service",
".",
"data",
".",
"get",
"(",
"self",
".",
"_json_key",
")",
"self",
".",
"_attributes",
"=",
"self",
".",
"data_service",
".",
"attributes",
".",
"get",
"(",
"self",
".",
"_json_key",
")",
"self",
".",
"_unit_of_measurement",
"=",
"self",
".",
"data_service",
".",
"unit"
] | [
214,
4
] | [
219,
58
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgePowerFlowSensor.__init__ | (self, platform_name, sensor_key, data_service) | Initialize the power flow sensor. | Initialize the power flow sensor. | def __init__(self, platform_name, sensor_key, data_service):
"""Initialize the power flow sensor."""
super().__init__(platform_name, sensor_key, data_service)
self._json_key = SENSOR_TYPES[self.sensor_key][0]
self._attributes = {} | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
"self",
".",
"_json_key",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"0",
"]",
"self",
".",
"_attributes",
"=",
"{",
"}"
] | [
225,
4
] | [
231,
29
] | python | en | ['en', 'pl', 'en'] | True |
SolarEdgePowerFlowSensor.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"
] | [
234,
4
] | [
236,
31
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgePowerFlowSensor.device_class | (self) | Device Class. | Device Class. | def device_class(self):
"""Device Class."""
return DEVICE_CLASS_POWER | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_POWER"
] | [
239,
4
] | [
241,
33
] | python | en | ['en', 'zh', 'en'] | False |
SolarEdgePowerFlowSensor.update | (self) | Get the latest inventory data and update state and attributes. | Get the latest inventory data and update state and attributes. | def update(self):
"""Get the latest inventory data and update state and attributes."""
self.data_service.update()
self._state = self.data_service.data.get(self._json_key)
self._attributes = self.data_service.attributes.get(self._json_key)
self._unit_of_measurement = self.data_service.unit | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"data_service",
".",
"update",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"data_service",
".",
"data",
".",
"get",
"(",
"self",
".",
"_json_key",
")",
"self",
".",
"_attributes",
"=",
"self",
".",
"data_service",
".",
"attributes",
".",
"get",
"(",
"self",
".",
"_json_key",
")",
"self",
".",
"_unit_of_measurement",
"=",
"self",
".",
"data_service",
".",
"unit"
] | [
243,
4
] | [
248,
58
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeStorageLevelSensor.__init__ | (self, platform_name, sensor_key, data_service) | Initialize the storage level sensor. | Initialize the storage level sensor. | def __init__(self, platform_name, sensor_key, data_service):
"""Initialize the storage level sensor."""
super().__init__(platform_name, sensor_key, data_service)
self._json_key = SENSOR_TYPES[self.sensor_key][0] | [
"def",
"__init__",
"(",
"self",
",",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"platform_name",
",",
"sensor_key",
",",
"data_service",
")",
"self",
".",
"_json_key",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"sensor_key",
"]",
"[",
"0",
"]"
] | [
254,
4
] | [
258,
57
] | python | en | ['en', 'zu', 'en'] | True |
SolarEdgeStorageLevelSensor.device_class | (self) | Return the device_class of the device. | Return the device_class of the device. | def device_class(self):
"""Return the device_class of the device."""
return DEVICE_CLASS_BATTERY | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_BATTERY"
] | [
261,
4
] | [
263,
35
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeStorageLevelSensor.update | (self) | Get the latest inventory data and update state and attributes. | Get the latest inventory data and update state and attributes. | def update(self):
"""Get the latest inventory data and update state and attributes."""
self.data_service.update()
attr = self.data_service.attributes.get(self._json_key)
if attr and "soc" in attr:
self._state = attr["soc"] | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"data_service",
".",
"update",
"(",
")",
"attr",
"=",
"self",
".",
"data_service",
".",
"attributes",
".",
"get",
"(",
"self",
".",
"_json_key",
")",
"if",
"attr",
"and",
"\"soc\"",
"in",
"attr",
":",
"self",
".",
"_state",
"=",
"attr",
"[",
"\"soc\"",
"]"
] | [
265,
4
] | [
270,
37
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeDataService.__init__ | (self, api, site_id) | Initialize the data object. | Initialize the data object. | def __init__(self, api, site_id):
"""Initialize the data object."""
self.api = api
self.site_id = site_id
self.data = {}
self.attributes = {} | [
"def",
"__init__",
"(",
"self",
",",
"api",
",",
"site_id",
")",
":",
"self",
".",
"api",
"=",
"api",
"self",
".",
"site_id",
"=",
"site_id",
"self",
".",
"data",
"=",
"{",
"}",
"self",
".",
"attributes",
"=",
"{",
"}"
] | [
276,
4
] | [
282,
28
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeOverviewDataService.update | (self) | Update the data from the SolarEdge Monitoring API. | Update the data from the SolarEdge Monitoring API. | def update(self):
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_overview(self.site_id)
overview = data["overview"]
except KeyError:
_LOGGER.error("Missing overview data, skipping update")
return
except (ConnectTimeout, HTTPError):
_LOGGER.error("Could not retrieve data, skipping update")
return
self.data = {}
for key, value in overview.items():
if key in ["lifeTimeData", "lastYearData", "lastMonthData", "lastDayData"]:
data = value["energy"]
elif key in ["currentPower"]:
data = value["power"]
else:
data = value
self.data[key] = data
_LOGGER.debug("Updated SolarEdge overview: %s", self.data) | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"api",
".",
"get_overview",
"(",
"self",
".",
"site_id",
")",
"overview",
"=",
"data",
"[",
"\"overview\"",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing overview data, skipping update\"",
")",
"return",
"except",
"(",
"ConnectTimeout",
",",
"HTTPError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not retrieve data, skipping update\"",
")",
"return",
"self",
".",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"overview",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"[",
"\"lifeTimeData\"",
",",
"\"lastYearData\"",
",",
"\"lastMonthData\"",
",",
"\"lastDayData\"",
"]",
":",
"data",
"=",
"value",
"[",
"\"energy\"",
"]",
"elif",
"key",
"in",
"[",
"\"currentPower\"",
"]",
":",
"data",
"=",
"value",
"[",
"\"power\"",
"]",
"else",
":",
"data",
"=",
"value",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"data",
"_LOGGER",
".",
"debug",
"(",
"\"Updated SolarEdge overview: %s\"",
",",
"self",
".",
"data",
")"
] | [
289,
4
] | [
312,
66
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeDetailsDataService.__init__ | (self, api, site_id) | Initialize the details data service. | Initialize the details data service. | def __init__(self, api, site_id):
"""Initialize the details data service."""
super().__init__(api, site_id)
self.data = None | [
"def",
"__init__",
"(",
"self",
",",
"api",
",",
"site_id",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"api",
",",
"site_id",
")",
"self",
".",
"data",
"=",
"None"
] | [
318,
4
] | [
322,
24
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeDetailsDataService.update | (self) | Update the data from the SolarEdge Monitoring API. | Update the data from the SolarEdge Monitoring API. | def update(self):
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_details(self.site_id)
details = data["details"]
except KeyError:
_LOGGER.error("Missing details data, skipping update")
return
except (ConnectTimeout, HTTPError):
_LOGGER.error("Could not retrieve data, skipping update")
return
self.data = None
self.attributes = {}
for key, value in details.items():
key = snakecase(key)
if key in ["primary_module"]:
for module_key, module_value in value.items():
self.attributes[snakecase(module_key)] = module_value
elif key in [
"peak_power",
"type",
"name",
"last_update_time",
"installation_date",
]:
self.attributes[key] = value
elif key == "status":
self.data = value
_LOGGER.debug("Updated SolarEdge details: %s, %s", self.data, self.attributes) | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"api",
".",
"get_details",
"(",
"self",
".",
"site_id",
")",
"details",
"=",
"data",
"[",
"\"details\"",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing details data, skipping update\"",
")",
"return",
"except",
"(",
"ConnectTimeout",
",",
"HTTPError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not retrieve data, skipping update\"",
")",
"return",
"self",
".",
"data",
"=",
"None",
"self",
".",
"attributes",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"details",
".",
"items",
"(",
")",
":",
"key",
"=",
"snakecase",
"(",
"key",
")",
"if",
"key",
"in",
"[",
"\"primary_module\"",
"]",
":",
"for",
"module_key",
",",
"module_value",
"in",
"value",
".",
"items",
"(",
")",
":",
"self",
".",
"attributes",
"[",
"snakecase",
"(",
"module_key",
")",
"]",
"=",
"module_value",
"elif",
"key",
"in",
"[",
"\"peak_power\"",
",",
"\"type\"",
",",
"\"name\"",
",",
"\"last_update_time\"",
",",
"\"installation_date\"",
",",
"]",
":",
"self",
".",
"attributes",
"[",
"key",
"]",
"=",
"value",
"elif",
"key",
"==",
"\"status\"",
":",
"self",
".",
"data",
"=",
"value",
"_LOGGER",
".",
"debug",
"(",
"\"Updated SolarEdge details: %s, %s\"",
",",
"self",
".",
"data",
",",
"self",
".",
"attributes",
")"
] | [
325,
4
] | [
358,
86
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeInventoryDataService.update | (self) | Update the data from the SolarEdge Monitoring API. | Update the data from the SolarEdge Monitoring API. | def update(self):
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_inventory(self.site_id)
inventory = data["Inventory"]
except KeyError:
_LOGGER.error("Missing inventory data, skipping update")
return
except (ConnectTimeout, HTTPError):
_LOGGER.error("Could not retrieve data, skipping update")
return
self.data = {}
self.attributes = {}
for key, value in inventory.items():
self.data[key] = len(value)
self.attributes[key] = {key: value}
_LOGGER.debug("Updated SolarEdge inventory: %s, %s", self.data, self.attributes) | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"api",
".",
"get_inventory",
"(",
"self",
".",
"site_id",
")",
"inventory",
"=",
"data",
"[",
"\"Inventory\"",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing inventory data, skipping update\"",
")",
"return",
"except",
"(",
"ConnectTimeout",
",",
"HTTPError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not retrieve data, skipping update\"",
")",
"return",
"self",
".",
"data",
"=",
"{",
"}",
"self",
".",
"attributes",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"inventory",
".",
"items",
"(",
")",
":",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"len",
"(",
"value",
")",
"self",
".",
"attributes",
"[",
"key",
"]",
"=",
"{",
"key",
":",
"value",
"}",
"_LOGGER",
".",
"debug",
"(",
"\"Updated SolarEdge inventory: %s, %s\"",
",",
"self",
".",
"data",
",",
"self",
".",
"attributes",
")"
] | [
365,
4
] | [
384,
88
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeEnergyDetailsService.__init__ | (self, api, site_id) | Initialize the power flow data service. | Initialize the power flow data service. | def __init__(self, api, site_id):
"""Initialize the power flow data service."""
super().__init__(api, site_id)
self.unit = None | [
"def",
"__init__",
"(",
"self",
",",
"api",
",",
"site_id",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"api",
",",
"site_id",
")",
"self",
".",
"unit",
"=",
"None"
] | [
390,
4
] | [
394,
24
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgeEnergyDetailsService.update | (self) | Update the data from the SolarEdge Monitoring API. | Update the data from the SolarEdge Monitoring API. | def update(self):
"""Update the data from the SolarEdge Monitoring API."""
try:
now = datetime.now()
today = date.today()
midnight = datetime.combine(today, datetime.min.time())
data = self.api.get_energy_details(
self.site_id,
midnight,
now.strftime("%Y-%m-%d %H:%M:%S"),
meters=None,
time_unit="DAY",
)
energy_details = data["energyDetails"]
except KeyError:
_LOGGER.error("Missing power flow data, skipping update")
return
except (ConnectTimeout, HTTPError):
_LOGGER.error("Could not retrieve data, skipping update")
return
if "meters" not in energy_details:
_LOGGER.debug(
"Missing meters in energy details data. Assuming site does not have any"
)
return
self.data = {}
self.attributes = {}
self.unit = energy_details["unit"]
meters = energy_details["meters"]
for entity in meters:
for key, data in entity.items():
if key == "type" and data in [
"Production",
"SelfConsumption",
"FeedIn",
"Purchased",
"Consumption",
]:
energy_type = data
if key == "values":
for row in data:
self.data[energy_type] = row["value"]
self.attributes[energy_type] = {"date": row["date"]}
_LOGGER.debug(
"Updated SolarEdge energy details: %s, %s", self.data, self.attributes
) | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"today",
"=",
"date",
".",
"today",
"(",
")",
"midnight",
"=",
"datetime",
".",
"combine",
"(",
"today",
",",
"datetime",
".",
"min",
".",
"time",
"(",
")",
")",
"data",
"=",
"self",
".",
"api",
".",
"get_energy_details",
"(",
"self",
".",
"site_id",
",",
"midnight",
",",
"now",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"",
")",
",",
"meters",
"=",
"None",
",",
"time_unit",
"=",
"\"DAY\"",
",",
")",
"energy_details",
"=",
"data",
"[",
"\"energyDetails\"",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing power flow data, skipping update\"",
")",
"return",
"except",
"(",
"ConnectTimeout",
",",
"HTTPError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not retrieve data, skipping update\"",
")",
"return",
"if",
"\"meters\"",
"not",
"in",
"energy_details",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Missing meters in energy details data. Assuming site does not have any\"",
")",
"return",
"self",
".",
"data",
"=",
"{",
"}",
"self",
".",
"attributes",
"=",
"{",
"}",
"self",
".",
"unit",
"=",
"energy_details",
"[",
"\"unit\"",
"]",
"meters",
"=",
"energy_details",
"[",
"\"meters\"",
"]",
"for",
"entity",
"in",
"meters",
":",
"for",
"key",
",",
"data",
"in",
"entity",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"\"type\"",
"and",
"data",
"in",
"[",
"\"Production\"",
",",
"\"SelfConsumption\"",
",",
"\"FeedIn\"",
",",
"\"Purchased\"",
",",
"\"Consumption\"",
",",
"]",
":",
"energy_type",
"=",
"data",
"if",
"key",
"==",
"\"values\"",
":",
"for",
"row",
"in",
"data",
":",
"self",
".",
"data",
"[",
"energy_type",
"]",
"=",
"row",
"[",
"\"value\"",
"]",
"self",
".",
"attributes",
"[",
"energy_type",
"]",
"=",
"{",
"\"date\"",
":",
"row",
"[",
"\"date\"",
"]",
"}",
"_LOGGER",
".",
"debug",
"(",
"\"Updated SolarEdge energy details: %s, %s\"",
",",
"self",
".",
"data",
",",
"self",
".",
"attributes",
")"
] | [
397,
4
] | [
446,
9
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgePowerFlowDataService.__init__ | (self, api, site_id) | Initialize the power flow data service. | Initialize the power flow data service. | def __init__(self, api, site_id):
"""Initialize the power flow data service."""
super().__init__(api, site_id)
self.unit = None | [
"def",
"__init__",
"(",
"self",
",",
"api",
",",
"site_id",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"api",
",",
"site_id",
")",
"self",
".",
"unit",
"=",
"None"
] | [
452,
4
] | [
456,
24
] | python | en | ['en', 'en', 'en'] | True |
SolarEdgePowerFlowDataService.update | (self) | Update the data from the SolarEdge Monitoring API. | Update the data from the SolarEdge Monitoring API. | def update(self):
"""Update the data from the SolarEdge Monitoring API."""
try:
data = self.api.get_current_power_flow(self.site_id)
power_flow = data["siteCurrentPowerFlow"]
except KeyError:
_LOGGER.error("Missing power flow data, skipping update")
return
except (ConnectTimeout, HTTPError):
_LOGGER.error("Could not retrieve data, skipping update")
return
power_from = []
power_to = []
if "connections" not in power_flow:
_LOGGER.debug(
"Missing connections in power flow data. Assuming site does not have any"
)
return
for connection in power_flow["connections"]:
power_from.append(connection["from"].lower())
power_to.append(connection["to"].lower())
self.data = {}
self.attributes = {}
self.unit = power_flow["unit"]
for key, value in power_flow.items():
if key in ["LOAD", "PV", "GRID", "STORAGE"]:
self.data[key] = value["currentPower"]
self.attributes[key] = {"status": value["status"]}
if key in ["GRID"]:
export = key.lower() in power_to
self.data[key] *= -1 if export else 1
self.attributes[key]["flow"] = "export" if export else "import"
if key in ["STORAGE"]:
charge = key.lower() in power_to
self.data[key] *= -1 if charge else 1
self.attributes[key]["flow"] = "charge" if charge else "discharge"
self.attributes[key]["soc"] = value["chargeLevel"]
_LOGGER.debug(
"Updated SolarEdge power flow: %s, %s", self.data, self.attributes
) | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"api",
".",
"get_current_power_flow",
"(",
"self",
".",
"site_id",
")",
"power_flow",
"=",
"data",
"[",
"\"siteCurrentPowerFlow\"",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing power flow data, skipping update\"",
")",
"return",
"except",
"(",
"ConnectTimeout",
",",
"HTTPError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not retrieve data, skipping update\"",
")",
"return",
"power_from",
"=",
"[",
"]",
"power_to",
"=",
"[",
"]",
"if",
"\"connections\"",
"not",
"in",
"power_flow",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Missing connections in power flow data. Assuming site does not have any\"",
")",
"return",
"for",
"connection",
"in",
"power_flow",
"[",
"\"connections\"",
"]",
":",
"power_from",
".",
"append",
"(",
"connection",
"[",
"\"from\"",
"]",
".",
"lower",
"(",
")",
")",
"power_to",
".",
"append",
"(",
"connection",
"[",
"\"to\"",
"]",
".",
"lower",
"(",
")",
")",
"self",
".",
"data",
"=",
"{",
"}",
"self",
".",
"attributes",
"=",
"{",
"}",
"self",
".",
"unit",
"=",
"power_flow",
"[",
"\"unit\"",
"]",
"for",
"key",
",",
"value",
"in",
"power_flow",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"[",
"\"LOAD\"",
",",
"\"PV\"",
",",
"\"GRID\"",
",",
"\"STORAGE\"",
"]",
":",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"value",
"[",
"\"currentPower\"",
"]",
"self",
".",
"attributes",
"[",
"key",
"]",
"=",
"{",
"\"status\"",
":",
"value",
"[",
"\"status\"",
"]",
"}",
"if",
"key",
"in",
"[",
"\"GRID\"",
"]",
":",
"export",
"=",
"key",
".",
"lower",
"(",
")",
"in",
"power_to",
"self",
".",
"data",
"[",
"key",
"]",
"*=",
"-",
"1",
"if",
"export",
"else",
"1",
"self",
".",
"attributes",
"[",
"key",
"]",
"[",
"\"flow\"",
"]",
"=",
"\"export\"",
"if",
"export",
"else",
"\"import\"",
"if",
"key",
"in",
"[",
"\"STORAGE\"",
"]",
":",
"charge",
"=",
"key",
".",
"lower",
"(",
")",
"in",
"power_to",
"self",
".",
"data",
"[",
"key",
"]",
"*=",
"-",
"1",
"if",
"charge",
"else",
"1",
"self",
".",
"attributes",
"[",
"key",
"]",
"[",
"\"flow\"",
"]",
"=",
"\"charge\"",
"if",
"charge",
"else",
"\"discharge\"",
"self",
".",
"attributes",
"[",
"key",
"]",
"[",
"\"soc\"",
"]",
"=",
"value",
"[",
"\"chargeLevel\"",
"]",
"_LOGGER",
".",
"debug",
"(",
"\"Updated SolarEdge power flow: %s, %s\"",
",",
"self",
".",
"data",
",",
"self",
".",
"attributes",
")"
] | [
459,
4
] | [
506,
9
] | python | en | ['en', 'en', 'en'] | True |
get_service | (hass, config, discovery_info=None) | Get the Facebook notification service. | Get the Facebook notification service. | def get_service(hass, config, discovery_info=None):
"""Get the Facebook notification service."""
return FacebookNotificationService(config[CONF_PAGE_ACCESS_TOKEN]) | [
"def",
"get_service",
"(",
"hass",
",",
"config",
",",
"discovery_info",
"=",
"None",
")",
":",
"return",
"FacebookNotificationService",
"(",
"config",
"[",
"CONF_PAGE_ACCESS_TOKEN",
"]",
")"
] | [
27,
0
] | [
29,
70
] | python | en | ['en', 'en', 'en'] | True |
log_error | (response) | Log error message. | Log error message. | def log_error(response):
"""Log error message."""
obj = response.json()
error_message = obj["error"]["message"]
error_code = obj["error"]["code"]
_LOGGER.error(
"Error %s : %s (Code %s)", response.status_code, error_message, error_code
) | [
"def",
"log_error",
"(",
"response",
")",
":",
"obj",
"=",
"response",
".",
"json",
"(",
")",
"error_message",
"=",
"obj",
"[",
"\"error\"",
"]",
"[",
"\"message\"",
"]",
"error_code",
"=",
"obj",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
"_LOGGER",
".",
"error",
"(",
"\"Error %s : %s (Code %s)\"",
",",
"response",
".",
"status_code",
",",
"error_message",
",",
"error_code",
")"
] | [
82,
0
] | [
90,
5
] | python | da | ['da', 'de', 'en'] | False |
FacebookNotificationService.__init__ | (self, access_token) | Initialize the service. | Initialize the service. | def __init__(self, access_token):
"""Initialize the service."""
self.page_access_token = access_token | [
"def",
"__init__",
"(",
"self",
",",
"access_token",
")",
":",
"self",
".",
"page_access_token",
"=",
"access_token"
] | [
35,
4
] | [
37,
45
] | python | en | ['en', 'en', 'en'] | True |
FacebookNotificationService.send_message | (self, message="", **kwargs) | Send some message. | Send some message. | def send_message(self, message="", **kwargs):
"""Send some message."""
payload = {"access_token": self.page_access_token}
targets = kwargs.get(ATTR_TARGET)
data = kwargs.get(ATTR_DATA)
body_message = {"text": message}
if data is not None:
body_message.update(data)
# Only one of text or attachment can be specified
if "attachment" in body_message:
body_message.pop("text")
if not targets:
_LOGGER.error("At least 1 target is required")
return
for target in targets:
# If the target starts with a "+", it's a phone number,
# otherwise it's a user id.
if target.startswith("+"):
recipient = {"phone_number": target}
else:
recipient = {"id": target}
body = {
"recipient": recipient,
"message": body_message,
"messaging_type": "MESSAGE_TAG",
"tag": "ACCOUNT_UPDATE",
}
resp = requests.post(
BASE_URL,
data=json.dumps(body),
params=payload,
headers={CONTENT_TYPE: CONTENT_TYPE_JSON},
timeout=10,
)
if resp.status_code != HTTP_OK:
log_error(resp) | [
"def",
"send_message",
"(",
"self",
",",
"message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"\"access_token\"",
":",
"self",
".",
"page_access_token",
"}",
"targets",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TARGET",
")",
"data",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_DATA",
")",
"body_message",
"=",
"{",
"\"text\"",
":",
"message",
"}",
"if",
"data",
"is",
"not",
"None",
":",
"body_message",
".",
"update",
"(",
"data",
")",
"# Only one of text or attachment can be specified",
"if",
"\"attachment\"",
"in",
"body_message",
":",
"body_message",
".",
"pop",
"(",
"\"text\"",
")",
"if",
"not",
"targets",
":",
"_LOGGER",
".",
"error",
"(",
"\"At least 1 target is required\"",
")",
"return",
"for",
"target",
"in",
"targets",
":",
"# If the target starts with a \"+\", it's a phone number,",
"# otherwise it's a user id.",
"if",
"target",
".",
"startswith",
"(",
"\"+\"",
")",
":",
"recipient",
"=",
"{",
"\"phone_number\"",
":",
"target",
"}",
"else",
":",
"recipient",
"=",
"{",
"\"id\"",
":",
"target",
"}",
"body",
"=",
"{",
"\"recipient\"",
":",
"recipient",
",",
"\"message\"",
":",
"body_message",
",",
"\"messaging_type\"",
":",
"\"MESSAGE_TAG\"",
",",
"\"tag\"",
":",
"\"ACCOUNT_UPDATE\"",
",",
"}",
"resp",
"=",
"requests",
".",
"post",
"(",
"BASE_URL",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"body",
")",
",",
"params",
"=",
"payload",
",",
"headers",
"=",
"{",
"CONTENT_TYPE",
":",
"CONTENT_TYPE_JSON",
"}",
",",
"timeout",
"=",
"10",
",",
")",
"if",
"resp",
".",
"status_code",
"!=",
"HTTP_OK",
":",
"log_error",
"(",
"resp",
")"
] | [
39,
4
] | [
79,
31
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Wink water heater devices. | Set up the Wink water heater devices. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Wink water heater devices."""
for water_heater in pywink.get_water_heaters():
_id = water_heater.object_id() + water_heater.name()
if _id not in hass.data[DOMAIN]["unique_ids"]:
add_entities([WinkWaterHeater(water_heater, hass)]) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"for",
"water_heater",
"in",
"pywink",
".",
"get_water_heaters",
"(",
")",
":",
"_id",
"=",
"water_heater",
".",
"object_id",
"(",
")",
"+",
"water_heater",
".",
"name",
"(",
")",
"if",
"_id",
"not",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"unique_ids\"",
"]",
":",
"add_entities",
"(",
"[",
"WinkWaterHeater",
"(",
"water_heater",
",",
"hass",
")",
"]",
")"
] | [
44,
0
] | [
50,
63
] | python | en | ['en', 'en', 'en'] | True |
WinkWaterHeater.supported_features | (self) | Return the list of supported features. | Return the list of supported features. | def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS_HEATER | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_FLAGS_HEATER"
] | [
57,
4
] | [
59,
35
] | python | en | ['en', 'en', 'en'] | True |
WinkWaterHeater.temperature_unit | (self) | Return the unit of measurement. | Return the unit of measurement. | def temperature_unit(self):
"""Return the unit of measurement."""
# The Wink API always returns temp in Celsius
return TEMP_CELSIUS | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"# The Wink API always returns temp in Celsius",
"return",
"TEMP_CELSIUS"
] | [
62,
4
] | [
65,
27
] | python | en | ['en', 'la', 'en'] | True |
WinkWaterHeater.device_state_attributes | (self) | Return the optional device state attributes. | Return the optional device state attributes. | def device_state_attributes(self):
"""Return the optional device state attributes."""
data = {}
data[ATTR_VACATION_MODE] = self.wink.vacation_mode_enabled()
data[ATTR_RHEEM_TYPE] = self.wink.rheem_type()
return data | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"ATTR_VACATION_MODE",
"]",
"=",
"self",
".",
"wink",
".",
"vacation_mode_enabled",
"(",
")",
"data",
"[",
"ATTR_RHEEM_TYPE",
"]",
"=",
"self",
".",
"wink",
".",
"rheem_type",
"(",
")",
"return",
"data"
] | [
68,
4
] | [
74,
19
] | python | en | ['en', 'en', 'en'] | True |
WinkWaterHeater.current_operation | (self) |
Return current operation one of the following.
["eco", "performance", "heat_pump",
"high_demand", "electric_only", "gas]
|
Return current operation one of the following. | def current_operation(self):
"""
Return current operation one of the following.
["eco", "performance", "heat_pump",
"high_demand", "electric_only", "gas]
"""
if not self.wink.is_on():
current_op = STATE_OFF
else:
current_op = WINK_STATE_TO_HA.get(self.wink.current_mode())
if current_op is None:
current_op = STATE_UNKNOWN
return current_op | [
"def",
"current_operation",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"wink",
".",
"is_on",
"(",
")",
":",
"current_op",
"=",
"STATE_OFF",
"else",
":",
"current_op",
"=",
"WINK_STATE_TO_HA",
".",
"get",
"(",
"self",
".",
"wink",
".",
"current_mode",
"(",
")",
")",
"if",
"current_op",
"is",
"None",
":",
"current_op",
"=",
"STATE_UNKNOWN",
"return",
"current_op"
] | [
77,
4
] | [
90,
25
] | python | en | ['en', 'error', 'th'] | False |
WinkWaterHeater.operation_list | (self) | List of available operation modes. | List of available operation modes. | def operation_list(self):
"""List of available operation modes."""
op_list = ["off"]
modes = self.wink.modes()
for mode in modes:
if mode == "aux":
continue
ha_mode = WINK_STATE_TO_HA.get(mode)
if ha_mode is not None:
op_list.append(ha_mode)
else:
error = (
"Invalid operation mode mapping. "
f"{mode} doesn't map. Please report this."
)
_LOGGER.error(error)
return op_list | [
"def",
"operation_list",
"(",
"self",
")",
":",
"op_list",
"=",
"[",
"\"off\"",
"]",
"modes",
"=",
"self",
".",
"wink",
".",
"modes",
"(",
")",
"for",
"mode",
"in",
"modes",
":",
"if",
"mode",
"==",
"\"aux\"",
":",
"continue",
"ha_mode",
"=",
"WINK_STATE_TO_HA",
".",
"get",
"(",
"mode",
")",
"if",
"ha_mode",
"is",
"not",
"None",
":",
"op_list",
".",
"append",
"(",
"ha_mode",
")",
"else",
":",
"error",
"=",
"(",
"\"Invalid operation mode mapping. \"",
"f\"{mode} doesn't map. Please report this.\"",
")",
"_LOGGER",
".",
"error",
"(",
"error",
")",
"return",
"op_list"
] | [
93,
4
] | [
109,
22
] | python | en | ['en', 'en', 'en'] | True |
WinkWaterHeater.set_temperature | (self, **kwargs) | Set new target temperature. | Set new target temperature. | def set_temperature(self, **kwargs):
"""Set new target temperature."""
target_temp = kwargs.get(ATTR_TEMPERATURE)
self.wink.set_temperature(target_temp) | [
"def",
"set_temperature",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"target_temp",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TEMPERATURE",
")",
"self",
".",
"wink",
".",
"set_temperature",
"(",
"target_temp",
")"
] | [
111,
4
] | [
114,
46
] | python | en | ['en', 'ca', 'en'] | True |
WinkWaterHeater.set_operation_mode | (self, operation_mode) | Set operation mode. | Set operation mode. | def set_operation_mode(self, operation_mode):
"""Set operation mode."""
op_mode_to_set = HA_STATE_TO_WINK.get(operation_mode)
self.wink.set_operation_mode(op_mode_to_set) | [
"def",
"set_operation_mode",
"(",
"self",
",",
"operation_mode",
")",
":",
"op_mode_to_set",
"=",
"HA_STATE_TO_WINK",
".",
"get",
"(",
"operation_mode",
")",
"self",
".",
"wink",
".",
"set_operation_mode",
"(",
"op_mode_to_set",
")"
] | [
116,
4
] | [
119,
52
] | python | en | ['nl', 'ny', 'en'] | False |
WinkWaterHeater.target_temperature | (self) | Return the temperature we try to reach. | Return the temperature we try to reach. | def target_temperature(self):
"""Return the temperature we try to reach."""
return self.wink.current_set_point() | [
"def",
"target_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"current_set_point",
"(",
")"
] | [
122,
4
] | [
124,
44
] | python | en | ['en', 'en', 'en'] | True |
WinkWaterHeater.turn_away_mode_on | (self) | Turn away on. | Turn away on. | def turn_away_mode_on(self):
"""Turn away on."""
self.wink.set_vacation_mode(True) | [
"def",
"turn_away_mode_on",
"(",
"self",
")",
":",
"self",
".",
"wink",
".",
"set_vacation_mode",
"(",
"True",
")"
] | [
126,
4
] | [
128,
41
] | python | en | ['en', 'yo', 'en'] | True |
WinkWaterHeater.turn_away_mode_off | (self) | Turn away off. | Turn away off. | def turn_away_mode_off(self):
"""Turn away off."""
self.wink.set_vacation_mode(False) | [
"def",
"turn_away_mode_off",
"(",
"self",
")",
":",
"self",
".",
"wink",
".",
"set_vacation_mode",
"(",
"False",
")"
] | [
130,
4
] | [
132,
42
] | python | en | ['en', 'yo', 'en'] | True |
WinkWaterHeater.min_temp | (self) | Return the minimum temperature. | Return the minimum temperature. | def min_temp(self):
"""Return the minimum temperature."""
return self.wink.min_set_point() | [
"def",
"min_temp",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"min_set_point",
"(",
")"
] | [
135,
4
] | [
137,
40
] | python | en | ['en', 'la', 'en'] | True |
WinkWaterHeater.max_temp | (self) | Return the maximum temperature. | Return the maximum temperature. | def max_temp(self):
"""Return the maximum temperature."""
return self.wink.max_set_point() | [
"def",
"max_temp",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"max_set_point",
"(",
")"
] | [
140,
4
] | [
142,
40
] | python | en | ['en', 'la', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up switches. | Set up switches. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up switches."""
async def async_discover(devices):
"""Add new devices to platform."""
_async_setup_entities(devices, async_add_entities)
disp = async_dispatcher_connect(
hass, VS_DISCOVERY.format(VS_SWITCHES), async_discover
)
hass.data[DOMAIN][VS_DISPATCHERS].append(disp)
_async_setup_entities(hass.data[DOMAIN][VS_SWITCHES], async_add_entities)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"async",
"def",
"async_discover",
"(",
"devices",
")",
":",
"\"\"\"Add new devices to platform.\"\"\"",
"_async_setup_entities",
"(",
"devices",
",",
"async_add_entities",
")",
"disp",
"=",
"async_dispatcher_connect",
"(",
"hass",
",",
"VS_DISCOVERY",
".",
"format",
"(",
"VS_SWITCHES",
")",
",",
"async_discover",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"VS_DISPATCHERS",
"]",
".",
"append",
"(",
"disp",
")",
"_async_setup_entities",
"(",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"VS_SWITCHES",
"]",
",",
"async_add_entities",
")",
"return",
"True"
] | [
23,
0
] | [
36,
15
] | python | en | ['en', 'en', 'en'] | True |
_async_setup_entities | (devices, async_add_entities) | Check if device is online and add entity. | Check if device is online and add entity. | def _async_setup_entities(devices, async_add_entities):
"""Check if device is online and add entity."""
dev_list = []
for dev in devices:
if DEV_TYPE_TO_HA.get(dev.device_type) == "outlet":
dev_list.append(VeSyncSwitchHA(dev))
elif DEV_TYPE_TO_HA.get(dev.device_type) == "switch":
dev_list.append(VeSyncLightSwitch(dev))
else:
_LOGGER.warning(
"%s - Unknown device type - %s", dev.device_name, dev.device_type
)
continue
async_add_entities(dev_list, update_before_add=True) | [
"def",
"_async_setup_entities",
"(",
"devices",
",",
"async_add_entities",
")",
":",
"dev_list",
"=",
"[",
"]",
"for",
"dev",
"in",
"devices",
":",
"if",
"DEV_TYPE_TO_HA",
".",
"get",
"(",
"dev",
".",
"device_type",
")",
"==",
"\"outlet\"",
":",
"dev_list",
".",
"append",
"(",
"VeSyncSwitchHA",
"(",
"dev",
")",
")",
"elif",
"DEV_TYPE_TO_HA",
".",
"get",
"(",
"dev",
".",
"device_type",
")",
"==",
"\"switch\"",
":",
"dev_list",
".",
"append",
"(",
"VeSyncLightSwitch",
"(",
"dev",
")",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"\"%s - Unknown device type - %s\"",
",",
"dev",
".",
"device_name",
",",
"dev",
".",
"device_type",
")",
"continue",
"async_add_entities",
"(",
"dev_list",
",",
"update_before_add",
"=",
"True",
")"
] | [
40,
0
] | [
54,
56
] | python | en | ['en', 'en', 'en'] | True |
VeSyncBaseSwitch.turn_on | (self, **kwargs) | Turn the device on. | Turn the device on. | def turn_on(self, **kwargs):
"""Turn the device on."""
self.device.turn_on() | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"device",
".",
"turn_on",
"(",
")"
] | [
60,
4
] | [
62,
29
] | python | en | ['en', 'en', 'en'] | True |
VeSyncSwitchHA.__init__ | (self, plug) | Initialize the VeSync switch device. | Initialize the VeSync switch device. | def __init__(self, plug):
"""Initialize the VeSync switch device."""
super().__init__(plug)
self.smartplug = plug | [
"def",
"__init__",
"(",
"self",
",",
"plug",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"plug",
")",
"self",
".",
"smartplug",
"=",
"plug"
] | [
68,
4
] | [
71,
29
] | python | en | ['en', 'cs', 'en'] | True |
VeSyncSwitchHA.device_state_attributes | (self) | Return the state attributes of the device. | Return the state attributes of the device. | def device_state_attributes(self):
"""Return the state attributes of the device."""
if not hasattr(self.smartplug, "weekly_energy_total"):
return {}
return {
"voltage": self.smartplug.voltage,
"weekly_energy_total": self.smartplug.weekly_energy_total,
"monthly_energy_total": self.smartplug.monthly_energy_total,
"yearly_energy_total": self.smartplug.yearly_energy_total,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"smartplug",
",",
"\"weekly_energy_total\"",
")",
":",
"return",
"{",
"}",
"return",
"{",
"\"voltage\"",
":",
"self",
".",
"smartplug",
".",
"voltage",
",",
"\"weekly_energy_total\"",
":",
"self",
".",
"smartplug",
".",
"weekly_energy_total",
",",
"\"monthly_energy_total\"",
":",
"self",
".",
"smartplug",
".",
"monthly_energy_total",
",",
"\"yearly_energy_total\"",
":",
"self",
".",
"smartplug",
".",
"yearly_energy_total",
",",
"}"
] | [
74,
4
] | [
83,
9
] | python | en | ['en', 'en', 'en'] | True |
VeSyncSwitchHA.current_power_w | (self) | Return the current power usage in W. | Return the current power usage in W. | def current_power_w(self):
"""Return the current power usage in W."""
return self.smartplug.power | [
"def",
"current_power_w",
"(",
"self",
")",
":",
"return",
"self",
".",
"smartplug",
".",
"power"
] | [
86,
4
] | [
88,
35
] | python | en | ['en', 'en', 'en'] | True |
VeSyncSwitchHA.today_energy_kwh | (self) | Return the today total energy usage in kWh. | Return the today total energy usage in kWh. | def today_energy_kwh(self):
"""Return the today total energy usage in kWh."""
return self.smartplug.energy_today | [
"def",
"today_energy_kwh",
"(",
"self",
")",
":",
"return",
"self",
".",
"smartplug",
".",
"energy_today"
] | [
91,
4
] | [
93,
42
] | python | en | ['en', 'en', 'en'] | True |
VeSyncSwitchHA.update | (self) | Update outlet details and energy usage. | Update outlet details and energy usage. | def update(self):
"""Update outlet details and energy usage."""
self.smartplug.update()
self.smartplug.update_energy() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"smartplug",
".",
"update",
"(",
")",
"self",
".",
"smartplug",
".",
"update_energy",
"(",
")"
] | [
95,
4
] | [
98,
38
] | python | en | ['en', 'en', 'en'] | True |
VeSyncLightSwitch.__init__ | (self, switch) | Initialize Light Switch device class. | Initialize Light Switch device class. | def __init__(self, switch):
"""Initialize Light Switch device class."""
super().__init__(switch)
self.switch = switch | [
"def",
"__init__",
"(",
"self",
",",
"switch",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"switch",
")",
"self",
".",
"switch",
"=",
"switch"
] | [
104,
4
] | [
107,
28
] | python | en | ['de', 'en', 'en'] | True |
TrustedNetworksLoginFlow.__init__ | (
self,
auth_provider: TrustedNetworksAuthProvider,
ip_addr: IPAddress,
available_users: Dict[str, Optional[str]],
allow_bypass_login: bool,
) | Initialize the login flow. | Initialize the login flow. | def __init__(
self,
auth_provider: TrustedNetworksAuthProvider,
ip_addr: IPAddress,
available_users: Dict[str, Optional[str]],
allow_bypass_login: bool,
) -> None:
"""Initialize the login flow."""
super().__init__(auth_provider)
self._available_users = available_users
self._ip_address = ip_addr
self._allow_bypass_login = allow_bypass_login | [
"def",
"__init__",
"(",
"self",
",",
"auth_provider",
":",
"TrustedNetworksAuthProvider",
",",
"ip_addr",
":",
"IPAddress",
",",
"available_users",
":",
"Dict",
"[",
"str",
",",
"Optional",
"[",
"str",
"]",
"]",
",",
"allow_bypass_login",
":",
"bool",
",",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"auth_provider",
")",
"self",
".",
"_available_users",
"=",
"available_users",
"self",
".",
"_ip_address",
"=",
"ip_addr",
"self",
".",
"_allow_bypass_login",
"=",
"allow_bypass_login"
] | [
169,
4
] | [
180,
53
] | python | en | ['en', 'en', 'en'] | True |
TrustedNetworksLoginFlow.async_step_init | (
self, user_input: Optional[Dict[str, str]] = None
) | Handle the step of the form. | Handle the step of the form. | async def async_step_init(
self, user_input: Optional[Dict[str, str]] = None
) -> Dict[str, Any]:
"""Handle the step of the form."""
try:
cast(
TrustedNetworksAuthProvider, self._auth_provider
).async_validate_access(self._ip_address)
except InvalidAuthError:
return self.async_abort(reason="not_allowed")
if user_input is not None:
return await self.async_finish(user_input)
if self._allow_bypass_login and len(self._available_users) == 1:
return await self.async_finish(
{"user": next(iter(self._available_users.keys()))}
)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema({"user": vol.In(self._available_users)}),
) | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"try",
":",
"cast",
"(",
"TrustedNetworksAuthProvider",
",",
"self",
".",
"_auth_provider",
")",
".",
"async_validate_access",
"(",
"self",
".",
"_ip_address",
")",
"except",
"InvalidAuthError",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"not_allowed\"",
")",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"await",
"self",
".",
"async_finish",
"(",
"user_input",
")",
"if",
"self",
".",
"_allow_bypass_login",
"and",
"len",
"(",
"self",
".",
"_available_users",
")",
"==",
"1",
":",
"return",
"await",
"self",
".",
"async_finish",
"(",
"{",
"\"user\"",
":",
"next",
"(",
"iter",
"(",
"self",
".",
"_available_users",
".",
"keys",
"(",
")",
")",
")",
"}",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"init\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"\"user\"",
":",
"vol",
".",
"In",
"(",
"self",
".",
"_available_users",
")",
"}",
")",
",",
")"
] | [
182,
4
] | [
205,
9
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Binary Sensor platform for ADS. | Set up the Binary Sensor platform for ADS. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Binary Sensor platform for ADS."""
ads_hub = hass.data.get(DATA_ADS)
ads_var = config[CONF_ADS_VAR]
name = config[CONF_NAME]
device_class = config.get(CONF_DEVICE_CLASS)
ads_sensor = AdsBinarySensor(ads_hub, name, ads_var, device_class)
add_entities([ads_sensor]) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"ads_hub",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"DATA_ADS",
")",
"ads_var",
"=",
"config",
"[",
"CONF_ADS_VAR",
"]",
"name",
"=",
"config",
"[",
"CONF_NAME",
"]",
"device_class",
"=",
"config",
".",
"get",
"(",
"CONF_DEVICE_CLASS",
")",
"ads_sensor",
"=",
"AdsBinarySensor",
"(",
"ads_hub",
",",
"name",
",",
"ads_var",
",",
"device_class",
")",
"add_entities",
"(",
"[",
"ads_sensor",
"]",
")"
] | [
24,
0
] | [
33,
30
] | python | en | ['en', 'pt', 'en'] | True |
AdsBinarySensor.__init__ | (self, ads_hub, name, ads_var, device_class) | Initialize ADS binary sensor. | Initialize ADS binary sensor. | def __init__(self, ads_hub, name, ads_var, device_class):
"""Initialize ADS binary sensor."""
super().__init__(ads_hub, name, ads_var)
self._device_class = device_class or DEVICE_CLASS_MOVING | [
"def",
"__init__",
"(",
"self",
",",
"ads_hub",
",",
"name",
",",
"ads_var",
",",
"device_class",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"ads_hub",
",",
"name",
",",
"ads_var",
")",
"self",
".",
"_device_class",
"=",
"device_class",
"or",
"DEVICE_CLASS_MOVING"
] | [
39,
4
] | [
42,
64
] | python | en | ['en', 'pl', 'en'] | True |
AdsBinarySensor.async_added_to_hass | (self) | Register device notification. | Register device notification. | async def async_added_to_hass(self):
"""Register device notification."""
await self.async_initialize_device(self._ads_var, self._ads_hub.PLCTYPE_BOOL) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"self",
".",
"async_initialize_device",
"(",
"self",
".",
"_ads_var",
",",
"self",
".",
"_ads_hub",
".",
"PLCTYPE_BOOL",
")"
] | [
44,
4
] | [
46,
85
] | python | en | ['da', 'en', 'en'] | True |
AdsBinarySensor.is_on | (self) | Return True if the entity is on. | Return True if the entity is on. | def is_on(self):
"""Return True if the entity is on."""
return self._state_dict[STATE_KEY_STATE] | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state_dict",
"[",
"STATE_KEY_STATE",
"]"
] | [
49,
4
] | [
51,
48
] | python | en | ['en', 'en', 'en'] | True |
AdsBinarySensor.device_class | (self) | Return the device class. | Return the device class. | def device_class(self):
"""Return the device class."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
54,
4
] | [
56,
33
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up MQTT room Sensor. | Set up MQTT room Sensor. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up MQTT room Sensor."""
async_add_entities(
[
MQTTRoomSensor(
config.get(CONF_NAME),
config.get(CONF_STATE_TOPIC),
config.get(CONF_DEVICE_ID),
config.get(CONF_TIMEOUT),
config.get(CONF_AWAY_TIMEOUT),
)
]
) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"async_add_entities",
"(",
"[",
"MQTTRoomSensor",
"(",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
",",
"config",
".",
"get",
"(",
"CONF_STATE_TOPIC",
")",
",",
"config",
".",
"get",
"(",
"CONF_DEVICE_ID",
")",
",",
"config",
".",
"get",
"(",
"CONF_TIMEOUT",
")",
",",
"config",
".",
"get",
"(",
"CONF_AWAY_TIMEOUT",
")",
",",
")",
"]",
")"
] | [
53,
0
] | [
65,
5
] | python | en | ['en', 'ca', 'en'] | True |
_parse_update_data | (topic, data) | Parse the room presence update. | Parse the room presence update. | def _parse_update_data(topic, data):
"""Parse the room presence update."""
parts = topic.split("/")
room = parts[-1]
device_id = slugify(data.get(ATTR_ID)).upper()
distance = data.get("distance")
parsed_data = {ATTR_DEVICE_ID: device_id, ATTR_ROOM: room, ATTR_DISTANCE: distance}
return parsed_data | [
"def",
"_parse_update_data",
"(",
"topic",
",",
"data",
")",
":",
"parts",
"=",
"topic",
".",
"split",
"(",
"\"/\"",
")",
"room",
"=",
"parts",
"[",
"-",
"1",
"]",
"device_id",
"=",
"slugify",
"(",
"data",
".",
"get",
"(",
"ATTR_ID",
")",
")",
".",
"upper",
"(",
")",
"distance",
"=",
"data",
".",
"get",
"(",
"\"distance\"",
")",
"parsed_data",
"=",
"{",
"ATTR_DEVICE_ID",
":",
"device_id",
",",
"ATTR_ROOM",
":",
"room",
",",
"ATTR_DISTANCE",
":",
"distance",
"}",
"return",
"parsed_data"
] | [
151,
0
] | [
158,
22
] | python | en | ['en', 'en', 'en'] | True |
MQTTRoomSensor.__init__ | (self, name, state_topic, device_id, timeout, consider_home) | Initialize the sensor. | Initialize the sensor. | def __init__(self, name, state_topic, device_id, timeout, consider_home):
"""Initialize the sensor."""
self._state = STATE_NOT_HOME
self._name = name
self._state_topic = f"{state_topic}/+"
self._device_id = slugify(device_id).upper()
self._timeout = timeout
self._consider_home = (
timedelta(seconds=consider_home) if consider_home else None
)
self._distance = None
self._updated = None | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"state_topic",
",",
"device_id",
",",
"timeout",
",",
"consider_home",
")",
":",
"self",
".",
"_state",
"=",
"STATE_NOT_HOME",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_state_topic",
"=",
"f\"{state_topic}/+\"",
"self",
".",
"_device_id",
"=",
"slugify",
"(",
"device_id",
")",
".",
"upper",
"(",
")",
"self",
".",
"_timeout",
"=",
"timeout",
"self",
".",
"_consider_home",
"=",
"(",
"timedelta",
"(",
"seconds",
"=",
"consider_home",
")",
"if",
"consider_home",
"else",
"None",
")",
"self",
".",
"_distance",
"=",
"None",
"self",
".",
"_updated",
"=",
"None"
] | [
71,
4
] | [
82,
28
] | python | en | ['en', 'en', 'en'] | True |
MQTTRoomSensor.async_added_to_hass | (self) | Subscribe to MQTT events. | Subscribe to MQTT events. | async def async_added_to_hass(self):
"""Subscribe to MQTT events."""
@callback
def update_state(device_id, room, distance):
"""Update the sensor state."""
self._state = room
self._distance = distance
self._updated = dt.utcnow()
self.async_write_ha_state()
@callback
def message_received(msg):
"""Handle new MQTT messages."""
try:
data = MQTT_PAYLOAD(msg.payload)
except vol.MultipleInvalid as error:
_LOGGER.debug("Skipping update because of malformatted data: %s", error)
return
device = _parse_update_data(msg.topic, data)
if device.get(CONF_DEVICE_ID) == self._device_id:
if self._distance is None or self._updated is None:
update_state(**device)
else:
# update if:
# device is in the same room OR
# device is closer to another room OR
# last update from other room was too long ago
timediff = dt.utcnow() - self._updated
if (
device.get(ATTR_ROOM) == self._state
or device.get(ATTR_DISTANCE) < self._distance
or timediff.seconds >= self._timeout
):
update_state(**device)
return await mqtt.async_subscribe(
self.hass, self._state_topic, message_received, 1
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"@",
"callback",
"def",
"update_state",
"(",
"device_id",
",",
"room",
",",
"distance",
")",
":",
"\"\"\"Update the sensor state.\"\"\"",
"self",
".",
"_state",
"=",
"room",
"self",
".",
"_distance",
"=",
"distance",
"self",
".",
"_updated",
"=",
"dt",
".",
"utcnow",
"(",
")",
"self",
".",
"async_write_ha_state",
"(",
")",
"@",
"callback",
"def",
"message_received",
"(",
"msg",
")",
":",
"\"\"\"Handle new MQTT messages.\"\"\"",
"try",
":",
"data",
"=",
"MQTT_PAYLOAD",
"(",
"msg",
".",
"payload",
")",
"except",
"vol",
".",
"MultipleInvalid",
"as",
"error",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Skipping update because of malformatted data: %s\"",
",",
"error",
")",
"return",
"device",
"=",
"_parse_update_data",
"(",
"msg",
".",
"topic",
",",
"data",
")",
"if",
"device",
".",
"get",
"(",
"CONF_DEVICE_ID",
")",
"==",
"self",
".",
"_device_id",
":",
"if",
"self",
".",
"_distance",
"is",
"None",
"or",
"self",
".",
"_updated",
"is",
"None",
":",
"update_state",
"(",
"*",
"*",
"device",
")",
"else",
":",
"# update if:",
"# device is in the same room OR",
"# device is closer to another room OR",
"# last update from other room was too long ago",
"timediff",
"=",
"dt",
".",
"utcnow",
"(",
")",
"-",
"self",
".",
"_updated",
"if",
"(",
"device",
".",
"get",
"(",
"ATTR_ROOM",
")",
"==",
"self",
".",
"_state",
"or",
"device",
".",
"get",
"(",
"ATTR_DISTANCE",
")",
"<",
"self",
".",
"_distance",
"or",
"timediff",
".",
"seconds",
">=",
"self",
".",
"_timeout",
")",
":",
"update_state",
"(",
"*",
"*",
"device",
")",
"return",
"await",
"mqtt",
".",
"async_subscribe",
"(",
"self",
".",
"hass",
",",
"self",
".",
"_state_topic",
",",
"message_received",
",",
"1",
")"
] | [
84,
4
] | [
124,
9
] | python | en | ['en', 'en', 'en'] | True |
MQTTRoomSensor.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"
] | [
127,
4
] | [
129,
25
] | python | en | ['en', 'mi', 'en'] | True |
MQTTRoomSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {ATTR_DISTANCE: self._distance} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"ATTR_DISTANCE",
":",
"self",
".",
"_distance",
"}"
] | [
132,
4
] | [
134,
46
] | python | en | ['en', 'en', 'en'] | True |
MQTTRoomSensor.state | (self) | Return the current room of the entity. | Return the current room of the entity. | def state(self):
"""Return the current room of the entity."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
137,
4
] | [
139,
26
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.