Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
test_availability_poll_state | (
hass, mqtt_client_mock, mqtt_mock, setup_tasmota
) | Test polling after MQTT connection (re)established. | Test polling after MQTT connection (re)established. | async def test_availability_poll_state(
hass, mqtt_client_mock, mqtt_mock, setup_tasmota
):
"""Test polling after MQTT connection (re)established."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["swc"][0] = 1
config["swn"][0] = "Test"
poll_topic = "tasmota_49A3BC/cmnd/STATUS"
await help_test_availability_poll_state(
hass,
mqtt_client_mock,
mqtt_mock,
binary_sensor.DOMAIN,
config,
poll_topic,
"10",
) | [
"async",
"def",
"test_availability_poll_state",
"(",
"hass",
",",
"mqtt_client_mock",
",",
"mqtt_mock",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"swc\"",
"]",
"[",
"0",
"]",
"=",
"1",
"config",
"[",
"\"swn\"",
"]",
"[",
"0",
"]",
"=",
"\"Test\"",
"poll_topic",
"=",
"\"tasmota_49A3BC/cmnd/STATUS\"",
"await",
"help_test_availability_poll_state",
"(",
"hass",
",",
"mqtt_client_mock",
",",
"mqtt_mock",
",",
"binary_sensor",
".",
"DOMAIN",
",",
"config",
",",
"poll_topic",
",",
"\"10\"",
",",
")"
] | [
307,
0
] | [
323,
5
] | python | da | ['da', 'da', 'en'] | True |
test_discovery_removal_binary_sensor | (hass, mqtt_mock, caplog, setup_tasmota) | Test removal of discovered binary_sensor. | Test removal of discovered binary_sensor. | async def test_discovery_removal_binary_sensor(hass, mqtt_mock, caplog, setup_tasmota):
"""Test removal of discovered binary_sensor."""
config1 = copy.deepcopy(DEFAULT_CONFIG)
config2 = copy.deepcopy(DEFAULT_CONFIG)
config1["swc"][0] = 1
config2["swc"][0] = 0
config1["swn"][0] = "Test"
config2["swn"][0] = "Test"
await help_test_discovery_removal(
hass, mqtt_mock, caplog, binary_sensor.DOMAIN, config1, config2
) | [
"async",
"def",
"test_discovery_removal_binary_sensor",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"setup_tasmota",
")",
":",
"config1",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config2",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config1",
"[",
"\"swc\"",
"]",
"[",
"0",
"]",
"=",
"1",
"config2",
"[",
"\"swc\"",
"]",
"[",
"0",
"]",
"=",
"0",
"config1",
"[",
"\"swn\"",
"]",
"[",
"0",
"]",
"=",
"\"Test\"",
"config2",
"[",
"\"swn\"",
"]",
"[",
"0",
"]",
"=",
"\"Test\"",
"await",
"help_test_discovery_removal",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"binary_sensor",
".",
"DOMAIN",
",",
"config1",
",",
"config2",
")"
] | [
326,
0
] | [
337,
5
] | python | en | ['en', 'en', 'en'] | True |
test_discovery_update_unchanged_binary_sensor | (
hass, mqtt_mock, caplog, setup_tasmota
) | Test update of discovered binary_sensor. | Test update of discovered binary_sensor. | async def test_discovery_update_unchanged_binary_sensor(
hass, mqtt_mock, caplog, setup_tasmota
):
"""Test update of discovered binary_sensor."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["swc"][0] = 1
config["swn"][0] = "Test"
with patch(
"homeassistant.components.tasmota.binary_sensor.TasmotaBinarySensor.discovery_update"
) as discovery_update:
await help_test_discovery_update_unchanged(
hass, mqtt_mock, caplog, binary_sensor.DOMAIN, config, discovery_update
) | [
"async",
"def",
"test_discovery_update_unchanged_binary_sensor",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"swc\"",
"]",
"[",
"0",
"]",
"=",
"1",
"config",
"[",
"\"swn\"",
"]",
"[",
"0",
"]",
"=",
"\"Test\"",
"with",
"patch",
"(",
"\"homeassistant.components.tasmota.binary_sensor.TasmotaBinarySensor.discovery_update\"",
")",
"as",
"discovery_update",
":",
"await",
"help_test_discovery_update_unchanged",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"binary_sensor",
".",
"DOMAIN",
",",
"config",
",",
"discovery_update",
")"
] | [
340,
0
] | [
352,
9
] | python | en | ['en', 'en', 'en'] | True |
test_discovery_device_remove | (hass, mqtt_mock, setup_tasmota) | Test device registry remove. | Test device registry remove. | async def test_discovery_device_remove(hass, mqtt_mock, setup_tasmota):
"""Test device registry remove."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["swc"][0] = 1
unique_id = f"{DEFAULT_CONFIG['mac']}_binary_sensor_switch_0"
await help_test_discovery_device_remove(
hass, mqtt_mock, binary_sensor.DOMAIN, unique_id, config
) | [
"async",
"def",
"test_discovery_device_remove",
"(",
"hass",
",",
"mqtt_mock",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"swc\"",
"]",
"[",
"0",
"]",
"=",
"1",
"unique_id",
"=",
"f\"{DEFAULT_CONFIG['mac']}_binary_sensor_switch_0\"",
"await",
"help_test_discovery_device_remove",
"(",
"hass",
",",
"mqtt_mock",
",",
"binary_sensor",
".",
"DOMAIN",
",",
"unique_id",
",",
"config",
")"
] | [
355,
0
] | [
362,
5
] | python | en | ['fr', 'en', 'en'] | True |
test_entity_id_update_subscriptions | (hass, mqtt_mock, setup_tasmota) | Test MQTT subscriptions are managed when entity_id is updated. | Test MQTT subscriptions are managed when entity_id is updated. | async def test_entity_id_update_subscriptions(hass, mqtt_mock, setup_tasmota):
"""Test MQTT subscriptions are managed when entity_id is updated."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["swc"][0] = 1
config["swn"][0] = "Test"
topics = [
get_topic_stat_result(config),
get_topic_tele_sensor(config),
get_topic_stat_status(config, 10),
get_topic_tele_will(config),
]
await help_test_entity_id_update_subscriptions(
hass, mqtt_mock, binary_sensor.DOMAIN, config, topics
) | [
"async",
"def",
"test_entity_id_update_subscriptions",
"(",
"hass",
",",
"mqtt_mock",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"swc\"",
"]",
"[",
"0",
"]",
"=",
"1",
"config",
"[",
"\"swn\"",
"]",
"[",
"0",
"]",
"=",
"\"Test\"",
"topics",
"=",
"[",
"get_topic_stat_result",
"(",
"config",
")",
",",
"get_topic_tele_sensor",
"(",
"config",
")",
",",
"get_topic_stat_status",
"(",
"config",
",",
"10",
")",
",",
"get_topic_tele_will",
"(",
"config",
")",
",",
"]",
"await",
"help_test_entity_id_update_subscriptions",
"(",
"hass",
",",
"mqtt_mock",
",",
"binary_sensor",
".",
"DOMAIN",
",",
"config",
",",
"topics",
")"
] | [
365,
0
] | [
378,
5
] | python | en | ['en', 'en', 'en'] | True |
test_entity_id_update_discovery_update | (hass, mqtt_mock, setup_tasmota) | Test MQTT discovery update when entity_id is updated. | Test MQTT discovery update when entity_id is updated. | async def test_entity_id_update_discovery_update(hass, mqtt_mock, setup_tasmota):
"""Test MQTT discovery update when entity_id is updated."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["swc"][0] = 1
config["swn"][0] = "Test"
await help_test_entity_id_update_discovery_update(
hass, mqtt_mock, binary_sensor.DOMAIN, config
) | [
"async",
"def",
"test_entity_id_update_discovery_update",
"(",
"hass",
",",
"mqtt_mock",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"swc\"",
"]",
"[",
"0",
"]",
"=",
"1",
"config",
"[",
"\"swn\"",
"]",
"[",
"0",
"]",
"=",
"\"Test\"",
"await",
"help_test_entity_id_update_discovery_update",
"(",
"hass",
",",
"mqtt_mock",
",",
"binary_sensor",
".",
"DOMAIN",
",",
"config",
")"
] | [
381,
0
] | [
388,
5
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Wink platform. | Set up the Wink platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Wink platform."""
for scene in pywink.get_scenes():
_id = scene.object_id() + scene.name()
if _id not in hass.data[DOMAIN]["unique_ids"]:
add_entities([WinkScene(scene, hass)]) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"for",
"scene",
"in",
"pywink",
".",
"get_scenes",
"(",
")",
":",
"_id",
"=",
"scene",
".",
"object_id",
"(",
")",
"+",
"scene",
".",
"name",
"(",
")",
"if",
"_id",
"not",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"unique_ids\"",
"]",
":",
"add_entities",
"(",
"[",
"WinkScene",
"(",
"scene",
",",
"hass",
")",
"]",
")"
] | [
10,
0
] | [
16,
50
] | python | en | ['en', 'da', 'en'] | True |
WinkScene.__init__ | (self, wink, hass) | Initialize the Wink device. | Initialize the Wink device. | def __init__(self, wink, hass):
"""Initialize the Wink device."""
super().__init__(wink, hass)
hass.data[DOMAIN]["entities"]["scene"].append(self) | [
"def",
"__init__",
"(",
"self",
",",
"wink",
",",
"hass",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"wink",
",",
"hass",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
"[",
"\"scene\"",
"]",
".",
"append",
"(",
"self",
")"
] | [
22,
4
] | [
25,
59
] | python | en | ['en', 'en', 'en'] | True |
WinkScene.async_added_to_hass | (self) | Call when entity is added to hass. | Call when entity is added to hass. | async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[DOMAIN]["entities"]["scene"].append(self) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
"[",
"\"scene\"",
"]",
".",
"append",
"(",
"self",
")"
] | [
27,
4
] | [
29,
64
] | python | en | ['en', 'en', 'en'] | True |
WinkScene.activate | (self, **kwargs: Any) | Activate the scene. | Activate the scene. | def activate(self, **kwargs: Any) -> None:
"""Activate the scene."""
self.wink.activate() | [
"def",
"activate",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"wink",
".",
"activate",
"(",
")"
] | [
31,
4
] | [
33,
28
] | python | en | ['en', 'it', 'en'] | True |
DN3BaseModel.clone | (self) |
This provides a standard way to copy models, weights and all.
|
This provides a standard way to copy models, weights and all.
| def clone(self):
"""
This provides a standard way to copy models, weights and all.
"""
return deepcopy(self) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"deepcopy",
"(",
"self",
")"
] | [
37,
4
] | [
41,
29
] | python | en | ['en', 'error', 'th'] | False |
Classifier.from_dataset | (cls, dataset: DN3ataset, **modelargs) |
Create a classifier from a dataset.
Parameters
----------
dataset
modelargs: dict
Options to construct the dataset, if dataset does not have listed targets, targets must be specified
in the keyword arguments or will fall back to 2.
Returns
-------
model: Classifier
A new `Classifier` ready to classifiy data from `dataset`
|
Create a classifier from a dataset. | def from_dataset(cls, dataset: DN3ataset, **modelargs):
"""
Create a classifier from a dataset.
Parameters
----------
dataset
modelargs: dict
Options to construct the dataset, if dataset does not have listed targets, targets must be specified
in the keyword arguments or will fall back to 2.
Returns
-------
model: Classifier
A new `Classifier` ready to classifiy data from `dataset`
"""
if hasattr(dataset, 'get_targets'):
targets = len(np.unique(dataset.get_targets()))
elif dataset.info is not None and isinstance(dataset.info.targets, int):
targets = dataset.info.targets
else:
targets = 2
modelargs.setdefault('targets', targets)
print("Creating {} using: {} channels x {} samples at {}Hz | {} targets".format(cls.__name__,
len(dataset.channels),
dataset.sequence_length,
dataset.sfreq,
modelargs['targets']))
assert isinstance(dataset, DN3ataset)
return cls(samples=dataset.sequence_length, channels=len(dataset.channels), **modelargs) | [
"def",
"from_dataset",
"(",
"cls",
",",
"dataset",
":",
"DN3ataset",
",",
"*",
"*",
"modelargs",
")",
":",
"if",
"hasattr",
"(",
"dataset",
",",
"'get_targets'",
")",
":",
"targets",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"dataset",
".",
"get_targets",
"(",
")",
")",
")",
"elif",
"dataset",
".",
"info",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"dataset",
".",
"info",
".",
"targets",
",",
"int",
")",
":",
"targets",
"=",
"dataset",
".",
"info",
".",
"targets",
"else",
":",
"targets",
"=",
"2",
"modelargs",
".",
"setdefault",
"(",
"'targets'",
",",
"targets",
")",
"print",
"(",
"\"Creating {} using: {} channels x {} samples at {}Hz | {} targets\"",
".",
"format",
"(",
"cls",
".",
"__name__",
",",
"len",
"(",
"dataset",
".",
"channels",
")",
",",
"dataset",
".",
"sequence_length",
",",
"dataset",
".",
"sfreq",
",",
"modelargs",
"[",
"'targets'",
"]",
")",
")",
"assert",
"isinstance",
"(",
"dataset",
",",
"DN3ataset",
")",
"return",
"cls",
"(",
"samples",
"=",
"dataset",
".",
"sequence_length",
",",
"channels",
"=",
"len",
"(",
"dataset",
".",
"channels",
")",
",",
"*",
"*",
"modelargs",
")"
] | [
71,
4
] | [
100,
96
] | python | en | ['en', 'error', 'th'] | False |
Classifier.make_new_classification_layer | (self) |
This allows for a distinction between the classification layer(s) and the rest of the network. Using a basic
formulation of a network being composed of two parts feature_extractor & classifier.
This method is for implementing the classification side, so that methods like :py:meth:`freeze_features` works
as intended.
Anything besides a layer that just flattens anything incoming to a vector and Linearly weights this to the
target should override this method, and there should be a variable called `self.classifier`
|
This allows for a distinction between the classification layer(s) and the rest of the network. Using a basic
formulation of a network being composed of two parts feature_extractor & classifier. | def make_new_classification_layer(self):
"""
This allows for a distinction between the classification layer(s) and the rest of the network. Using a basic
formulation of a network being composed of two parts feature_extractor & classifier.
This method is for implementing the classification side, so that methods like :py:meth:`freeze_features` works
as intended.
Anything besides a layer that just flattens anything incoming to a vector and Linearly weights this to the
target should override this method, and there should be a variable called `self.classifier`
"""
classifier = nn.Linear(self.num_features_for_classification, self.targets)
nn.init.xavier_normal_(classifier.weight)
classifier.bias.data.zero_()
self.classifier = nn.Sequential(Flatten(), classifier) | [
"def",
"make_new_classification_layer",
"(",
"self",
")",
":",
"classifier",
"=",
"nn",
".",
"Linear",
"(",
"self",
".",
"num_features_for_classification",
",",
"self",
".",
"targets",
")",
"nn",
".",
"init",
".",
"xavier_normal_",
"(",
"classifier",
".",
"weight",
")",
"classifier",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"self",
".",
"classifier",
"=",
"nn",
".",
"Sequential",
"(",
"Flatten",
"(",
")",
",",
"classifier",
")"
] | [
118,
4
] | [
133,
62
] | python | en | ['en', 'error', 'th'] | False |
Classifier.freeze_features | (self, unfreeze=False, freeze_classifier=False) |
In many cases, the features learned by a model in one domain can be applied to another case.
This method freezes (or un-freezes) all but the `classifier` layer. So that any further training does not (or
does if unfreeze=True) affect these weights.
Parameters
----------
unfreeze : bool
To unfreeze weights after a previous call to this.
freeze_classifier: bool
Commonly, the classifier layer will not be frozen (default). Setting this to `True` will freeze this
layer too.
|
In many cases, the features learned by a model in one domain can be applied to another case. | def freeze_features(self, unfreeze=False, freeze_classifier=False):
"""
In many cases, the features learned by a model in one domain can be applied to another case.
This method freezes (or un-freezes) all but the `classifier` layer. So that any further training does not (or
does if unfreeze=True) affect these weights.
Parameters
----------
unfreeze : bool
To unfreeze weights after a previous call to this.
freeze_classifier: bool
Commonly, the classifier layer will not be frozen (default). Setting this to `True` will freeze this
layer too.
"""
super(Classifier, self).freeze_features(unfreeze=unfreeze)
if isinstance(self.classifier, nn.Module) and not freeze_classifier:
for param in self.classifier.parameters():
param.requires_grad = True | [
"def",
"freeze_features",
"(",
"self",
",",
"unfreeze",
"=",
"False",
",",
"freeze_classifier",
"=",
"False",
")",
":",
"super",
"(",
"Classifier",
",",
"self",
")",
".",
"freeze_features",
"(",
"unfreeze",
"=",
"unfreeze",
")",
"if",
"isinstance",
"(",
"self",
".",
"classifier",
",",
"nn",
".",
"Module",
")",
"and",
"not",
"freeze_classifier",
":",
"for",
"param",
"in",
"self",
".",
"classifier",
".",
"parameters",
"(",
")",
":",
"param",
".",
"requires_grad",
"=",
"True"
] | [
135,
4
] | [
154,
42
] | python | en | ['en', 'error', 'th'] | False |
StrideClassifier.__init__ | (self, targets, samples, channels, stride_width=2, return_features=False) |
Instead of summarizing the entire temporal dimension into a single prediction, a prediction kernel is swept over
the final sequence representation and generates predictions at each step.
Parameters
----------
targets
samples
channels
stride_width
return_features
|
Instead of summarizing the entire temporal dimension into a single prediction, a prediction kernel is swept over
the final sequence representation and generates predictions at each step. | def __init__(self, targets, samples, channels, stride_width=2, return_features=False):
"""
Instead of summarizing the entire temporal dimension into a single prediction, a prediction kernel is swept over
the final sequence representation and generates predictions at each step.
Parameters
----------
targets
samples
channels
stride_width
return_features
"""
self.stride_width = stride_width
super(StrideClassifier, self).__init__(targets, samples, channels, return_features=return_features) | [
"def",
"__init__",
"(",
"self",
",",
"targets",
",",
"samples",
",",
"channels",
",",
"stride_width",
"=",
"2",
",",
"return_features",
"=",
"False",
")",
":",
"self",
".",
"stride_width",
"=",
"stride_width",
"super",
"(",
"StrideClassifier",
",",
"self",
")",
".",
"__init__",
"(",
"targets",
",",
"samples",
",",
"channels",
",",
"return_features",
"=",
"return_features",
")"
] | [
186,
4
] | [
200,
107
] | python | en | ['en', 'error', 'th'] | False |
config_fixture | () | Create hass config fixture. | Create hass config fixture. | def config_fixture():
"""Create hass config fixture."""
return {DOMAIN: {}} | [
"def",
"config_fixture",
"(",
")",
":",
"return",
"{",
"DOMAIN",
":",
"{",
"}",
"}"
] | [
9,
0
] | [
11,
23
] | python | en | ['en', 'en', 'en'] | True |
test_basic_setup | (hass, config) | Test component setup creates entry from config. | Test component setup creates entry from config. | async def test_basic_setup(hass, config):
"""Test component setup creates entry from config."""
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
local_ip = await hass.async_add_executor_job(get_local_ip)
state = hass.states.get(f"sensor.{DOMAIN}")
assert state
assert state.state == local_ip | [
"async",
"def",
"test_basic_setup",
"(",
"hass",
",",
"config",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"local_ip",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"get_local_ip",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"sensor.{DOMAIN}\"",
")",
"assert",
"state",
"assert",
"state",
".",
"state",
"==",
"local_ip"
] | [
14,
0
] | [
21,
34
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up tuya sensors dynamically through tuya discovery. | Set up tuya sensors dynamically through tuya discovery. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up tuya sensors dynamically through tuya discovery."""
platform = config_entry.data[CONF_PLATFORM]
async def async_discover_sensor(dev_ids):
"""Discover and add a discovered tuya sensor."""
if not dev_ids:
return
entities = await hass.async_add_executor_job(
_setup_entities,
hass,
dev_ids,
platform,
)
async_add_entities(entities)
async_dispatcher_connect(
hass, TUYA_DISCOVERY_NEW.format(SENSOR_DOMAIN), async_discover_sensor
)
devices_ids = hass.data[DOMAIN]["pending"].pop(SENSOR_DOMAIN)
await async_discover_sensor(devices_ids) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"platform",
"=",
"config_entry",
".",
"data",
"[",
"CONF_PLATFORM",
"]",
"async",
"def",
"async_discover_sensor",
"(",
"dev_ids",
")",
":",
"\"\"\"Discover and add a discovered tuya sensor.\"\"\"",
"if",
"not",
"dev_ids",
":",
"return",
"entities",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"_setup_entities",
",",
"hass",
",",
"dev_ids",
",",
"platform",
",",
")",
"async_add_entities",
"(",
"entities",
")",
"async_dispatcher_connect",
"(",
"hass",
",",
"TUYA_DISCOVERY_NEW",
".",
"format",
"(",
"SENSOR_DOMAIN",
")",
",",
"async_discover_sensor",
")",
"devices_ids",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"pending\"",
"]",
".",
"pop",
"(",
"SENSOR_DOMAIN",
")",
"await",
"async_discover_sensor",
"(",
"devices_ids",
")"
] | [
17,
0
] | [
39,
44
] | python | en | ['en', 'zu', 'en'] | True |
_setup_entities | (hass, dev_ids, platform) | Set up Tuya Switch device. | Set up Tuya Switch device. | def _setup_entities(hass, dev_ids, platform):
"""Set up Tuya Switch device."""
tuya = hass.data[DOMAIN][TUYA_DATA]
entities = []
for dev_id in dev_ids:
device = tuya.get_device_by_id(dev_id)
if device is None:
continue
entities.append(TuyaSwitch(device, platform))
return entities | [
"def",
"_setup_entities",
"(",
"hass",
",",
"dev_ids",
",",
"platform",
")",
":",
"tuya",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"TUYA_DATA",
"]",
"entities",
"=",
"[",
"]",
"for",
"dev_id",
"in",
"dev_ids",
":",
"device",
"=",
"tuya",
".",
"get_device_by_id",
"(",
"dev_id",
")",
"if",
"device",
"is",
"None",
":",
"continue",
"entities",
".",
"append",
"(",
"TuyaSwitch",
"(",
"device",
",",
"platform",
")",
")",
"return",
"entities"
] | [
42,
0
] | [
51,
19
] | python | en | ['en', 'zu', 'en'] | True |
TuyaSwitch.__init__ | (self, tuya, platform) | Init Tuya switch device. | Init Tuya switch device. | def __init__(self, tuya, platform):
"""Init Tuya switch device."""
super().__init__(tuya, platform)
self.entity_id = ENTITY_ID_FORMAT.format(tuya.object_id()) | [
"def",
"__init__",
"(",
"self",
",",
"tuya",
",",
"platform",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"tuya",
",",
"platform",
")",
"self",
".",
"entity_id",
"=",
"ENTITY_ID_FORMAT",
".",
"format",
"(",
"tuya",
".",
"object_id",
"(",
")",
")"
] | [
57,
4
] | [
60,
66
] | python | en | ['en', 'pl', 'en'] | True |
TuyaSwitch.is_on | (self) | Return true if switch is on. | Return true if switch is on. | def is_on(self):
"""Return true if switch is on."""
return self._tuya.state() | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tuya",
".",
"state",
"(",
")"
] | [
63,
4
] | [
65,
33
] | python | en | ['en', 'fy', 'en'] | True |
TuyaSwitch.turn_on | (self, **kwargs) | Turn the switch on. | Turn the switch on. | def turn_on(self, **kwargs):
"""Turn the switch on."""
self._tuya.turn_on() | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_tuya",
".",
"turn_on",
"(",
")"
] | [
67,
4
] | [
69,
28
] | python | en | ['en', 'en', 'en'] | True |
TuyaSwitch.turn_off | (self, **kwargs) | Turn the device off. | Turn the device off. | def turn_off(self, **kwargs):
"""Turn the device off."""
self._tuya.turn_off() | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_tuya",
".",
"turn_off",
"(",
")"
] | [
71,
4
] | [
73,
29
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Plaato sensor. | Set up the Plaato sensor. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Plaato sensor.""" | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":"
] | [
29,
0
] | [
30,
35
] | python | en | ['en', 'ceb', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up Plaato from a config entry. | Set up Plaato from a config entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Plaato from a config entry."""
devices = {}
def get_device(device_id):
"""Get a device."""
return hass.data[PLAATO_DOMAIN].get(device_id, False)
def get_device_sensors(device_id):
"""Get device sensors."""
return hass.data[PLAATO_DOMAIN].get(device_id).get(PLAATO_DEVICE_SENSORS)
async def _update_sensor(device_id):
"""Update/Create the sensors."""
if device_id not in devices and get_device(device_id):
entities = []
sensors = get_device_sensors(device_id)
for sensor_type in sensors:
entities.append(PlaatoSensor(device_id, sensor_type))
devices[device_id] = entities
async_add_entities(entities, True)
else:
for entity in devices[device_id]:
async_dispatcher_send(hass, f"{PLAATO_DOMAIN}_{entity.unique_id}")
hass.data[SENSOR_DATA_KEY] = async_dispatcher_connect(
hass, SENSOR_UPDATE, _update_sensor
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"devices",
"=",
"{",
"}",
"def",
"get_device",
"(",
"device_id",
")",
":",
"\"\"\"Get a device.\"\"\"",
"return",
"hass",
".",
"data",
"[",
"PLAATO_DOMAIN",
"]",
".",
"get",
"(",
"device_id",
",",
"False",
")",
"def",
"get_device_sensors",
"(",
"device_id",
")",
":",
"\"\"\"Get device sensors.\"\"\"",
"return",
"hass",
".",
"data",
"[",
"PLAATO_DOMAIN",
"]",
".",
"get",
"(",
"device_id",
")",
".",
"get",
"(",
"PLAATO_DEVICE_SENSORS",
")",
"async",
"def",
"_update_sensor",
"(",
"device_id",
")",
":",
"\"\"\"Update/Create the sensors.\"\"\"",
"if",
"device_id",
"not",
"in",
"devices",
"and",
"get_device",
"(",
"device_id",
")",
":",
"entities",
"=",
"[",
"]",
"sensors",
"=",
"get_device_sensors",
"(",
"device_id",
")",
"for",
"sensor_type",
"in",
"sensors",
":",
"entities",
".",
"append",
"(",
"PlaatoSensor",
"(",
"device_id",
",",
"sensor_type",
")",
")",
"devices",
"[",
"device_id",
"]",
"=",
"entities",
"async_add_entities",
"(",
"entities",
",",
"True",
")",
"else",
":",
"for",
"entity",
"in",
"devices",
"[",
"device_id",
"]",
":",
"async_dispatcher_send",
"(",
"hass",
",",
"f\"{PLAATO_DOMAIN}_{entity.unique_id}\"",
")",
"hass",
".",
"data",
"[",
"SENSOR_DATA_KEY",
"]",
"=",
"async_dispatcher_connect",
"(",
"hass",
",",
"SENSOR_UPDATE",
",",
"_update_sensor",
")",
"return",
"True"
] | [
33,
0
] | [
65,
15
] | python | en | ['en', 'en', 'en'] | True |
PlaatoSensor.__init__ | (self, device_id, sensor_type) | Initialize the sensor. | Initialize the sensor. | def __init__(self, device_id, sensor_type):
"""Initialize the sensor."""
self._device_id = device_id
self._type = sensor_type
self._state = 0
self._name = f"{device_id} {sensor_type}"
self._attributes = None | [
"def",
"__init__",
"(",
"self",
",",
"device_id",
",",
"sensor_type",
")",
":",
"self",
".",
"_device_id",
"=",
"device_id",
"self",
".",
"_type",
"=",
"sensor_type",
"self",
".",
"_state",
"=",
"0",
"self",
".",
"_name",
"=",
"f\"{device_id} {sensor_type}\"",
"self",
".",
"_attributes",
"=",
"None"
] | [
71,
4
] | [
77,
31
] | python | en | ['en', 'en', 'en'] | True |
PlaatoSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return f"{PLAATO_DOMAIN} {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{PLAATO_DOMAIN} {self._name}\""
] | [
80,
4
] | [
82,
46
] | python | en | ['en', 'mi', 'en'] | True |
PlaatoSensor.unique_id | (self) | Return the unique ID of this sensor. | Return the unique ID of this sensor. | def unique_id(self):
"""Return the unique ID of this sensor."""
return f"{self._device_id}_{self._type}" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self._device_id}_{self._type}\""
] | [
85,
4
] | [
87,
48
] | python | en | ['en', 'la', 'en'] | True |
PlaatoSensor.device_info | (self) | Get device info. | Get device info. | def device_info(self):
"""Get device info."""
return {
"identifiers": {(PLAATO_DOMAIN, self._device_id)},
"name": self._device_id,
"manufacturer": "Plaato",
"model": "Airlock",
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"PLAATO_DOMAIN",
",",
"self",
".",
"_device_id",
")",
"}",
",",
"\"name\"",
":",
"self",
".",
"_device_id",
",",
"\"manufacturer\"",
":",
"\"Plaato\"",
",",
"\"model\"",
":",
"\"Airlock\"",
",",
"}"
] | [
90,
4
] | [
97,
9
] | python | en | ['fr', 'en', 'en'] | True |
PlaatoSensor.get_sensors | (self) | Get device sensors. | Get device sensors. | def get_sensors(self):
"""Get device sensors."""
return (
self.hass.data[PLAATO_DOMAIN]
.get(self._device_id)
.get(PLAATO_DEVICE_SENSORS, False)
) | [
"def",
"get_sensors",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"hass",
".",
"data",
"[",
"PLAATO_DOMAIN",
"]",
".",
"get",
"(",
"self",
".",
"_device_id",
")",
".",
"get",
"(",
"PLAATO_DEVICE_SENSORS",
",",
"False",
")",
")"
] | [
99,
4
] | [
105,
9
] | python | bg | ['fr', 'bg', 'en'] | False |
PlaatoSensor.get_sensors_unit_of_measurement | (self, sensor_type) | Get unit of measurement for sensor of type. | Get unit of measurement for sensor of type. | def get_sensors_unit_of_measurement(self, sensor_type):
"""Get unit of measurement for sensor of type."""
return (
self.hass.data[PLAATO_DOMAIN]
.get(self._device_id)
.get(PLAATO_DEVICE_ATTRS, [])
.get(sensor_type, "")
) | [
"def",
"get_sensors_unit_of_measurement",
"(",
"self",
",",
"sensor_type",
")",
":",
"return",
"(",
"self",
".",
"hass",
".",
"data",
"[",
"PLAATO_DOMAIN",
"]",
".",
"get",
"(",
"self",
".",
"_device_id",
")",
".",
"get",
"(",
"PLAATO_DEVICE_ATTRS",
",",
"[",
"]",
")",
".",
"get",
"(",
"sensor_type",
",",
"\"\"",
")",
")"
] | [
107,
4
] | [
114,
9
] | python | en | ['en', 'en', 'en'] | True |
PlaatoSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
sensors = self.get_sensors()
if sensors is False:
_LOGGER.debug("Device with name %s has no sensors", self.name)
return 0
if self._type == ATTR_ABV:
return round(sensors.get(self._type), 2)
if self._type == ATTR_TEMP:
return round(sensors.get(self._type), 1)
if self._type == ATTR_CO2_VOLUME:
return round(sensors.get(self._type), 2)
return sensors.get(self._type) | [
"def",
"state",
"(",
"self",
")",
":",
"sensors",
"=",
"self",
".",
"get_sensors",
"(",
")",
"if",
"sensors",
"is",
"False",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Device with name %s has no sensors\"",
",",
"self",
".",
"name",
")",
"return",
"0",
"if",
"self",
".",
"_type",
"==",
"ATTR_ABV",
":",
"return",
"round",
"(",
"sensors",
".",
"get",
"(",
"self",
".",
"_type",
")",
",",
"2",
")",
"if",
"self",
".",
"_type",
"==",
"ATTR_TEMP",
":",
"return",
"round",
"(",
"sensors",
".",
"get",
"(",
"self",
".",
"_type",
")",
",",
"1",
")",
"if",
"self",
".",
"_type",
"==",
"ATTR_CO2_VOLUME",
":",
"return",
"round",
"(",
"sensors",
".",
"get",
"(",
"self",
".",
"_type",
")",
",",
"2",
")",
"return",
"sensors",
".",
"get",
"(",
"self",
".",
"_type",
")"
] | [
117,
4
] | [
130,
38
] | python | en | ['en', 'en', 'en'] | True |
PlaatoSensor.device_state_attributes | (self) | Return the state attributes of the monitored installation. | Return the state attributes of the monitored installation. | def device_state_attributes(self):
"""Return the state attributes of the monitored installation."""
if self._attributes is not None:
return self._attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_attributes",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_attributes"
] | [
133,
4
] | [
136,
35
] | python | en | ['en', 'en', 'en'] | True |
PlaatoSensor.unit_of_measurement | (self) | Return the unit of measurement. | Return the unit of measurement. | def unit_of_measurement(self):
"""Return the unit of measurement."""
if self._type == ATTR_TEMP:
return self.get_sensors_unit_of_measurement(ATTR_TEMP_UNIT)
if self._type == ATTR_BATCH_VOLUME or self._type == ATTR_CO2_VOLUME:
return self.get_sensors_unit_of_measurement(ATTR_VOLUME_UNIT)
if self._type == ATTR_BPM:
return "bpm"
if self._type == ATTR_ABV:
return PERCENTAGE
return "" | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"if",
"self",
".",
"_type",
"==",
"ATTR_TEMP",
":",
"return",
"self",
".",
"get_sensors_unit_of_measurement",
"(",
"ATTR_TEMP_UNIT",
")",
"if",
"self",
".",
"_type",
"==",
"ATTR_BATCH_VOLUME",
"or",
"self",
".",
"_type",
"==",
"ATTR_CO2_VOLUME",
":",
"return",
"self",
".",
"get_sensors_unit_of_measurement",
"(",
"ATTR_VOLUME_UNIT",
")",
"if",
"self",
".",
"_type",
"==",
"ATTR_BPM",
":",
"return",
"\"bpm\"",
"if",
"self",
".",
"_type",
"==",
"ATTR_ABV",
":",
"return",
"PERCENTAGE",
"return",
"\"\""
] | [
139,
4
] | [
150,
17
] | python | en | ['en', 'la', 'en'] | True |
PlaatoSensor.should_poll | (self) | Return the polling state. | Return the polling state. | def should_poll(self):
"""Return the polling state."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
153,
4
] | [
155,
20
] | python | en | ['en', 'en', 'en'] | True |
PlaatoSensor.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
f"{PLAATO_DOMAIN}_{self.unique_id}", self.async_write_ha_state
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"hass",
".",
"helpers",
".",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"f\"{PLAATO_DOMAIN}_{self.unique_id}\"",
",",
"self",
".",
"async_write_ha_state",
")",
")"
] | [
157,
4
] | [
163,
9
] | python | en | ['en', 'no', 'en'] | False |
async_setup_entry | (
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) | Set up ESPHome switches based on a config entry. | Set up ESPHome switches based on a config entry. | async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up ESPHome switches based on a config entry."""
await platform_async_setup_entry(
hass,
entry,
async_add_entities,
component_key="switch",
info_type=SwitchInfo,
entity_type=EsphomeSwitch,
state_type=SwitchState,
) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
")",
"->",
"None",
":",
"await",
"platform_async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
",",
"component_key",
"=",
"\"switch\"",
",",
"info_type",
"=",
"SwitchInfo",
",",
"entity_type",
"=",
"EsphomeSwitch",
",",
"state_type",
"=",
"SwitchState",
",",
")"
] | [
12,
0
] | [
24,
5
] | python | en | ['en', 'en', 'en'] | True |
EsphomeSwitch.icon | (self) | Return the icon. | Return the icon. | def icon(self) -> str:
"""Return the icon."""
return self._static_info.icon | [
"def",
"icon",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_static_info",
".",
"icon"
] | [
39,
4
] | [
41,
37
] | python | en | ['en', 'sr', 'en'] | True |
EsphomeSwitch.assumed_state | (self) | Return true if we do optimistic updates. | Return true if we do optimistic updates. | def assumed_state(self) -> bool:
"""Return true if we do optimistic updates."""
return self._static_info.assumed_state | [
"def",
"assumed_state",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_static_info",
".",
"assumed_state"
] | [
44,
4
] | [
46,
46
] | python | en | ['pt', 'la', 'en'] | False |
EsphomeSwitch.is_on | (self) | Return true if the switch is on. | Return true if the switch is on. | def is_on(self) -> Optional[bool]:
"""Return true if the switch is on."""
return self._state.state | [
"def",
"is_on",
"(",
"self",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"return",
"self",
".",
"_state",
".",
"state"
] | [
51,
4
] | [
53,
32
] | python | en | ['en', 'en', 'en'] | True |
EsphomeSwitch.async_turn_on | (self, **kwargs) | Turn the entity on. | Turn the entity on. | async def async_turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
await self._client.switch_command(self._static_info.key, True) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"await",
"self",
".",
"_client",
".",
"switch_command",
"(",
"self",
".",
"_static_info",
".",
"key",
",",
"True",
")"
] | [
55,
4
] | [
57,
70
] | python | en | ['en', 'en', 'en'] | True |
EsphomeSwitch.async_turn_off | (self, **kwargs) | Turn the entity off. | Turn the entity off. | async def async_turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
await self._client.switch_command(self._static_info.key, False) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"await",
"self",
".",
"_client",
".",
"switch_command",
"(",
"self",
".",
"_static_info",
".",
"key",
",",
"False",
")"
] | [
59,
4
] | [
61,
71
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Zabbix sensor platform. | Set up the Zabbix sensor platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Zabbix sensor platform."""
sensors = []
zapi = hass.data[zabbix.DOMAIN]
if not zapi:
_LOGGER.error("zapi is None. Zabbix integration hasn't been loaded?")
return False
_LOGGER.info("Connected to Zabbix API Version %s", zapi.api_version())
trigger_conf = config.get(_CONF_TRIGGERS)
# The following code seems overly complex. Need to think about this...
if trigger_conf:
hostids = trigger_conf.get(_CONF_HOSTIDS)
individual = trigger_conf.get(_CONF_INDIVIDUAL)
name = trigger_conf.get(CONF_NAME)
if individual:
# Individual sensor per host
if not hostids:
# We need hostids
_LOGGER.error("If using 'individual', must specify hostids")
return False
for hostid in hostids:
_LOGGER.debug("Creating Zabbix Sensor: %s", str(hostid))
sensor = ZabbixSingleHostTriggerCountSensor(zapi, [hostid], name)
sensors.append(sensor)
else:
if not hostids:
# Single sensor that provides the total count of triggers.
_LOGGER.debug("Creating Zabbix Sensor")
sensor = ZabbixTriggerCountSensor(zapi, name)
else:
# Single sensor that sums total issues for all hosts
_LOGGER.debug("Creating Zabbix Sensor group: %s", str(hostids))
sensor = ZabbixMultipleHostTriggerCountSensor(zapi, hostids, name)
sensors.append(sensor)
else:
# Single sensor that provides the total count of triggers.
_LOGGER.debug("Creating Zabbix Sensor")
sensor = ZabbixTriggerCountSensor(zapi)
sensors.append(sensor)
add_entities(sensors) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"sensors",
"=",
"[",
"]",
"zapi",
"=",
"hass",
".",
"data",
"[",
"zabbix",
".",
"DOMAIN",
"]",
"if",
"not",
"zapi",
":",
"_LOGGER",
".",
"error",
"(",
"\"zapi is None. Zabbix integration hasn't been loaded?\"",
")",
"return",
"False",
"_LOGGER",
".",
"info",
"(",
"\"Connected to Zabbix API Version %s\"",
",",
"zapi",
".",
"api_version",
"(",
")",
")",
"trigger_conf",
"=",
"config",
".",
"get",
"(",
"_CONF_TRIGGERS",
")",
"# The following code seems overly complex. Need to think about this...",
"if",
"trigger_conf",
":",
"hostids",
"=",
"trigger_conf",
".",
"get",
"(",
"_CONF_HOSTIDS",
")",
"individual",
"=",
"trigger_conf",
".",
"get",
"(",
"_CONF_INDIVIDUAL",
")",
"name",
"=",
"trigger_conf",
".",
"get",
"(",
"CONF_NAME",
")",
"if",
"individual",
":",
"# Individual sensor per host",
"if",
"not",
"hostids",
":",
"# We need hostids",
"_LOGGER",
".",
"error",
"(",
"\"If using 'individual', must specify hostids\"",
")",
"return",
"False",
"for",
"hostid",
"in",
"hostids",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Creating Zabbix Sensor: %s\"",
",",
"str",
"(",
"hostid",
")",
")",
"sensor",
"=",
"ZabbixSingleHostTriggerCountSensor",
"(",
"zapi",
",",
"[",
"hostid",
"]",
",",
"name",
")",
"sensors",
".",
"append",
"(",
"sensor",
")",
"else",
":",
"if",
"not",
"hostids",
":",
"# Single sensor that provides the total count of triggers.",
"_LOGGER",
".",
"debug",
"(",
"\"Creating Zabbix Sensor\"",
")",
"sensor",
"=",
"ZabbixTriggerCountSensor",
"(",
"zapi",
",",
"name",
")",
"else",
":",
"# Single sensor that sums total issues for all hosts",
"_LOGGER",
".",
"debug",
"(",
"\"Creating Zabbix Sensor group: %s\"",
",",
"str",
"(",
"hostids",
")",
")",
"sensor",
"=",
"ZabbixMultipleHostTriggerCountSensor",
"(",
"zapi",
",",
"hostids",
",",
"name",
")",
"sensors",
".",
"append",
"(",
"sensor",
")",
"else",
":",
"# Single sensor that provides the total count of triggers.",
"_LOGGER",
".",
"debug",
"(",
"\"Creating Zabbix Sensor\"",
")",
"sensor",
"=",
"ZabbixTriggerCountSensor",
"(",
"zapi",
")",
"sensors",
".",
"append",
"(",
"sensor",
")",
"add_entities",
"(",
"sensors",
")"
] | [
33,
0
] | [
78,
25
] | python | en | ['en', 'cs', 'en'] | True |
ZabbixTriggerCountSensor.__init__ | (self, zApi, name="Zabbix") | Initialize Zabbix sensor. | Initialize Zabbix sensor. | def __init__(self, zApi, name="Zabbix"):
"""Initialize Zabbix sensor."""
self._name = name
self._zapi = zApi
self._state = None
self._attributes = {} | [
"def",
"__init__",
"(",
"self",
",",
"zApi",
",",
"name",
"=",
"\"Zabbix\"",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_zapi",
"=",
"zApi",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_attributes",
"=",
"{",
"}"
] | [
84,
4
] | [
89,
29
] | python | it | ['mt', 'pl', 'it'] | False |
ZabbixTriggerCountSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
92,
4
] | [
94,
25
] | python | en | ['en', 'mi', 'en'] | True |
ZabbixTriggerCountSensor.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"
] | [
97,
4
] | [
99,
26
] | python | en | ['en', 'en', 'en'] | True |
ZabbixTriggerCountSensor.unit_of_measurement | (self) | Return the units of measurement. | Return the units of measurement. | def unit_of_measurement(self):
"""Return the units of measurement."""
return "issues" | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"\"issues\""
] | [
102,
4
] | [
104,
23
] | python | en | ['en', 'bg', 'en'] | True |
ZabbixTriggerCountSensor.update | (self) | Update the sensor. | Update the sensor. | def update(self):
"""Update the sensor."""
_LOGGER.debug("Updating ZabbixTriggerCountSensor: %s", str(self._name))
triggers = self._call_zabbix_api()
self._state = len(triggers) | [
"def",
"update",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Updating ZabbixTriggerCountSensor: %s\"",
",",
"str",
"(",
"self",
".",
"_name",
")",
")",
"triggers",
"=",
"self",
".",
"_call_zabbix_api",
"(",
")",
"self",
".",
"_state",
"=",
"len",
"(",
"triggers",
")"
] | [
111,
4
] | [
115,
35
] | python | en | ['en', 'nl', 'en'] | True |
ZabbixTriggerCountSensor.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."""
return self._attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_attributes"
] | [
118,
4
] | [
120,
31
] | python | en | ['en', 'en', 'en'] | True |
ZabbixSingleHostTriggerCountSensor.__init__ | (self, zApi, hostid, name=None) | Initialize Zabbix sensor. | Initialize Zabbix sensor. | def __init__(self, zApi, hostid, name=None):
"""Initialize Zabbix sensor."""
super().__init__(zApi, name)
self._hostid = hostid
if not name:
self._name = self._zapi.host.get(hostids=self._hostid, output="extend")[0][
"name"
]
self._attributes["Host ID"] = self._hostid | [
"def",
"__init__",
"(",
"self",
",",
"zApi",
",",
"hostid",
",",
"name",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"zApi",
",",
"name",
")",
"self",
".",
"_hostid",
"=",
"hostid",
"if",
"not",
"name",
":",
"self",
".",
"_name",
"=",
"self",
".",
"_zapi",
".",
"host",
".",
"get",
"(",
"hostids",
"=",
"self",
".",
"_hostid",
",",
"output",
"=",
"\"extend\"",
")",
"[",
"0",
"]",
"[",
"\"name\"",
"]",
"self",
".",
"_attributes",
"[",
"\"Host ID\"",
"]",
"=",
"self",
".",
"_hostid"
] | [
126,
4
] | [
135,
50
] | python | it | ['mt', 'pl', 'it'] | False |
ZabbixMultipleHostTriggerCountSensor.__init__ | (self, zApi, hostids, name=None) | Initialize Zabbix sensor. | Initialize Zabbix sensor. | def __init__(self, zApi, hostids, name=None):
"""Initialize Zabbix sensor."""
super().__init__(zApi, name)
self._hostids = hostids
if not name:
host_names = self._zapi.host.get(hostids=self._hostids, output="extend")
self._name = " ".join(name["name"] for name in host_names)
self._attributes["Host IDs"] = self._hostids | [
"def",
"__init__",
"(",
"self",
",",
"zApi",
",",
"hostids",
",",
"name",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"zApi",
",",
"name",
")",
"self",
".",
"_hostids",
"=",
"hostids",
"if",
"not",
"name",
":",
"host_names",
"=",
"self",
".",
"_zapi",
".",
"host",
".",
"get",
"(",
"hostids",
"=",
"self",
".",
"_hostids",
",",
"output",
"=",
"\"extend\"",
")",
"self",
".",
"_name",
"=",
"\" \"",
".",
"join",
"(",
"name",
"[",
"\"name\"",
"]",
"for",
"name",
"in",
"host_names",
")",
"self",
".",
"_attributes",
"[",
"\"Host IDs\"",
"]",
"=",
"self",
".",
"_hostids"
] | [
150,
4
] | [
157,
52
] | python | it | ['mt', 'pl', 'it'] | False |
async_setup | (hass: HomeAssistant, config: dict) | Set up the Risco component. | Set up the Risco component. | async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Risco component."""
hass.data.setdefault(DOMAIN, {})
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
":",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"return",
"True"
] | [
29,
0
] | [
32,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass: HomeAssistant, entry: ConfigEntry) | Set up Risco from a config entry. | Set up Risco from a config entry. | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Risco from a config entry."""
data = entry.data
risco = RiscoAPI(data[CONF_USERNAME], data[CONF_PASSWORD], data[CONF_PIN])
try:
await risco.login(async_get_clientsession(hass))
except CannotConnectError as error:
raise ConfigEntryNotReady() from error
except UnauthorizedError:
_LOGGER.exception("Failed to login to Risco cloud")
return False
scan_interval = entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
coordinator = RiscoDataUpdateCoordinator(hass, risco, scan_interval)
await coordinator.async_refresh()
events_coordinator = RiscoEventsDataUpdateCoordinator(
hass, risco, entry.entry_id, 60
)
undo_listener = entry.add_update_listener(_update_listener)
hass.data[DOMAIN][entry.entry_id] = {
DATA_COORDINATOR: coordinator,
UNDO_UPDATE_LISTENER: undo_listener,
EVENTS_COORDINATOR: events_coordinator,
}
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"data",
"=",
"entry",
".",
"data",
"risco",
"=",
"RiscoAPI",
"(",
"data",
"[",
"CONF_USERNAME",
"]",
",",
"data",
"[",
"CONF_PASSWORD",
"]",
",",
"data",
"[",
"CONF_PIN",
"]",
")",
"try",
":",
"await",
"risco",
".",
"login",
"(",
"async_get_clientsession",
"(",
"hass",
")",
")",
"except",
"CannotConnectError",
"as",
"error",
":",
"raise",
"ConfigEntryNotReady",
"(",
")",
"from",
"error",
"except",
"UnauthorizedError",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Failed to login to Risco cloud\"",
")",
"return",
"False",
"scan_interval",
"=",
"entry",
".",
"options",
".",
"get",
"(",
"CONF_SCAN_INTERVAL",
",",
"DEFAULT_SCAN_INTERVAL",
")",
"coordinator",
"=",
"RiscoDataUpdateCoordinator",
"(",
"hass",
",",
"risco",
",",
"scan_interval",
")",
"await",
"coordinator",
".",
"async_refresh",
"(",
")",
"events_coordinator",
"=",
"RiscoEventsDataUpdateCoordinator",
"(",
"hass",
",",
"risco",
",",
"entry",
".",
"entry_id",
",",
"60",
")",
"undo_listener",
"=",
"entry",
".",
"add_update_listener",
"(",
"_update_listener",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"=",
"{",
"DATA_COORDINATOR",
":",
"coordinator",
",",
"UNDO_UPDATE_LISTENER",
":",
"undo_listener",
",",
"EVENTS_COORDINATOR",
":",
"events_coordinator",
",",
"}",
"for",
"component",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"component",
")",
")",
"return",
"True"
] | [
35,
0
] | [
67,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass: HomeAssistant, entry: ConfigEntry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENER]()
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"unload_ok",
"=",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"entry",
",",
"component",
")",
"for",
"component",
"in",
"PLATFORMS",
"]",
")",
")",
"if",
"unload_ok",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"UNDO_UPDATE_LISTENER",
"]",
"(",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"pop",
"(",
"entry",
".",
"entry_id",
")",
"return",
"unload_ok"
] | [
70,
0
] | [
85,
20
] | python | en | ['en', 'es', 'en'] | True |
_update_listener | (hass: HomeAssistant, entry: ConfigEntry) | Handle options update. | Handle options update. | async def _update_listener(hass: HomeAssistant, entry: ConfigEntry):
"""Handle options update."""
await hass.config_entries.async_reload(entry.entry_id) | [
"async",
"def",
"_update_listener",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"await",
"hass",
".",
"config_entries",
".",
"async_reload",
"(",
"entry",
".",
"entry_id",
")"
] | [
88,
0
] | [
90,
58
] | python | en | ['en', 'nl', 'en'] | True |
RiscoDataUpdateCoordinator.__init__ | (self, hass, risco, scan_interval) | Initialize global risco data updater. | Initialize global risco data updater. | def __init__(self, hass, risco, scan_interval):
"""Initialize global risco data updater."""
self.risco = risco
interval = timedelta(seconds=scan_interval)
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=interval,
) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"risco",
",",
"scan_interval",
")",
":",
"self",
".",
"risco",
"=",
"risco",
"interval",
"=",
"timedelta",
"(",
"seconds",
"=",
"scan_interval",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"hass",
",",
"_LOGGER",
",",
"name",
"=",
"DOMAIN",
",",
"update_interval",
"=",
"interval",
",",
")"
] | [
96,
4
] | [
105,
9
] | python | co | ['it', 'co', 'pt'] | False |
RiscoDataUpdateCoordinator._async_update_data | (self) | Fetch data from risco. | Fetch data from risco. | async def _async_update_data(self):
"""Fetch data from risco."""
try:
return await self.risco.get_state()
except (CannotConnectError, UnauthorizedError, OperationError) as error:
raise UpdateFailed(error) from error | [
"async",
"def",
"_async_update_data",
"(",
"self",
")",
":",
"try",
":",
"return",
"await",
"self",
".",
"risco",
".",
"get_state",
"(",
")",
"except",
"(",
"CannotConnectError",
",",
"UnauthorizedError",
",",
"OperationError",
")",
"as",
"error",
":",
"raise",
"UpdateFailed",
"(",
"error",
")",
"from",
"error"
] | [
107,
4
] | [
112,
48
] | python | en | ['en', 'en', 'en'] | True |
RiscoEventsDataUpdateCoordinator.__init__ | (self, hass, risco, eid, scan_interval) | Initialize global risco data updater. | Initialize global risco data updater. | def __init__(self, hass, risco, eid, scan_interval):
"""Initialize global risco data updater."""
self.risco = risco
self._store = Store(
hass, LAST_EVENT_STORAGE_VERSION, f"risco_{eid}_last_event_timestamp"
)
interval = timedelta(seconds=scan_interval)
super().__init__(
hass,
_LOGGER,
name=f"{DOMAIN}_events",
update_interval=interval,
) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"risco",
",",
"eid",
",",
"scan_interval",
")",
":",
"self",
".",
"risco",
"=",
"risco",
"self",
".",
"_store",
"=",
"Store",
"(",
"hass",
",",
"LAST_EVENT_STORAGE_VERSION",
",",
"f\"risco_{eid}_last_event_timestamp\"",
")",
"interval",
"=",
"timedelta",
"(",
"seconds",
"=",
"scan_interval",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"hass",
",",
"_LOGGER",
",",
"name",
"=",
"f\"{DOMAIN}_events\"",
",",
"update_interval",
"=",
"interval",
",",
")"
] | [
118,
4
] | [
130,
9
] | python | co | ['it', 'co', 'pt'] | False |
RiscoEventsDataUpdateCoordinator._async_update_data | (self) | Fetch data from risco. | Fetch data from risco. | async def _async_update_data(self):
"""Fetch data from risco."""
last_store = await self._store.async_load() or {}
last_timestamp = last_store.get(
LAST_EVENT_TIMESTAMP_KEY, "2020-01-01T00:00:00Z"
)
try:
events = await self.risco.get_events(last_timestamp, 10)
except (CannotConnectError, UnauthorizedError, OperationError) as error:
raise UpdateFailed(error) from error
if len(events) > 0:
await self._store.async_save({LAST_EVENT_TIMESTAMP_KEY: events[0].time})
return events | [
"async",
"def",
"_async_update_data",
"(",
"self",
")",
":",
"last_store",
"=",
"await",
"self",
".",
"_store",
".",
"async_load",
"(",
")",
"or",
"{",
"}",
"last_timestamp",
"=",
"last_store",
".",
"get",
"(",
"LAST_EVENT_TIMESTAMP_KEY",
",",
"\"2020-01-01T00:00:00Z\"",
")",
"try",
":",
"events",
"=",
"await",
"self",
".",
"risco",
".",
"get_events",
"(",
"last_timestamp",
",",
"10",
")",
"except",
"(",
"CannotConnectError",
",",
"UnauthorizedError",
",",
"OperationError",
")",
"as",
"error",
":",
"raise",
"UpdateFailed",
"(",
"error",
")",
"from",
"error",
"if",
"len",
"(",
"events",
")",
">",
"0",
":",
"await",
"self",
".",
"_store",
".",
"async_save",
"(",
"{",
"LAST_EVENT_TIMESTAMP_KEY",
":",
"events",
"[",
"0",
"]",
".",
"time",
"}",
")",
"return",
"events"
] | [
132,
4
] | [
146,
21
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up the SleepIQ component.
Will automatically load sensor components to support
devices discovered on the account.
| Set up the SleepIQ component. | def setup(hass, config):
"""Set up the SleepIQ component.
Will automatically load sensor components to support
devices discovered on the account.
"""
username = config[DOMAIN][CONF_USERNAME]
password = config[DOMAIN][CONF_PASSWORD]
client = Sleepyq(username, password)
try:
data = SleepIQData(client)
data.update()
except ValueError:
message = """
SleepIQ failed to login, double check your username and password"
"""
_LOGGER.error(message)
return False
hass.data[DOMAIN] = data
discovery.load_platform(hass, "sensor", DOMAIN, {}, config)
discovery.load_platform(hass, "binary_sensor", DOMAIN, {}, config)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"username",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_USERNAME",
"]",
"password",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_PASSWORD",
"]",
"client",
"=",
"Sleepyq",
"(",
"username",
",",
"password",
")",
"try",
":",
"data",
"=",
"SleepIQData",
"(",
"client",
")",
"data",
".",
"update",
"(",
")",
"except",
"ValueError",
":",
"message",
"=",
"\"\"\"\n SleepIQ failed to login, double check your username and password\"\n \"\"\"",
"_LOGGER",
".",
"error",
"(",
"message",
")",
"return",
"False",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"data",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"\"sensor\"",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"\"binary_sensor\"",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"return",
"True"
] | [
32,
0
] | [
55,
15
] | python | en | ['en', 'bg', 'en'] | True |
SleepIQData.__init__ | (self, client) | Initialize the data object. | Initialize the data object. | def __init__(self, client):
"""Initialize the data object."""
self._client = client
self.beds = {}
self.update() | [
"def",
"__init__",
"(",
"self",
",",
"client",
")",
":",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"beds",
"=",
"{",
"}",
"self",
".",
"update",
"(",
")"
] | [
61,
4
] | [
66,
21
] | python | en | ['en', 'en', 'en'] | True |
SleepIQData.update | (self) | Get the latest data from SleepIQ. | Get the latest data from SleepIQ. | def update(self):
"""Get the latest data from SleepIQ."""
self._client.login()
beds = self._client.beds_with_sleeper_status()
self.beds = {bed.bed_id: bed for bed in beds} | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_client",
".",
"login",
"(",
")",
"beds",
"=",
"self",
".",
"_client",
".",
"beds_with_sleeper_status",
"(",
")",
"self",
".",
"beds",
"=",
"{",
"bed",
".",
"bed_id",
":",
"bed",
"for",
"bed",
"in",
"beds",
"}"
] | [
69,
4
] | [
74,
53
] | python | en | ['en', 'en', 'en'] | True |
SleepIQSensor.__init__ | (self, sleepiq_data, bed_id, side) | Initialize the sensor. | Initialize the sensor. | def __init__(self, sleepiq_data, bed_id, side):
"""Initialize the sensor."""
self._bed_id = bed_id
self._side = side
self.sleepiq_data = sleepiq_data
self.side = None
self.bed = None
# added by subclass
self._name = None
self.type = None | [
"def",
"__init__",
"(",
"self",
",",
"sleepiq_data",
",",
"bed_id",
",",
"side",
")",
":",
"self",
".",
"_bed_id",
"=",
"bed_id",
"self",
".",
"_side",
"=",
"side",
"self",
".",
"sleepiq_data",
"=",
"sleepiq_data",
"self",
".",
"side",
"=",
"None",
"self",
".",
"bed",
"=",
"None",
"# added by subclass",
"self",
".",
"_name",
"=",
"None",
"self",
".",
"type",
"=",
"None"
] | [
80,
4
] | [
90,
24
] | python | en | ['en', 'en', 'en'] | True |
SleepIQSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return "SleepNumber {} {} {}".format(
self.bed.name, self.side.sleeper.first_name, self._name
) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"\"SleepNumber {} {} {}\"",
".",
"format",
"(",
"self",
".",
"bed",
".",
"name",
",",
"self",
".",
"side",
".",
"sleeper",
".",
"first_name",
",",
"self",
".",
"_name",
")"
] | [
93,
4
] | [
97,
9
] | python | en | ['en', 'mi', 'en'] | True |
SleepIQSensor.update | (self) | Get the latest data from SleepIQ and updates the states. | Get the latest data from SleepIQ and updates the states. | def update(self):
"""Get the latest data from SleepIQ and updates the states."""
# Call the API for new sleepiq data. Each sensor will re-trigger this
# same exact call, but that's fine. We cache results for a short period
# of time to prevent hitting API limits.
self.sleepiq_data.update()
self.bed = self.sleepiq_data.beds[self._bed_id]
self.side = getattr(self.bed, self._side) | [
"def",
"update",
"(",
"self",
")",
":",
"# Call the API for new sleepiq data. Each sensor will re-trigger this",
"# same exact call, but that's fine. We cache results for a short period",
"# of time to prevent hitting API limits.",
"self",
".",
"sleepiq_data",
".",
"update",
"(",
")",
"self",
".",
"bed",
"=",
"self",
".",
"sleepiq_data",
".",
"beds",
"[",
"self",
".",
"_bed_id",
"]",
"self",
".",
"side",
"=",
"getattr",
"(",
"self",
".",
"bed",
",",
"self",
".",
"_side",
")"
] | [
99,
4
] | [
107,
49
] | python | en | ['en', 'en', 'en'] | True |
registries | (hass) | Registry mock setup. | Registry mock setup. | def registries(hass):
"""Registry mock setup."""
from types import SimpleNamespace
ret = SimpleNamespace()
ret.entity = mock_registry(hass)
ret.device = mock_device_registry(hass)
ret.area = mock_area_registry(hass)
return ret | [
"def",
"registries",
"(",
"hass",
")",
":",
"from",
"types",
"import",
"SimpleNamespace",
"ret",
"=",
"SimpleNamespace",
"(",
")",
"ret",
".",
"entity",
"=",
"mock_registry",
"(",
"hass",
")",
"ret",
".",
"device",
"=",
"mock_device_registry",
"(",
"hass",
")",
"ret",
".",
"area",
"=",
"mock_area_registry",
"(",
"hass",
")",
"return",
"ret"
] | [
37,
0
] | [
45,
14
] | python | en | ['en', 'da', 'en'] | True |
test_sync_message | (hass) | Test a sync message. | Test a sync message. | async def test_sync_message(hass):
"""Test a sync message."""
light = DemoLight(
None,
"Demo Light",
state=False,
hs_color=(180, 75),
effect_list=LIGHT_EFFECT_LIST,
effect=LIGHT_EFFECT_LIST[0],
)
light.hass = hass
light.entity_id = "light.demo_light"
await light.async_update_ha_state()
# This should not show up in the sync request
hass.states.async_set("sensor.no_match", "something")
# Excluded via config
hass.states.async_set("light.not_expose", "on")
config = MockConfig(
should_expose=lambda state: state.entity_id != "light.not_expose",
entity_config={
"light.demo_light": {
const.CONF_ROOM_HINT: "Living Room",
const.CONF_ALIASES: ["Hello", "World"],
}
},
)
events = []
hass.bus.async_listen(EVENT_SYNC_RECEIVED, events.append)
result = await sh.async_handle_message(
hass,
config,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"id": "light.demo_light",
"name": {
"name": "Demo Light",
"nicknames": ["Demo Light", "Hello", "World"],
},
"traits": [
trait.TRAIT_BRIGHTNESS,
trait.TRAIT_ONOFF,
trait.TRAIT_COLOR_SETTING,
trait.TRAIT_MODES,
],
"type": const.TYPE_LIGHT,
"willReportState": False,
"attributes": {
"availableModes": [
{
"name": "effect",
"name_values": [
{"lang": "en", "name_synonym": ["effect"]}
],
"ordered": False,
"settings": [
{
"setting_name": "rainbow",
"setting_values": [
{
"lang": "en",
"setting_synonym": ["rainbow"],
}
],
},
{
"setting_name": "none",
"setting_values": [
{"lang": "en", "setting_synonym": ["none"]}
],
},
],
}
],
"colorModel": "hsv",
"colorTemperatureRange": {
"temperatureMinK": 2000,
"temperatureMaxK": 6535,
},
},
"roomHint": "Living Room",
}
],
},
}
await hass.async_block_till_done()
assert len(events) == 1
assert events[0].event_type == EVENT_SYNC_RECEIVED
assert events[0].data == {"request_id": REQ_ID, "source": "cloud"} | [
"async",
"def",
"test_sync_message",
"(",
"hass",
")",
":",
"light",
"=",
"DemoLight",
"(",
"None",
",",
"\"Demo Light\"",
",",
"state",
"=",
"False",
",",
"hs_color",
"=",
"(",
"180",
",",
"75",
")",
",",
"effect_list",
"=",
"LIGHT_EFFECT_LIST",
",",
"effect",
"=",
"LIGHT_EFFECT_LIST",
"[",
"0",
"]",
",",
")",
"light",
".",
"hass",
"=",
"hass",
"light",
".",
"entity_id",
"=",
"\"light.demo_light\"",
"await",
"light",
".",
"async_update_ha_state",
"(",
")",
"# This should not show up in the sync request",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"sensor.no_match\"",
",",
"\"something\"",
")",
"# Excluded via config",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.not_expose\"",
",",
"\"on\"",
")",
"config",
"=",
"MockConfig",
"(",
"should_expose",
"=",
"lambda",
"state",
":",
"state",
".",
"entity_id",
"!=",
"\"light.not_expose\"",
",",
"entity_config",
"=",
"{",
"\"light.demo_light\"",
":",
"{",
"const",
".",
"CONF_ROOM_HINT",
":",
"\"Living Room\"",
",",
"const",
".",
"CONF_ALIASES",
":",
"[",
"\"Hello\"",
",",
"\"World\"",
"]",
",",
"}",
"}",
",",
")",
"events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_SYNC_RECEIVED",
",",
"events",
".",
"append",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"config",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.demo_light\"",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"Demo Light\"",
",",
"\"nicknames\"",
":",
"[",
"\"Demo Light\"",
",",
"\"Hello\"",
",",
"\"World\"",
"]",
",",
"}",
",",
"\"traits\"",
":",
"[",
"trait",
".",
"TRAIT_BRIGHTNESS",
",",
"trait",
".",
"TRAIT_ONOFF",
",",
"trait",
".",
"TRAIT_COLOR_SETTING",
",",
"trait",
".",
"TRAIT_MODES",
",",
"]",
",",
"\"type\"",
":",
"const",
".",
"TYPE_LIGHT",
",",
"\"willReportState\"",
":",
"False",
",",
"\"attributes\"",
":",
"{",
"\"availableModes\"",
":",
"[",
"{",
"\"name\"",
":",
"\"effect\"",
",",
"\"name_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"name_synonym\"",
":",
"[",
"\"effect\"",
"]",
"}",
"]",
",",
"\"ordered\"",
":",
"False",
",",
"\"settings\"",
":",
"[",
"{",
"\"setting_name\"",
":",
"\"rainbow\"",
",",
"\"setting_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"setting_synonym\"",
":",
"[",
"\"rainbow\"",
"]",
",",
"}",
"]",
",",
"}",
",",
"{",
"\"setting_name\"",
":",
"\"none\"",
",",
"\"setting_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"setting_synonym\"",
":",
"[",
"\"none\"",
"]",
"}",
"]",
",",
"}",
",",
"]",
",",
"}",
"]",
",",
"\"colorModel\"",
":",
"\"hsv\"",
",",
"\"colorTemperatureRange\"",
":",
"{",
"\"temperatureMinK\"",
":",
"2000",
",",
"\"temperatureMaxK\"",
":",
"6535",
",",
"}",
",",
"}",
",",
"\"roomHint\"",
":",
"\"Living Room\"",
",",
"}",
"]",
",",
"}",
",",
"}",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"events",
")",
"==",
"1",
"assert",
"events",
"[",
"0",
"]",
".",
"event_type",
"==",
"EVENT_SYNC_RECEIVED",
"assert",
"events",
"[",
"0",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"source\"",
":",
"\"cloud\"",
"}"
] | [
48,
0
] | [
150,
70
] | python | en | ['en', 'en', 'en'] | True |
test_sync_in_area | (hass, registries) | Test a sync message where room hint comes from area. | Test a sync message where room hint comes from area. | async def test_sync_in_area(hass, registries):
"""Test a sync message where room hint comes from area."""
area = registries.area.async_create("Living Room")
device = registries.device.async_get_or_create(
config_entry_id="1234",
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
registries.device.async_update_device(device.id, area_id=area.id)
entity = registries.entity.async_get_or_create(
"light", "test", "1235", suggested_object_id="demo_light", device_id=device.id
)
light = DemoLight(
None,
"Demo Light",
state=False,
hs_color=(180, 75),
effect_list=LIGHT_EFFECT_LIST,
effect=LIGHT_EFFECT_LIST[0],
)
light.hass = hass
light.entity_id = entity.entity_id
await light.async_update_ha_state()
config = MockConfig(should_expose=lambda _: True, entity_config={})
events = []
hass.bus.async_listen(EVENT_SYNC_RECEIVED, events.append)
result = await sh.async_handle_message(
hass,
config,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"id": "light.demo_light",
"name": {"name": "Demo Light"},
"traits": [
trait.TRAIT_BRIGHTNESS,
trait.TRAIT_ONOFF,
trait.TRAIT_COLOR_SETTING,
trait.TRAIT_MODES,
],
"type": const.TYPE_LIGHT,
"willReportState": False,
"attributes": {
"availableModes": [
{
"name": "effect",
"name_values": [
{"lang": "en", "name_synonym": ["effect"]}
],
"ordered": False,
"settings": [
{
"setting_name": "rainbow",
"setting_values": [
{
"lang": "en",
"setting_synonym": ["rainbow"],
}
],
},
{
"setting_name": "none",
"setting_values": [
{"lang": "en", "setting_synonym": ["none"]}
],
},
],
}
],
"colorModel": "hsv",
"colorTemperatureRange": {
"temperatureMinK": 2000,
"temperatureMaxK": 6535,
},
},
"roomHint": "Living Room",
}
],
},
}
await hass.async_block_till_done()
assert len(events) == 1
assert events[0].event_type == EVENT_SYNC_RECEIVED
assert events[0].data == {"request_id": REQ_ID, "source": "cloud"} | [
"async",
"def",
"test_sync_in_area",
"(",
"hass",
",",
"registries",
")",
":",
"area",
"=",
"registries",
".",
"area",
".",
"async_create",
"(",
"\"Living Room\"",
")",
"device",
"=",
"registries",
".",
"device",
".",
"async_get_or_create",
"(",
"config_entry_id",
"=",
"\"1234\"",
",",
"connections",
"=",
"{",
"(",
"device_registry",
".",
"CONNECTION_NETWORK_MAC",
",",
"\"12:34:56:AB:CD:EF\"",
")",
"}",
",",
")",
"registries",
".",
"device",
".",
"async_update_device",
"(",
"device",
".",
"id",
",",
"area_id",
"=",
"area",
".",
"id",
")",
"entity",
"=",
"registries",
".",
"entity",
".",
"async_get_or_create",
"(",
"\"light\"",
",",
"\"test\"",
",",
"\"1235\"",
",",
"suggested_object_id",
"=",
"\"demo_light\"",
",",
"device_id",
"=",
"device",
".",
"id",
")",
"light",
"=",
"DemoLight",
"(",
"None",
",",
"\"Demo Light\"",
",",
"state",
"=",
"False",
",",
"hs_color",
"=",
"(",
"180",
",",
"75",
")",
",",
"effect_list",
"=",
"LIGHT_EFFECT_LIST",
",",
"effect",
"=",
"LIGHT_EFFECT_LIST",
"[",
"0",
"]",
",",
")",
"light",
".",
"hass",
"=",
"hass",
"light",
".",
"entity_id",
"=",
"entity",
".",
"entity_id",
"await",
"light",
".",
"async_update_ha_state",
"(",
")",
"config",
"=",
"MockConfig",
"(",
"should_expose",
"=",
"lambda",
"_",
":",
"True",
",",
"entity_config",
"=",
"{",
"}",
")",
"events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_SYNC_RECEIVED",
",",
"events",
".",
"append",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"config",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.demo_light\"",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"Demo Light\"",
"}",
",",
"\"traits\"",
":",
"[",
"trait",
".",
"TRAIT_BRIGHTNESS",
",",
"trait",
".",
"TRAIT_ONOFF",
",",
"trait",
".",
"TRAIT_COLOR_SETTING",
",",
"trait",
".",
"TRAIT_MODES",
",",
"]",
",",
"\"type\"",
":",
"const",
".",
"TYPE_LIGHT",
",",
"\"willReportState\"",
":",
"False",
",",
"\"attributes\"",
":",
"{",
"\"availableModes\"",
":",
"[",
"{",
"\"name\"",
":",
"\"effect\"",
",",
"\"name_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"name_synonym\"",
":",
"[",
"\"effect\"",
"]",
"}",
"]",
",",
"\"ordered\"",
":",
"False",
",",
"\"settings\"",
":",
"[",
"{",
"\"setting_name\"",
":",
"\"rainbow\"",
",",
"\"setting_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"setting_synonym\"",
":",
"[",
"\"rainbow\"",
"]",
",",
"}",
"]",
",",
"}",
",",
"{",
"\"setting_name\"",
":",
"\"none\"",
",",
"\"setting_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"setting_synonym\"",
":",
"[",
"\"none\"",
"]",
"}",
"]",
",",
"}",
",",
"]",
",",
"}",
"]",
",",
"\"colorModel\"",
":",
"\"hsv\"",
",",
"\"colorTemperatureRange\"",
":",
"{",
"\"temperatureMinK\"",
":",
"2000",
",",
"\"temperatureMaxK\"",
":",
"6535",
",",
"}",
",",
"}",
",",
"\"roomHint\"",
":",
"\"Living Room\"",
",",
"}",
"]",
",",
"}",
",",
"}",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"events",
")",
"==",
"1",
"assert",
"events",
"[",
"0",
"]",
".",
"event_type",
"==",
"EVENT_SYNC_RECEIVED",
"assert",
"events",
"[",
"0",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"source\"",
":",
"\"cloud\"",
"}"
] | [
154,
0
] | [
251,
70
] | python | en | ['en', 'en', 'en'] | True |
test_query_message | (hass) | Test a sync message. | Test a sync message. | async def test_query_message(hass):
"""Test a sync message."""
light = DemoLight(
None,
"Demo Light",
state=False,
hs_color=(180, 75),
effect_list=LIGHT_EFFECT_LIST,
effect=LIGHT_EFFECT_LIST[0],
)
light.hass = hass
light.entity_id = "light.demo_light"
await light.async_update_ha_state()
light2 = DemoLight(
None, "Another Light", state=True, hs_color=(180, 75), ct=400, brightness=78
)
light2.hass = hass
light2.entity_id = "light.another_light"
await light2.async_update_ha_state()
light3 = DemoLight(None, "Color temp Light", state=True, ct=400, brightness=200)
light3.hass = hass
light3.entity_id = "light.color_temp_light"
await light3.async_update_ha_state()
events = []
hass.bus.async_listen(EVENT_QUERY_RECEIVED, events.append)
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{
"requestId": REQ_ID,
"inputs": [
{
"intent": "action.devices.QUERY",
"payload": {
"devices": [
{"id": "light.demo_light"},
{"id": "light.another_light"},
{"id": "light.color_temp_light"},
{"id": "light.non_existing"},
]
},
}
],
},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"devices": {
"light.non_existing": {"online": False},
"light.demo_light": {"on": False, "online": True, "brightness": 0},
"light.another_light": {
"on": True,
"online": True,
"brightness": 30,
"color": {
"spectrumHsv": {
"hue": 180,
"saturation": 0.75,
"value": 0.3058823529411765,
},
},
},
"light.color_temp_light": {
"on": True,
"online": True,
"brightness": 78,
"color": {"temperatureK": 2500},
},
}
},
}
await hass.async_block_till_done()
assert len(events) == 4
assert events[0].event_type == EVENT_QUERY_RECEIVED
assert events[0].data == {
"request_id": REQ_ID,
"entity_id": "light.demo_light",
"source": "cloud",
}
assert events[1].event_type == EVENT_QUERY_RECEIVED
assert events[1].data == {
"request_id": REQ_ID,
"entity_id": "light.another_light",
"source": "cloud",
}
assert events[2].event_type == EVENT_QUERY_RECEIVED
assert events[2].data == {
"request_id": REQ_ID,
"entity_id": "light.color_temp_light",
"source": "cloud",
}
assert events[3].event_type == EVENT_QUERY_RECEIVED
assert events[3].data == {
"request_id": REQ_ID,
"entity_id": "light.non_existing",
"source": "cloud",
} | [
"async",
"def",
"test_query_message",
"(",
"hass",
")",
":",
"light",
"=",
"DemoLight",
"(",
"None",
",",
"\"Demo Light\"",
",",
"state",
"=",
"False",
",",
"hs_color",
"=",
"(",
"180",
",",
"75",
")",
",",
"effect_list",
"=",
"LIGHT_EFFECT_LIST",
",",
"effect",
"=",
"LIGHT_EFFECT_LIST",
"[",
"0",
"]",
",",
")",
"light",
".",
"hass",
"=",
"hass",
"light",
".",
"entity_id",
"=",
"\"light.demo_light\"",
"await",
"light",
".",
"async_update_ha_state",
"(",
")",
"light2",
"=",
"DemoLight",
"(",
"None",
",",
"\"Another Light\"",
",",
"state",
"=",
"True",
",",
"hs_color",
"=",
"(",
"180",
",",
"75",
")",
",",
"ct",
"=",
"400",
",",
"brightness",
"=",
"78",
")",
"light2",
".",
"hass",
"=",
"hass",
"light2",
".",
"entity_id",
"=",
"\"light.another_light\"",
"await",
"light2",
".",
"async_update_ha_state",
"(",
")",
"light3",
"=",
"DemoLight",
"(",
"None",
",",
"\"Color temp Light\"",
",",
"state",
"=",
"True",
",",
"ct",
"=",
"400",
",",
"brightness",
"=",
"200",
")",
"light3",
".",
"hass",
"=",
"hass",
"light3",
".",
"entity_id",
"=",
"\"light.color_temp_light\"",
"await",
"light3",
".",
"async_update_ha_state",
"(",
")",
"events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_QUERY_RECEIVED",
",",
"events",
".",
"append",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.QUERY\"",
",",
"\"payload\"",
":",
"{",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.demo_light\"",
"}",
",",
"{",
"\"id\"",
":",
"\"light.another_light\"",
"}",
",",
"{",
"\"id\"",
":",
"\"light.color_temp_light\"",
"}",
",",
"{",
"\"id\"",
":",
"\"light.non_existing\"",
"}",
",",
"]",
"}",
",",
"}",
"]",
",",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"devices\"",
":",
"{",
"\"light.non_existing\"",
":",
"{",
"\"online\"",
":",
"False",
"}",
",",
"\"light.demo_light\"",
":",
"{",
"\"on\"",
":",
"False",
",",
"\"online\"",
":",
"True",
",",
"\"brightness\"",
":",
"0",
"}",
",",
"\"light.another_light\"",
":",
"{",
"\"on\"",
":",
"True",
",",
"\"online\"",
":",
"True",
",",
"\"brightness\"",
":",
"30",
",",
"\"color\"",
":",
"{",
"\"spectrumHsv\"",
":",
"{",
"\"hue\"",
":",
"180",
",",
"\"saturation\"",
":",
"0.75",
",",
"\"value\"",
":",
"0.3058823529411765",
",",
"}",
",",
"}",
",",
"}",
",",
"\"light.color_temp_light\"",
":",
"{",
"\"on\"",
":",
"True",
",",
"\"online\"",
":",
"True",
",",
"\"brightness\"",
":",
"78",
",",
"\"color\"",
":",
"{",
"\"temperatureK\"",
":",
"2500",
"}",
",",
"}",
",",
"}",
"}",
",",
"}",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"events",
")",
"==",
"4",
"assert",
"events",
"[",
"0",
"]",
".",
"event_type",
"==",
"EVENT_QUERY_RECEIVED",
"assert",
"events",
"[",
"0",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.demo_light\"",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"1",
"]",
".",
"event_type",
"==",
"EVENT_QUERY_RECEIVED",
"assert",
"events",
"[",
"1",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.another_light\"",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"2",
"]",
".",
"event_type",
"==",
"EVENT_QUERY_RECEIVED",
"assert",
"events",
"[",
"2",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.color_temp_light\"",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"3",
"]",
".",
"event_type",
"==",
"EVENT_QUERY_RECEIVED",
"assert",
"events",
"[",
"3",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.non_existing\"",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}"
] | [
254,
0
] | [
360,
5
] | python | en | ['en', 'en', 'en'] | True |
test_execute | (hass) | Test an execute command. | Test an execute command. | async def test_execute(hass):
"""Test an execute command."""
await async_setup_component(hass, "light", {"light": {"platform": "demo"}})
await hass.async_block_till_done()
await hass.services.async_call(
"light", "turn_off", {"entity_id": "light.ceiling_lights"}, blocking=True
)
events = []
hass.bus.async_listen(EVENT_COMMAND_RECEIVED, events.append)
service_events = []
hass.bus.async_listen(EVENT_CALL_SERVICE, service_events.append)
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
None,
{
"requestId": REQ_ID,
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [
{"id": "light.non_existing"},
{"id": "light.ceiling_lights"},
{"id": "light.kitchen_lights"},
],
"execution": [
{
"command": "action.devices.commands.OnOff",
"params": {"on": True},
},
{
"command": "action.devices.commands.BrightnessAbsolute",
"params": {"brightness": 20},
},
],
}
]
},
}
],
},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"commands": [
{
"ids": ["light.non_existing"],
"status": "ERROR",
"errorCode": "deviceOffline",
},
{
"ids": ["light.ceiling_lights"],
"status": "SUCCESS",
"states": {
"on": True,
"online": True,
"brightness": 20,
"color": {"temperatureK": 2631},
},
},
{
"ids": ["light.kitchen_lights"],
"status": "SUCCESS",
"states": {
"on": True,
"online": True,
"brightness": 20,
"color": {
"spectrumHsv": {
"hue": 345,
"saturation": 0.75,
"value": 0.2,
},
},
},
},
]
},
}
assert len(events) == 6
assert events[0].event_type == EVENT_COMMAND_RECEIVED
assert events[0].data == {
"request_id": REQ_ID,
"entity_id": "light.non_existing",
"execution": {
"command": "action.devices.commands.OnOff",
"params": {"on": True},
},
"source": "cloud",
}
assert events[1].event_type == EVENT_COMMAND_RECEIVED
assert events[1].data == {
"request_id": REQ_ID,
"entity_id": "light.non_existing",
"execution": {
"command": "action.devices.commands.BrightnessAbsolute",
"params": {"brightness": 20},
},
"source": "cloud",
}
assert events[2].event_type == EVENT_COMMAND_RECEIVED
assert events[2].data == {
"request_id": REQ_ID,
"entity_id": "light.ceiling_lights",
"execution": {
"command": "action.devices.commands.OnOff",
"params": {"on": True},
},
"source": "cloud",
}
assert events[3].event_type == EVENT_COMMAND_RECEIVED
assert events[3].data == {
"request_id": REQ_ID,
"entity_id": "light.ceiling_lights",
"execution": {
"command": "action.devices.commands.BrightnessAbsolute",
"params": {"brightness": 20},
},
"source": "cloud",
}
assert events[4].event_type == EVENT_COMMAND_RECEIVED
assert events[4].data == {
"request_id": REQ_ID,
"entity_id": "light.kitchen_lights",
"execution": {
"command": "action.devices.commands.OnOff",
"params": {"on": True},
},
"source": "cloud",
}
assert events[5].event_type == EVENT_COMMAND_RECEIVED
assert events[5].data == {
"request_id": REQ_ID,
"entity_id": "light.kitchen_lights",
"execution": {
"command": "action.devices.commands.BrightnessAbsolute",
"params": {"brightness": 20},
},
"source": "cloud",
}
service_events = sorted(
service_events, key=lambda ev: ev.data["service_data"]["entity_id"]
)
assert len(service_events) == 4
assert service_events[0].data == {
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": "light.ceiling_lights"},
}
assert service_events[1].data == {
"domain": "light",
"service": "turn_on",
"service_data": {"brightness_pct": 20, "entity_id": "light.ceiling_lights"},
}
assert service_events[0].context == events[2].context
assert service_events[1].context == events[2].context
assert service_events[1].context == events[3].context
assert service_events[2].data == {
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": "light.kitchen_lights"},
}
assert service_events[3].data == {
"domain": "light",
"service": "turn_on",
"service_data": {"brightness_pct": 20, "entity_id": "light.kitchen_lights"},
}
assert service_events[2].context == events[4].context
assert service_events[3].context == events[4].context
assert service_events[3].context == events[5].context | [
"async",
"def",
"test_execute",
"(",
"hass",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"light\"",
",",
"{",
"\"light\"",
":",
"{",
"\"platform\"",
":",
"\"demo\"",
"}",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"light\"",
",",
"\"turn_off\"",
",",
"{",
"\"entity_id\"",
":",
"\"light.ceiling_lights\"",
"}",
",",
"blocking",
"=",
"True",
")",
"events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_COMMAND_RECEIVED",
",",
"events",
".",
"append",
")",
"service_events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_CALL_SERVICE",
",",
"service_events",
".",
"append",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"None",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.EXECUTE\"",
",",
"\"payload\"",
":",
"{",
"\"commands\"",
":",
"[",
"{",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.non_existing\"",
"}",
",",
"{",
"\"id\"",
":",
"\"light.ceiling_lights\"",
"}",
",",
"{",
"\"id\"",
":",
"\"light.kitchen_lights\"",
"}",
",",
"]",
",",
"\"execution\"",
":",
"[",
"{",
"\"command\"",
":",
"\"action.devices.commands.OnOff\"",
",",
"\"params\"",
":",
"{",
"\"on\"",
":",
"True",
"}",
",",
"}",
",",
"{",
"\"command\"",
":",
"\"action.devices.commands.BrightnessAbsolute\"",
",",
"\"params\"",
":",
"{",
"\"brightness\"",
":",
"20",
"}",
",",
"}",
",",
"]",
",",
"}",
"]",
"}",
",",
"}",
"]",
",",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"commands\"",
":",
"[",
"{",
"\"ids\"",
":",
"[",
"\"light.non_existing\"",
"]",
",",
"\"status\"",
":",
"\"ERROR\"",
",",
"\"errorCode\"",
":",
"\"deviceOffline\"",
",",
"}",
",",
"{",
"\"ids\"",
":",
"[",
"\"light.ceiling_lights\"",
"]",
",",
"\"status\"",
":",
"\"SUCCESS\"",
",",
"\"states\"",
":",
"{",
"\"on\"",
":",
"True",
",",
"\"online\"",
":",
"True",
",",
"\"brightness\"",
":",
"20",
",",
"\"color\"",
":",
"{",
"\"temperatureK\"",
":",
"2631",
"}",
",",
"}",
",",
"}",
",",
"{",
"\"ids\"",
":",
"[",
"\"light.kitchen_lights\"",
"]",
",",
"\"status\"",
":",
"\"SUCCESS\"",
",",
"\"states\"",
":",
"{",
"\"on\"",
":",
"True",
",",
"\"online\"",
":",
"True",
",",
"\"brightness\"",
":",
"20",
",",
"\"color\"",
":",
"{",
"\"spectrumHsv\"",
":",
"{",
"\"hue\"",
":",
"345",
",",
"\"saturation\"",
":",
"0.75",
",",
"\"value\"",
":",
"0.2",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
",",
"]",
"}",
",",
"}",
"assert",
"len",
"(",
"events",
")",
"==",
"6",
"assert",
"events",
"[",
"0",
"]",
".",
"event_type",
"==",
"EVENT_COMMAND_RECEIVED",
"assert",
"events",
"[",
"0",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.non_existing\"",
",",
"\"execution\"",
":",
"{",
"\"command\"",
":",
"\"action.devices.commands.OnOff\"",
",",
"\"params\"",
":",
"{",
"\"on\"",
":",
"True",
"}",
",",
"}",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"1",
"]",
".",
"event_type",
"==",
"EVENT_COMMAND_RECEIVED",
"assert",
"events",
"[",
"1",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.non_existing\"",
",",
"\"execution\"",
":",
"{",
"\"command\"",
":",
"\"action.devices.commands.BrightnessAbsolute\"",
",",
"\"params\"",
":",
"{",
"\"brightness\"",
":",
"20",
"}",
",",
"}",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"2",
"]",
".",
"event_type",
"==",
"EVENT_COMMAND_RECEIVED",
"assert",
"events",
"[",
"2",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.ceiling_lights\"",
",",
"\"execution\"",
":",
"{",
"\"command\"",
":",
"\"action.devices.commands.OnOff\"",
",",
"\"params\"",
":",
"{",
"\"on\"",
":",
"True",
"}",
",",
"}",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"3",
"]",
".",
"event_type",
"==",
"EVENT_COMMAND_RECEIVED",
"assert",
"events",
"[",
"3",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.ceiling_lights\"",
",",
"\"execution\"",
":",
"{",
"\"command\"",
":",
"\"action.devices.commands.BrightnessAbsolute\"",
",",
"\"params\"",
":",
"{",
"\"brightness\"",
":",
"20",
"}",
",",
"}",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"4",
"]",
".",
"event_type",
"==",
"EVENT_COMMAND_RECEIVED",
"assert",
"events",
"[",
"4",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.kitchen_lights\"",
",",
"\"execution\"",
":",
"{",
"\"command\"",
":",
"\"action.devices.commands.OnOff\"",
",",
"\"params\"",
":",
"{",
"\"on\"",
":",
"True",
"}",
",",
"}",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"assert",
"events",
"[",
"5",
"]",
".",
"event_type",
"==",
"EVENT_COMMAND_RECEIVED",
"assert",
"events",
"[",
"5",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"light.kitchen_lights\"",
",",
"\"execution\"",
":",
"{",
"\"command\"",
":",
"\"action.devices.commands.BrightnessAbsolute\"",
",",
"\"params\"",
":",
"{",
"\"brightness\"",
":",
"20",
"}",
",",
"}",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}",
"service_events",
"=",
"sorted",
"(",
"service_events",
",",
"key",
"=",
"lambda",
"ev",
":",
"ev",
".",
"data",
"[",
"\"service_data\"",
"]",
"[",
"\"entity_id\"",
"]",
")",
"assert",
"len",
"(",
"service_events",
")",
"==",
"4",
"assert",
"service_events",
"[",
"0",
"]",
".",
"data",
"==",
"{",
"\"domain\"",
":",
"\"light\"",
",",
"\"service\"",
":",
"\"turn_on\"",
",",
"\"service_data\"",
":",
"{",
"\"entity_id\"",
":",
"\"light.ceiling_lights\"",
"}",
",",
"}",
"assert",
"service_events",
"[",
"1",
"]",
".",
"data",
"==",
"{",
"\"domain\"",
":",
"\"light\"",
",",
"\"service\"",
":",
"\"turn_on\"",
",",
"\"service_data\"",
":",
"{",
"\"brightness_pct\"",
":",
"20",
",",
"\"entity_id\"",
":",
"\"light.ceiling_lights\"",
"}",
",",
"}",
"assert",
"service_events",
"[",
"0",
"]",
".",
"context",
"==",
"events",
"[",
"2",
"]",
".",
"context",
"assert",
"service_events",
"[",
"1",
"]",
".",
"context",
"==",
"events",
"[",
"2",
"]",
".",
"context",
"assert",
"service_events",
"[",
"1",
"]",
".",
"context",
"==",
"events",
"[",
"3",
"]",
".",
"context",
"assert",
"service_events",
"[",
"2",
"]",
".",
"data",
"==",
"{",
"\"domain\"",
":",
"\"light\"",
",",
"\"service\"",
":",
"\"turn_on\"",
",",
"\"service_data\"",
":",
"{",
"\"entity_id\"",
":",
"\"light.kitchen_lights\"",
"}",
",",
"}",
"assert",
"service_events",
"[",
"3",
"]",
".",
"data",
"==",
"{",
"\"domain\"",
":",
"\"light\"",
",",
"\"service\"",
":",
"\"turn_on\"",
",",
"\"service_data\"",
":",
"{",
"\"brightness_pct\"",
":",
"20",
",",
"\"entity_id\"",
":",
"\"light.kitchen_lights\"",
"}",
",",
"}",
"assert",
"service_events",
"[",
"2",
"]",
".",
"context",
"==",
"events",
"[",
"4",
"]",
".",
"context",
"assert",
"service_events",
"[",
"3",
"]",
".",
"context",
"==",
"events",
"[",
"4",
"]",
".",
"context",
"assert",
"service_events",
"[",
"3",
"]",
".",
"context",
"==",
"events",
"[",
"5",
"]",
".",
"context"
] | [
363,
0
] | [
544,
57
] | python | en | ['en', 'en', 'en'] | True |
test_raising_error_trait | (hass) | Test raising an error while executing a trait command. | Test raising an error while executing a trait command. | async def test_raising_error_trait(hass):
"""Test raising an error while executing a trait command."""
hass.states.async_set(
"climate.bla",
HVAC_MODE_HEAT,
{ATTR_MIN_TEMP: 15, ATTR_MAX_TEMP: 30, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS},
)
events = []
hass.bus.async_listen(EVENT_COMMAND_RECEIVED, events.append)
await hass.async_block_till_done()
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{
"requestId": REQ_ID,
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [{"id": "climate.bla"}],
"execution": [
{
"command": "action.devices.commands."
"ThermostatTemperatureSetpoint",
"params": {"thermostatTemperatureSetpoint": 10},
}
],
}
]
},
}
],
},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"commands": [
{
"ids": ["climate.bla"],
"status": "ERROR",
"errorCode": "valueOutOfRange",
}
]
},
}
assert len(events) == 1
assert events[0].event_type == EVENT_COMMAND_RECEIVED
assert events[0].data == {
"request_id": REQ_ID,
"entity_id": "climate.bla",
"execution": {
"command": "action.devices.commands.ThermostatTemperatureSetpoint",
"params": {"thermostatTemperatureSetpoint": 10},
},
"source": "cloud",
} | [
"async",
"def",
"test_raising_error_trait",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"climate.bla\"",
",",
"HVAC_MODE_HEAT",
",",
"{",
"ATTR_MIN_TEMP",
":",
"15",
",",
"ATTR_MAX_TEMP",
":",
"30",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"TEMP_CELSIUS",
"}",
",",
")",
"events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_COMMAND_RECEIVED",
",",
"events",
".",
"append",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.EXECUTE\"",
",",
"\"payload\"",
":",
"{",
"\"commands\"",
":",
"[",
"{",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"climate.bla\"",
"}",
"]",
",",
"\"execution\"",
":",
"[",
"{",
"\"command\"",
":",
"\"action.devices.commands.\"",
"\"ThermostatTemperatureSetpoint\"",
",",
"\"params\"",
":",
"{",
"\"thermostatTemperatureSetpoint\"",
":",
"10",
"}",
",",
"}",
"]",
",",
"}",
"]",
"}",
",",
"}",
"]",
",",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"commands\"",
":",
"[",
"{",
"\"ids\"",
":",
"[",
"\"climate.bla\"",
"]",
",",
"\"status\"",
":",
"\"ERROR\"",
",",
"\"errorCode\"",
":",
"\"valueOutOfRange\"",
",",
"}",
"]",
"}",
",",
"}",
"assert",
"len",
"(",
"events",
")",
"==",
"1",
"assert",
"events",
"[",
"0",
"]",
".",
"event_type",
"==",
"EVENT_COMMAND_RECEIVED",
"assert",
"events",
"[",
"0",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"entity_id\"",
":",
"\"climate.bla\"",
",",
"\"execution\"",
":",
"{",
"\"command\"",
":",
"\"action.devices.commands.ThermostatTemperatureSetpoint\"",
",",
"\"params\"",
":",
"{",
"\"thermostatTemperatureSetpoint\"",
":",
"10",
"}",
",",
"}",
",",
"\"source\"",
":",
"\"cloud\"",
",",
"}"
] | [
547,
0
] | [
611,
5
] | python | en | ['en', 'gd', 'en'] | True |
test_serialize_input_boolean | (hass) | Test serializing an input boolean entity. | Test serializing an input boolean entity. | async def test_serialize_input_boolean(hass):
"""Test serializing an input boolean entity."""
state = State("input_boolean.bla", "on")
# pylint: disable=protected-access
entity = sh.GoogleEntity(hass, BASIC_CONFIG, state)
result = await entity.sync_serialize(None)
assert result == {
"id": "input_boolean.bla",
"attributes": {},
"name": {"name": "bla"},
"traits": ["action.devices.traits.OnOff"],
"type": "action.devices.types.SWITCH",
"willReportState": False,
} | [
"async",
"def",
"test_serialize_input_boolean",
"(",
"hass",
")",
":",
"state",
"=",
"State",
"(",
"\"input_boolean.bla\"",
",",
"\"on\"",
")",
"# pylint: disable=protected-access",
"entity",
"=",
"sh",
".",
"GoogleEntity",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"state",
")",
"result",
"=",
"await",
"entity",
".",
"sync_serialize",
"(",
"None",
")",
"assert",
"result",
"==",
"{",
"\"id\"",
":",
"\"input_boolean.bla\"",
",",
"\"attributes\"",
":",
"{",
"}",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"bla\"",
"}",
",",
"\"traits\"",
":",
"[",
"\"action.devices.traits.OnOff\"",
"]",
",",
"\"type\"",
":",
"\"action.devices.types.SWITCH\"",
",",
"\"willReportState\"",
":",
"False",
",",
"}"
] | [
614,
0
] | [
627,
5
] | python | en | ['en', 'en', 'en'] | True |
test_unavailable_state_does_sync | (hass) | Test that an unavailable entity does sync over. | Test that an unavailable entity does sync over. | async def test_unavailable_state_does_sync(hass):
"""Test that an unavailable entity does sync over."""
light = DemoLight(
None,
"Demo Light",
state=False,
hs_color=(180, 75),
effect_list=LIGHT_EFFECT_LIST,
effect=LIGHT_EFFECT_LIST[0],
)
light.hass = hass
light.entity_id = "light.demo_light"
light._available = False # pylint: disable=protected-access
await light.async_update_ha_state()
events = []
hass.bus.async_listen(EVENT_SYNC_RECEIVED, events.append)
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"id": "light.demo_light",
"name": {"name": "Demo Light"},
"traits": [
trait.TRAIT_BRIGHTNESS,
trait.TRAIT_ONOFF,
trait.TRAIT_COLOR_SETTING,
trait.TRAIT_MODES,
],
"type": const.TYPE_LIGHT,
"willReportState": False,
"attributes": {
"availableModes": [
{
"name": "effect",
"name_values": [
{"lang": "en", "name_synonym": ["effect"]}
],
"ordered": False,
"settings": [
{
"setting_name": "rainbow",
"setting_values": [
{
"lang": "en",
"setting_synonym": ["rainbow"],
}
],
},
{
"setting_name": "none",
"setting_values": [
{"lang": "en", "setting_synonym": ["none"]}
],
},
],
}
],
"colorModel": "hsv",
"colorTemperatureRange": {
"temperatureMinK": 2000,
"temperatureMaxK": 6535,
},
},
}
],
},
}
await hass.async_block_till_done()
assert len(events) == 1
assert events[0].event_type == EVENT_SYNC_RECEIVED
assert events[0].data == {"request_id": REQ_ID, "source": "cloud"} | [
"async",
"def",
"test_unavailable_state_does_sync",
"(",
"hass",
")",
":",
"light",
"=",
"DemoLight",
"(",
"None",
",",
"\"Demo Light\"",
",",
"state",
"=",
"False",
",",
"hs_color",
"=",
"(",
"180",
",",
"75",
")",
",",
"effect_list",
"=",
"LIGHT_EFFECT_LIST",
",",
"effect",
"=",
"LIGHT_EFFECT_LIST",
"[",
"0",
"]",
",",
")",
"light",
".",
"hass",
"=",
"hass",
"light",
".",
"entity_id",
"=",
"\"light.demo_light\"",
"light",
".",
"_available",
"=",
"False",
"# pylint: disable=protected-access",
"await",
"light",
".",
"async_update_ha_state",
"(",
")",
"events",
"=",
"[",
"]",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_SYNC_RECEIVED",
",",
"events",
".",
"append",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.demo_light\"",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"Demo Light\"",
"}",
",",
"\"traits\"",
":",
"[",
"trait",
".",
"TRAIT_BRIGHTNESS",
",",
"trait",
".",
"TRAIT_ONOFF",
",",
"trait",
".",
"TRAIT_COLOR_SETTING",
",",
"trait",
".",
"TRAIT_MODES",
",",
"]",
",",
"\"type\"",
":",
"const",
".",
"TYPE_LIGHT",
",",
"\"willReportState\"",
":",
"False",
",",
"\"attributes\"",
":",
"{",
"\"availableModes\"",
":",
"[",
"{",
"\"name\"",
":",
"\"effect\"",
",",
"\"name_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"name_synonym\"",
":",
"[",
"\"effect\"",
"]",
"}",
"]",
",",
"\"ordered\"",
":",
"False",
",",
"\"settings\"",
":",
"[",
"{",
"\"setting_name\"",
":",
"\"rainbow\"",
",",
"\"setting_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"setting_synonym\"",
":",
"[",
"\"rainbow\"",
"]",
",",
"}",
"]",
",",
"}",
",",
"{",
"\"setting_name\"",
":",
"\"none\"",
",",
"\"setting_values\"",
":",
"[",
"{",
"\"lang\"",
":",
"\"en\"",
",",
"\"setting_synonym\"",
":",
"[",
"\"none\"",
"]",
"}",
"]",
",",
"}",
",",
"]",
",",
"}",
"]",
",",
"\"colorModel\"",
":",
"\"hsv\"",
",",
"\"colorTemperatureRange\"",
":",
"{",
"\"temperatureMinK\"",
":",
"2000",
",",
"\"temperatureMaxK\"",
":",
"6535",
",",
"}",
",",
"}",
",",
"}",
"]",
",",
"}",
",",
"}",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"events",
")",
"==",
"1",
"assert",
"events",
"[",
"0",
"]",
".",
"event_type",
"==",
"EVENT_SYNC_RECEIVED",
"assert",
"events",
"[",
"0",
"]",
".",
"data",
"==",
"{",
"\"request_id\"",
":",
"REQ_ID",
",",
"\"source\"",
":",
"\"cloud\"",
"}"
] | [
630,
0
] | [
713,
70
] | python | en | ['en', 'en', 'en'] | True |
test_device_class_switch | (hass, device_class, google_type) | Test that a cover entity syncs to the correct device type. | Test that a cover entity syncs to the correct device type. | async def test_device_class_switch(hass, device_class, google_type):
"""Test that a cover entity syncs to the correct device type."""
sensor = DemoSwitch(
None,
"Demo Sensor",
state=False,
icon="mdi:switch",
assumed=False,
device_class=device_class,
)
sensor.hass = hass
sensor.entity_id = "switch.demo_sensor"
await sensor.async_update_ha_state()
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"attributes": {},
"id": "switch.demo_sensor",
"name": {"name": "Demo Sensor"},
"traits": ["action.devices.traits.OnOff"],
"type": google_type,
"willReportState": False,
}
],
},
} | [
"async",
"def",
"test_device_class_switch",
"(",
"hass",
",",
"device_class",
",",
"google_type",
")",
":",
"sensor",
"=",
"DemoSwitch",
"(",
"None",
",",
"\"Demo Sensor\"",
",",
"state",
"=",
"False",
",",
"icon",
"=",
"\"mdi:switch\"",
",",
"assumed",
"=",
"False",
",",
"device_class",
"=",
"device_class",
",",
")",
"sensor",
".",
"hass",
"=",
"hass",
"sensor",
".",
"entity_id",
"=",
"\"switch.demo_sensor\"",
"await",
"sensor",
".",
"async_update_ha_state",
"(",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"attributes\"",
":",
"{",
"}",
",",
"\"id\"",
":",
"\"switch.demo_sensor\"",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"Demo Sensor\"",
"}",
",",
"\"traits\"",
":",
"[",
"\"action.devices.traits.OnOff\"",
"]",
",",
"\"type\"",
":",
"google_type",
",",
"\"willReportState\"",
":",
"False",
",",
"}",
"]",
",",
"}",
",",
"}"
] | [
724,
0
] | [
761,
5
] | python | en | ['en', 'en', 'en'] | True |
test_device_class_binary_sensor | (hass, device_class, google_type) | Test that a binary entity syncs to the correct device type. | Test that a binary entity syncs to the correct device type. | async def test_device_class_binary_sensor(hass, device_class, google_type):
"""Test that a binary entity syncs to the correct device type."""
sensor = DemoBinarySensor(
None, "Demo Sensor", state=False, device_class=device_class
)
sensor.hass = hass
sensor.entity_id = "binary_sensor.demo_sensor"
await sensor.async_update_ha_state()
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"attributes": {
"queryOnlyOpenClose": True,
"discreteOnlyOpenClose": True,
},
"id": "binary_sensor.demo_sensor",
"name": {"name": "Demo Sensor"},
"traits": ["action.devices.traits.OpenClose"],
"type": google_type,
"willReportState": False,
}
],
},
} | [
"async",
"def",
"test_device_class_binary_sensor",
"(",
"hass",
",",
"device_class",
",",
"google_type",
")",
":",
"sensor",
"=",
"DemoBinarySensor",
"(",
"None",
",",
"\"Demo Sensor\"",
",",
"state",
"=",
"False",
",",
"device_class",
"=",
"device_class",
")",
"sensor",
".",
"hass",
"=",
"hass",
"sensor",
".",
"entity_id",
"=",
"\"binary_sensor.demo_sensor\"",
"await",
"sensor",
".",
"async_update_ha_state",
"(",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"attributes\"",
":",
"{",
"\"queryOnlyOpenClose\"",
":",
"True",
",",
"\"discreteOnlyOpenClose\"",
":",
"True",
",",
"}",
",",
"\"id\"",
":",
"\"binary_sensor.demo_sensor\"",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"Demo Sensor\"",
"}",
",",
"\"traits\"",
":",
"[",
"\"action.devices.traits.OpenClose\"",
"]",
",",
"\"type\"",
":",
"google_type",
",",
"\"willReportState\"",
":",
"False",
",",
"}",
"]",
",",
"}",
",",
"}"
] | [
774,
0
] | [
809,
5
] | python | en | ['en', 'en', 'en'] | True |
test_device_class_cover | (hass, device_class, google_type) | Test that a binary entity syncs to the correct device type. | Test that a binary entity syncs to the correct device type. | async def test_device_class_cover(hass, device_class, google_type):
"""Test that a binary entity syncs to the correct device type."""
sensor = DemoCover(None, hass, "Demo Sensor", device_class=device_class)
sensor.hass = hass
sensor.entity_id = "cover.demo_sensor"
await sensor.async_update_ha_state()
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"attributes": {"discreteOnlyOpenClose": True},
"id": "cover.demo_sensor",
"name": {"name": "Demo Sensor"},
"traits": ["action.devices.traits.OpenClose"],
"type": google_type,
"willReportState": False,
}
],
},
} | [
"async",
"def",
"test_device_class_cover",
"(",
"hass",
",",
"device_class",
",",
"google_type",
")",
":",
"sensor",
"=",
"DemoCover",
"(",
"None",
",",
"hass",
",",
"\"Demo Sensor\"",
",",
"device_class",
"=",
"device_class",
")",
"sensor",
".",
"hass",
"=",
"hass",
"sensor",
".",
"entity_id",
"=",
"\"cover.demo_sensor\"",
"await",
"sensor",
".",
"async_update_ha_state",
"(",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"attributes\"",
":",
"{",
"\"discreteOnlyOpenClose\"",
":",
"True",
"}",
",",
"\"id\"",
":",
"\"cover.demo_sensor\"",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"Demo Sensor\"",
"}",
",",
"\"traits\"",
":",
"[",
"\"action.devices.traits.OpenClose\"",
"]",
",",
"\"type\"",
":",
"google_type",
",",
"\"willReportState\"",
":",
"False",
",",
"}",
"]",
",",
"}",
",",
"}"
] | [
820,
0
] | [
850,
5
] | python | en | ['en', 'en', 'en'] | True |
test_device_media_player | (hass, device_class, google_type) | Test that a binary entity syncs to the correct device type. | Test that a binary entity syncs to the correct device type. | async def test_device_media_player(hass, device_class, google_type):
"""Test that a binary entity syncs to the correct device type."""
sensor = AbstractDemoPlayer("Demo", device_class=device_class)
sensor.hass = hass
sensor.entity_id = "media_player.demo"
await sensor.async_update_ha_state()
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"attributes": {
"supportActivityState": True,
"supportPlaybackState": True,
},
"id": sensor.entity_id,
"name": {"name": sensor.name},
"traits": [
"action.devices.traits.OnOff",
"action.devices.traits.MediaState",
],
"type": google_type,
"willReportState": False,
}
],
},
} | [
"async",
"def",
"test_device_media_player",
"(",
"hass",
",",
"device_class",
",",
"google_type",
")",
":",
"sensor",
"=",
"AbstractDemoPlayer",
"(",
"\"Demo\"",
",",
"device_class",
"=",
"device_class",
")",
"sensor",
".",
"hass",
"=",
"hass",
"sensor",
".",
"entity_id",
"=",
"\"media_player.demo\"",
"await",
"sensor",
".",
"async_update_ha_state",
"(",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"attributes\"",
":",
"{",
"\"supportActivityState\"",
":",
"True",
",",
"\"supportPlaybackState\"",
":",
"True",
",",
"}",
",",
"\"id\"",
":",
"sensor",
".",
"entity_id",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"sensor",
".",
"name",
"}",
",",
"\"traits\"",
":",
"[",
"\"action.devices.traits.OnOff\"",
",",
"\"action.devices.traits.MediaState\"",
",",
"]",
",",
"\"type\"",
":",
"google_type",
",",
"\"willReportState\"",
":",
"False",
",",
"}",
"]",
",",
"}",
",",
"}"
] | [
862,
0
] | [
898,
5
] | python | en | ['en', 'en', 'en'] | True |
test_query_disconnect | (hass) | Test a disconnect message. | Test a disconnect message. | async def test_query_disconnect(hass):
"""Test a disconnect message."""
config = MockConfig(hass=hass)
config.async_enable_report_state()
assert config._unsub_report_state is not None
with patch.object(config, "async_disconnect_agent_user") as mock_disconnect:
result = await sh.async_handle_message(
hass,
config,
"test-agent",
{"inputs": [{"intent": "action.devices.DISCONNECT"}], "requestId": REQ_ID},
const.SOURCE_CLOUD,
)
assert result is None
assert len(mock_disconnect.mock_calls) == 1 | [
"async",
"def",
"test_query_disconnect",
"(",
"hass",
")",
":",
"config",
"=",
"MockConfig",
"(",
"hass",
"=",
"hass",
")",
"config",
".",
"async_enable_report_state",
"(",
")",
"assert",
"config",
".",
"_unsub_report_state",
"is",
"not",
"None",
"with",
"patch",
".",
"object",
"(",
"config",
",",
"\"async_disconnect_agent_user\"",
")",
"as",
"mock_disconnect",
":",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"config",
",",
"\"test-agent\"",
",",
"{",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.DISCONNECT\"",
"}",
"]",
",",
"\"requestId\"",
":",
"REQ_ID",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"is",
"None",
"assert",
"len",
"(",
"mock_disconnect",
".",
"mock_calls",
")",
"==",
"1"
] | [
901,
0
] | [
915,
47
] | python | en | ['it', 'en', 'en'] | True |
test_trait_execute_adding_query_data | (hass) | Test a trait execute influencing query data. | Test a trait execute influencing query data. | async def test_trait_execute_adding_query_data(hass):
"""Test a trait execute influencing query data."""
await async_process_ha_core_config(
hass,
{"external_url": "https://example.com"},
)
hass.states.async_set(
"camera.office", "idle", {"supported_features": camera.SUPPORT_STREAM}
)
with patch(
"homeassistant.components.camera.async_request_stream",
return_value="/api/streams/bla",
):
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
None,
{
"requestId": REQ_ID,
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [{"id": "camera.office"}],
"execution": [
{
"command": "action.devices.commands.GetCameraStream",
"params": {
"StreamToChromecast": True,
"SupportedStreamProtocols": [
"progressive_mp4",
"hls",
"dash",
"smooth_stream",
],
},
}
],
}
]
},
}
],
},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"commands": [
{
"ids": ["camera.office"],
"status": "SUCCESS",
"states": {
"online": True,
"cameraStreamAccessUrl": "https://example.com/api/streams/bla",
"cameraStreamReceiverAppId": "B12CE3CA",
},
}
]
},
} | [
"async",
"def",
"test_trait_execute_adding_query_data",
"(",
"hass",
")",
":",
"await",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"\"external_url\"",
":",
"\"https://example.com\"",
"}",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"camera.office\"",
",",
"\"idle\"",
",",
"{",
"\"supported_features\"",
":",
"camera",
".",
"SUPPORT_STREAM",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.camera.async_request_stream\"",
",",
"return_value",
"=",
"\"/api/streams/bla\"",
",",
")",
":",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"None",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.EXECUTE\"",
",",
"\"payload\"",
":",
"{",
"\"commands\"",
":",
"[",
"{",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"camera.office\"",
"}",
"]",
",",
"\"execution\"",
":",
"[",
"{",
"\"command\"",
":",
"\"action.devices.commands.GetCameraStream\"",
",",
"\"params\"",
":",
"{",
"\"StreamToChromecast\"",
":",
"True",
",",
"\"SupportedStreamProtocols\"",
":",
"[",
"\"progressive_mp4\"",
",",
"\"hls\"",
",",
"\"dash\"",
",",
"\"smooth_stream\"",
",",
"]",
",",
"}",
",",
"}",
"]",
",",
"}",
"]",
"}",
",",
"}",
"]",
",",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"commands\"",
":",
"[",
"{",
"\"ids\"",
":",
"[",
"\"camera.office\"",
"]",
",",
"\"status\"",
":",
"\"SUCCESS\"",
",",
"\"states\"",
":",
"{",
"\"online\"",
":",
"True",
",",
"\"cameraStreamAccessUrl\"",
":",
"\"https://example.com/api/streams/bla\"",
",",
"\"cameraStreamReceiverAppId\"",
":",
"\"B12CE3CA\"",
",",
"}",
",",
"}",
"]",
"}",
",",
"}"
] | [
918,
0
] | [
983,
5
] | python | en | ['fr', 'en', 'en'] | True |
test_identify | (hass) | Test identify message. | Test identify message. | async def test_identify(hass):
"""Test identify message."""
user_agent_id = "mock-user-id"
proxy_device_id = user_agent_id
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
user_agent_id,
{
"requestId": REQ_ID,
"inputs": [
{
"intent": "action.devices.IDENTIFY",
"payload": {
"device": {
"mdnsScanData": {
"additionals": [
{
"type": "TXT",
"class": "IN",
"name": "devhome._home-assistant._tcp.local",
"ttl": 4500,
"data": [
"version=0.101.0.dev0",
"base_url=http://192.168.1.101:8123",
"requires_api_password=true",
],
}
]
}
},
"structureData": {},
},
}
],
"devices": [
{
"id": "light.ceiling_lights",
"customData": {
"httpPort": 8123,
"httpSSL": False,
"proxyDeviceId": proxy_device_id,
"webhookId": "dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219",
},
}
],
},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"device": {
"id": proxy_device_id,
"isLocalOnly": True,
"isProxy": True,
"deviceInfo": {
"hwVersion": "UNKNOWN_HW_VERSION",
"manufacturer": "Home Assistant",
"model": "Home Assistant",
"swVersion": __version__,
},
}
},
} | [
"async",
"def",
"test_identify",
"(",
"hass",
")",
":",
"user_agent_id",
"=",
"\"mock-user-id\"",
"proxy_device_id",
"=",
"user_agent_id",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"user_agent_id",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.IDENTIFY\"",
",",
"\"payload\"",
":",
"{",
"\"device\"",
":",
"{",
"\"mdnsScanData\"",
":",
"{",
"\"additionals\"",
":",
"[",
"{",
"\"type\"",
":",
"\"TXT\"",
",",
"\"class\"",
":",
"\"IN\"",
",",
"\"name\"",
":",
"\"devhome._home-assistant._tcp.local\"",
",",
"\"ttl\"",
":",
"4500",
",",
"\"data\"",
":",
"[",
"\"version=0.101.0.dev0\"",
",",
"\"base_url=http://192.168.1.101:8123\"",
",",
"\"requires_api_password=true\"",
",",
"]",
",",
"}",
"]",
"}",
"}",
",",
"\"structureData\"",
":",
"{",
"}",
",",
"}",
",",
"}",
"]",
",",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.ceiling_lights\"",
",",
"\"customData\"",
":",
"{",
"\"httpPort\"",
":",
"8123",
",",
"\"httpSSL\"",
":",
"False",
",",
"\"proxyDeviceId\"",
":",
"proxy_device_id",
",",
"\"webhookId\"",
":",
"\"dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219\"",
",",
"}",
",",
"}",
"]",
",",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"device\"",
":",
"{",
"\"id\"",
":",
"proxy_device_id",
",",
"\"isLocalOnly\"",
":",
"True",
",",
"\"isProxy\"",
":",
"True",
",",
"\"deviceInfo\"",
":",
"{",
"\"hwVersion\"",
":",
"\"UNKNOWN_HW_VERSION\"",
",",
"\"manufacturer\"",
":",
"\"Home Assistant\"",
",",
"\"model\"",
":",
"\"Home Assistant\"",
",",
"\"swVersion\"",
":",
"__version__",
",",
"}",
",",
"}",
"}",
",",
"}"
] | [
986,
0
] | [
1051,
5
] | python | en | ['en', 'de', 'en'] | True |
test_reachable_devices | (hass) | Test REACHABLE_DEVICES intent. | Test REACHABLE_DEVICES intent. | async def test_reachable_devices(hass):
"""Test REACHABLE_DEVICES intent."""
# Matching passed in device.
hass.states.async_set("light.ceiling_lights", "on")
# Unsupported entity
hass.states.async_set("not_supported.entity", "something")
# Excluded via config
hass.states.async_set("light.not_expose", "on")
# Not passed in as google_id
hass.states.async_set("light.not_mentioned", "on")
# Has 2FA
hass.states.async_set("lock.has_2fa", "on")
config = MockConfig(
should_expose=lambda state: state.entity_id != "light.not_expose",
)
user_agent_id = "mock-user-id"
proxy_device_id = user_agent_id
result = await sh.async_handle_message(
hass,
config,
user_agent_id,
{
"requestId": REQ_ID,
"inputs": [
{
"intent": "action.devices.REACHABLE_DEVICES",
"payload": {
"device": {
"proxyDevice": {
"id": proxy_device_id,
"customData": "{}",
"proxyData": "{}",
}
},
"structureData": {},
},
}
],
"devices": [
{
"id": "light.ceiling_lights",
"customData": {
"httpPort": 8123,
"httpSSL": False,
"proxyDeviceId": proxy_device_id,
"webhookId": "dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219",
},
},
{
"id": "light.not_expose",
"customData": {
"httpPort": 8123,
"httpSSL": False,
"proxyDeviceId": proxy_device_id,
"webhookId": "dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219",
},
},
{
"id": "lock.has_2fa",
"customData": {
"httpPort": 8123,
"httpSSL": False,
"proxyDeviceId": proxy_device_id,
"webhookId": "dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219",
},
},
{"id": proxy_device_id, "customData": {}},
],
},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {"devices": [{"verificationId": "light.ceiling_lights"}]},
} | [
"async",
"def",
"test_reachable_devices",
"(",
"hass",
")",
":",
"# Matching passed in device.",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.ceiling_lights\"",
",",
"\"on\"",
")",
"# Unsupported entity",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"not_supported.entity\"",
",",
"\"something\"",
")",
"# Excluded via config",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.not_expose\"",
",",
"\"on\"",
")",
"# Not passed in as google_id",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.not_mentioned\"",
",",
"\"on\"",
")",
"# Has 2FA",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"lock.has_2fa\"",
",",
"\"on\"",
")",
"config",
"=",
"MockConfig",
"(",
"should_expose",
"=",
"lambda",
"state",
":",
"state",
".",
"entity_id",
"!=",
"\"light.not_expose\"",
",",
")",
"user_agent_id",
"=",
"\"mock-user-id\"",
"proxy_device_id",
"=",
"user_agent_id",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"config",
",",
"user_agent_id",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.REACHABLE_DEVICES\"",
",",
"\"payload\"",
":",
"{",
"\"device\"",
":",
"{",
"\"proxyDevice\"",
":",
"{",
"\"id\"",
":",
"proxy_device_id",
",",
"\"customData\"",
":",
"\"{}\"",
",",
"\"proxyData\"",
":",
"\"{}\"",
",",
"}",
"}",
",",
"\"structureData\"",
":",
"{",
"}",
",",
"}",
",",
"}",
"]",
",",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.ceiling_lights\"",
",",
"\"customData\"",
":",
"{",
"\"httpPort\"",
":",
"8123",
",",
"\"httpSSL\"",
":",
"False",
",",
"\"proxyDeviceId\"",
":",
"proxy_device_id",
",",
"\"webhookId\"",
":",
"\"dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219\"",
",",
"}",
",",
"}",
",",
"{",
"\"id\"",
":",
"\"light.not_expose\"",
",",
"\"customData\"",
":",
"{",
"\"httpPort\"",
":",
"8123",
",",
"\"httpSSL\"",
":",
"False",
",",
"\"proxyDeviceId\"",
":",
"proxy_device_id",
",",
"\"webhookId\"",
":",
"\"dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219\"",
",",
"}",
",",
"}",
",",
"{",
"\"id\"",
":",
"\"lock.has_2fa\"",
",",
"\"customData\"",
":",
"{",
"\"httpPort\"",
":",
"8123",
",",
"\"httpSSL\"",
":",
"False",
",",
"\"proxyDeviceId\"",
":",
"proxy_device_id",
",",
"\"webhookId\"",
":",
"\"dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219\"",
",",
"}",
",",
"}",
",",
"{",
"\"id\"",
":",
"proxy_device_id",
",",
"\"customData\"",
":",
"{",
"}",
"}",
",",
"]",
",",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"devices\"",
":",
"[",
"{",
"\"verificationId\"",
":",
"\"light.ceiling_lights\"",
"}",
"]",
"}",
",",
"}"
] | [
1054,
0
] | [
1136,
5
] | python | en | ['en', 'en', 'en'] | True |
test_sync_message_recovery | (hass, caplog) | Test a sync message recovers from bad entities. | Test a sync message recovers from bad entities. | async def test_sync_message_recovery(hass, caplog):
"""Test a sync message recovers from bad entities."""
light = DemoLight(
None,
"Demo Light",
state=False,
hs_color=(180, 75),
)
light.hass = hass
light.entity_id = "light.demo_light"
await light.async_update_ha_state()
hass.states.async_set(
"light.bad_light",
"on",
{
"min_mireds": "badvalue",
"supported_features": hass.components.light.SUPPORT_COLOR_TEMP,
},
)
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{"requestId": REQ_ID, "inputs": [{"intent": "action.devices.SYNC"}]},
const.SOURCE_CLOUD,
)
assert result == {
"requestId": REQ_ID,
"payload": {
"agentUserId": "test-agent",
"devices": [
{
"id": "light.demo_light",
"name": {"name": "Demo Light"},
"attributes": {
"colorModel": "hsv",
"colorTemperatureRange": {
"temperatureMaxK": 6535,
"temperatureMinK": 2000,
},
},
"traits": [
"action.devices.traits.Brightness",
"action.devices.traits.OnOff",
"action.devices.traits.ColorSetting",
],
"willReportState": False,
"type": "action.devices.types.LIGHT",
},
],
},
}
assert "Error serializing light.bad_light" in caplog.text | [
"async",
"def",
"test_sync_message_recovery",
"(",
"hass",
",",
"caplog",
")",
":",
"light",
"=",
"DemoLight",
"(",
"None",
",",
"\"Demo Light\"",
",",
"state",
"=",
"False",
",",
"hs_color",
"=",
"(",
"180",
",",
"75",
")",
",",
")",
"light",
".",
"hass",
"=",
"hass",
"light",
".",
"entity_id",
"=",
"\"light.demo_light\"",
"await",
"light",
".",
"async_update_ha_state",
"(",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.bad_light\"",
",",
"\"on\"",
",",
"{",
"\"min_mireds\"",
":",
"\"badvalue\"",
",",
"\"supported_features\"",
":",
"hass",
".",
"components",
".",
"light",
".",
"SUPPORT_COLOR_TEMP",
",",
"}",
",",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.SYNC\"",
"}",
"]",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"agentUserId\"",
":",
"\"test-agent\"",
",",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.demo_light\"",
",",
"\"name\"",
":",
"{",
"\"name\"",
":",
"\"Demo Light\"",
"}",
",",
"\"attributes\"",
":",
"{",
"\"colorModel\"",
":",
"\"hsv\"",
",",
"\"colorTemperatureRange\"",
":",
"{",
"\"temperatureMaxK\"",
":",
"6535",
",",
"\"temperatureMinK\"",
":",
"2000",
",",
"}",
",",
"}",
",",
"\"traits\"",
":",
"[",
"\"action.devices.traits.Brightness\"",
",",
"\"action.devices.traits.OnOff\"",
",",
"\"action.devices.traits.ColorSetting\"",
",",
"]",
",",
"\"willReportState\"",
":",
"False",
",",
"\"type\"",
":",
"\"action.devices.types.LIGHT\"",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
"assert",
"\"Error serializing light.bad_light\"",
"in",
"caplog",
".",
"text"
] | [
1139,
0
] | [
1195,
61
] | python | en | ['en', 'en', 'en'] | True |
test_query_recover | (hass, caplog) | Test that we recover if an entity raises during query. | Test that we recover if an entity raises during query. | async def test_query_recover(hass, caplog):
"""Test that we recover if an entity raises during query."""
hass.states.async_set(
"light.good",
"on",
{
"supported_features": hass.components.light.SUPPORT_BRIGHTNESS,
"brightness": 50,
},
)
hass.states.async_set(
"light.bad",
"on",
{
"supported_features": hass.components.light.SUPPORT_BRIGHTNESS,
"brightness": "shoe",
},
)
result = await sh.async_handle_message(
hass,
BASIC_CONFIG,
"test-agent",
{
"requestId": REQ_ID,
"inputs": [
{
"intent": "action.devices.QUERY",
"payload": {
"devices": [
{"id": "light.good"},
{"id": "light.bad"},
]
},
}
],
},
const.SOURCE_CLOUD,
)
assert (
f"Unexpected error serializing query for {hass.states.get('light.bad')}"
in caplog.text
)
assert result == {
"requestId": REQ_ID,
"payload": {
"devices": {
"light.bad": {"online": False},
"light.good": {"on": True, "online": True, "brightness": 19},
}
},
} | [
"async",
"def",
"test_query_recover",
"(",
"hass",
",",
"caplog",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.good\"",
",",
"\"on\"",
",",
"{",
"\"supported_features\"",
":",
"hass",
".",
"components",
".",
"light",
".",
"SUPPORT_BRIGHTNESS",
",",
"\"brightness\"",
":",
"50",
",",
"}",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.bad\"",
",",
"\"on\"",
",",
"{",
"\"supported_features\"",
":",
"hass",
".",
"components",
".",
"light",
".",
"SUPPORT_BRIGHTNESS",
",",
"\"brightness\"",
":",
"\"shoe\"",
",",
"}",
",",
")",
"result",
"=",
"await",
"sh",
".",
"async_handle_message",
"(",
"hass",
",",
"BASIC_CONFIG",
",",
"\"test-agent\"",
",",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"inputs\"",
":",
"[",
"{",
"\"intent\"",
":",
"\"action.devices.QUERY\"",
",",
"\"payload\"",
":",
"{",
"\"devices\"",
":",
"[",
"{",
"\"id\"",
":",
"\"light.good\"",
"}",
",",
"{",
"\"id\"",
":",
"\"light.bad\"",
"}",
",",
"]",
"}",
",",
"}",
"]",
",",
"}",
",",
"const",
".",
"SOURCE_CLOUD",
",",
")",
"assert",
"(",
"f\"Unexpected error serializing query for {hass.states.get('light.bad')}\"",
"in",
"caplog",
".",
"text",
")",
"assert",
"result",
"==",
"{",
"\"requestId\"",
":",
"REQ_ID",
",",
"\"payload\"",
":",
"{",
"\"devices\"",
":",
"{",
"\"light.bad\"",
":",
"{",
"\"online\"",
":",
"False",
"}",
",",
"\"light.good\"",
":",
"{",
"\"on\"",
":",
"True",
",",
"\"online\"",
":",
"True",
",",
"\"brightness\"",
":",
"19",
"}",
",",
"}",
"}",
",",
"}"
] | [
1198,
0
] | [
1251,
5
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List, bool], None],
) | Load Roku remote based on a config entry. | Load Roku remote based on a config entry. | async def async_setup_entry(
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List, bool], None],
) -> bool:
"""Load Roku remote based on a config entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
unique_id = coordinator.data.info.serial_number
async_add_entities([RokuRemote(unique_id, coordinator)], True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
":",
"Callable",
"[",
"[",
"List",
",",
"bool",
"]",
",",
"None",
"]",
",",
")",
"->",
"bool",
":",
"coordinator",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"unique_id",
"=",
"coordinator",
".",
"data",
".",
"info",
".",
"serial_number",
"async_add_entities",
"(",
"[",
"RokuRemote",
"(",
"unique_id",
",",
"coordinator",
")",
"]",
",",
"True",
")"
] | [
11,
0
] | [
19,
66
] | python | en | ['en', 'en', 'en'] | True |
RokuRemote.__init__ | (self, unique_id: str, coordinator: RokuDataUpdateCoordinator) | Initialize the Roku device. | Initialize the Roku device. | def __init__(self, unique_id: str, coordinator: RokuDataUpdateCoordinator) -> None:
"""Initialize the Roku device."""
super().__init__(
device_id=unique_id,
name=coordinator.data.info.name,
coordinator=coordinator,
)
self._unique_id = unique_id | [
"def",
"__init__",
"(",
"self",
",",
"unique_id",
":",
"str",
",",
"coordinator",
":",
"RokuDataUpdateCoordinator",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"device_id",
"=",
"unique_id",
",",
"name",
"=",
"coordinator",
".",
"data",
".",
"info",
".",
"name",
",",
"coordinator",
"=",
"coordinator",
",",
")",
"self",
".",
"_unique_id",
"=",
"unique_id"
] | [
25,
4
] | [
33,
35
] | python | en | ['en', 'en', 'en'] | True |
RokuRemote.unique_id | (self) | Return the unique ID for this entity. | Return the unique ID for this entity. | def unique_id(self) -> str:
"""Return the unique ID for this entity."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_unique_id"
] | [
36,
4
] | [
38,
30
] | python | en | ['en', 'en', 'en'] | True |
RokuRemote.is_on | (self) | Return true if device is on. | Return true if device is on. | def is_on(self) -> bool:
"""Return true if device is on."""
return not self.coordinator.data.state.standby | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"not",
"self",
".",
"coordinator",
".",
"data",
".",
"state",
".",
"standby"
] | [
41,
4
] | [
43,
54
] | python | en | ['en', 'fy', 'en'] | True |
RokuRemote.async_turn_on | (self, **kwargs) | Turn the device on. | Turn the device on. | async def async_turn_on(self, **kwargs) -> None:
"""Turn the device on."""
await self.coordinator.roku.remote("poweron")
await self.coordinator.async_request_refresh() | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"roku",
".",
"remote",
"(",
"\"poweron\"",
")",
"await",
"self",
".",
"coordinator",
".",
"async_request_refresh",
"(",
")"
] | [
46,
4
] | [
49,
54
] | python | en | ['en', 'en', 'en'] | True |
RokuRemote.async_turn_off | (self, **kwargs) | Turn the device off. | Turn the device off. | async def async_turn_off(self, **kwargs) -> None:
"""Turn the device off."""
await self.coordinator.roku.remote("poweroff")
await self.coordinator.async_request_refresh() | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"roku",
".",
"remote",
"(",
"\"poweroff\"",
")",
"await",
"self",
".",
"coordinator",
".",
"async_request_refresh",
"(",
")"
] | [
52,
4
] | [
55,
54
] | python | en | ['en', 'en', 'en'] | True |
RokuRemote.async_send_command | (self, command: List, **kwargs) | Send a command to one device. | Send a command to one device. | async def async_send_command(self, command: List, **kwargs) -> None:
"""Send a command to one device."""
num_repeats = kwargs[ATTR_NUM_REPEATS]
for _ in range(num_repeats):
for single_command in command:
await self.coordinator.roku.remote(single_command)
await self.coordinator.async_request_refresh() | [
"async",
"def",
"async_send_command",
"(",
"self",
",",
"command",
":",
"List",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"num_repeats",
"=",
"kwargs",
"[",
"ATTR_NUM_REPEATS",
"]",
"for",
"_",
"in",
"range",
"(",
"num_repeats",
")",
":",
"for",
"single_command",
"in",
"command",
":",
"await",
"self",
".",
"coordinator",
".",
"roku",
".",
"remote",
"(",
"single_command",
")",
"await",
"self",
".",
"coordinator",
".",
"async_request_refresh",
"(",
")"
] | [
58,
4
] | [
66,
54
] | python | en | ['en', 'en', 'en'] | True |
get_truncated_cumulative_reward | (
rewards: Union[list, np.ndarray, torch.Tensor],
discount: float,
k: int = -1
) | Compute K-step cumulative rewards from a reward sequence.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
discount (float): Reward discount as in standard RL.
k (int): Number of steps in computing cumulative rewards. If it is -1, returns are computed using the
largest possible number of steps. Defaults to -1.
Returns:
An ndarray or torch.Tensor instance containing the k-step cumulative rewards for each time step.
| Compute K-step cumulative rewards from a reward sequence.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
discount (float): Reward discount as in standard RL.
k (int): Number of steps in computing cumulative rewards. If it is -1, returns are computed using the
largest possible number of steps. Defaults to -1. | def get_truncated_cumulative_reward(
rewards: Union[list, np.ndarray, torch.Tensor],
discount: float,
k: int = -1
):
"""Compute K-step cumulative rewards from a reward sequence.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
discount (float): Reward discount as in standard RL.
k (int): Number of steps in computing cumulative rewards. If it is -1, returns are computed using the
largest possible number of steps. Defaults to -1.
Returns:
An ndarray or torch.Tensor instance containing the k-step cumulative rewards for each time step.
"""
if k < 0:
k = len(rewards) - 1
pad = np.pad if isinstance(rewards, list) or isinstance(rewards, np.ndarray) else F.pad
return reduce(
lambda x, y: x * discount + y,
[pad(rewards[i:], (0, i)) for i in range(min(k, len(rewards)) - 1, -1, -1)]
) | [
"def",
"get_truncated_cumulative_reward",
"(",
"rewards",
":",
"Union",
"[",
"list",
",",
"np",
".",
"ndarray",
",",
"torch",
".",
"Tensor",
"]",
",",
"discount",
":",
"float",
",",
"k",
":",
"int",
"=",
"-",
"1",
")",
":",
"if",
"k",
"<",
"0",
":",
"k",
"=",
"len",
"(",
"rewards",
")",
"-",
"1",
"pad",
"=",
"np",
".",
"pad",
"if",
"isinstance",
"(",
"rewards",
",",
"list",
")",
"or",
"isinstance",
"(",
"rewards",
",",
"np",
".",
"ndarray",
")",
"else",
"F",
".",
"pad",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"*",
"discount",
"+",
"y",
",",
"[",
"pad",
"(",
"rewards",
"[",
"i",
":",
"]",
",",
"(",
"0",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"k",
",",
"len",
"(",
"rewards",
")",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
"]",
")"
] | [
11,
0
] | [
32,
5
] | python | en | ['en', 'co', 'en'] | True |
get_k_step_returns | (
rewards: Union[list, np.ndarray, torch.Tensor],
values: Union[list, np.ndarray, torch.Tensor],
discount: float,
k: int = -1
) | Compute K-step returns given reward and value sequences.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
values (Union[list, np.ndarray, torch.Tensor]): Sequence of values for the traversed states in a trajectory.
discount (float): Reward discount as in standard RL.
k (int): Number of steps in computing returns. If it is -1, returns are computed using the largest possible
number of steps. Defaults to -1.
Returns:
An ndarray or torch.Tensor instance containing the k-step returns for each time step.
| Compute K-step returns given reward and value sequences.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
values (Union[list, np.ndarray, torch.Tensor]): Sequence of values for the traversed states in a trajectory.
discount (float): Reward discount as in standard RL.
k (int): Number of steps in computing returns. If it is -1, returns are computed using the largest possible
number of steps. Defaults to -1. | def get_k_step_returns(
rewards: Union[list, np.ndarray, torch.Tensor],
values: Union[list, np.ndarray, torch.Tensor],
discount: float,
k: int = -1
):
"""Compute K-step returns given reward and value sequences.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
values (Union[list, np.ndarray, torch.Tensor]): Sequence of values for the traversed states in a trajectory.
discount (float): Reward discount as in standard RL.
k (int): Number of steps in computing returns. If it is -1, returns are computed using the largest possible
number of steps. Defaults to -1.
Returns:
An ndarray or torch.Tensor instance containing the k-step returns for each time step.
"""
assert len(rewards) == len(values), "rewards and values should have the same length"
assert len(values.shape) == 1, "values should be a one-dimensional array"
rewards[-1] = values[-1]
if k < 0:
k = len(rewards) - 1
pad = np.pad if isinstance(rewards, list) or isinstance(rewards, np.ndarray) else F.pad
return reduce(
lambda x, y: x * discount + y,
[pad(rewards[i:], (0, i)) for i in range(min(k, len(rewards)) - 1, -1, -1)],
pad(values[k:], (0, k))
) | [
"def",
"get_k_step_returns",
"(",
"rewards",
":",
"Union",
"[",
"list",
",",
"np",
".",
"ndarray",
",",
"torch",
".",
"Tensor",
"]",
",",
"values",
":",
"Union",
"[",
"list",
",",
"np",
".",
"ndarray",
",",
"torch",
".",
"Tensor",
"]",
",",
"discount",
":",
"float",
",",
"k",
":",
"int",
"=",
"-",
"1",
")",
":",
"assert",
"len",
"(",
"rewards",
")",
"==",
"len",
"(",
"values",
")",
",",
"\"rewards and values should have the same length\"",
"assert",
"len",
"(",
"values",
".",
"shape",
")",
"==",
"1",
",",
"\"values should be a one-dimensional array\"",
"rewards",
"[",
"-",
"1",
"]",
"=",
"values",
"[",
"-",
"1",
"]",
"if",
"k",
"<",
"0",
":",
"k",
"=",
"len",
"(",
"rewards",
")",
"-",
"1",
"pad",
"=",
"np",
".",
"pad",
"if",
"isinstance",
"(",
"rewards",
",",
"list",
")",
"or",
"isinstance",
"(",
"rewards",
",",
"np",
".",
"ndarray",
")",
"else",
"F",
".",
"pad",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"*",
"discount",
"+",
"y",
",",
"[",
"pad",
"(",
"rewards",
"[",
"i",
":",
"]",
",",
"(",
"0",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"k",
",",
"len",
"(",
"rewards",
")",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
"]",
",",
"pad",
"(",
"values",
"[",
"k",
":",
"]",
",",
"(",
"0",
",",
"k",
")",
")",
")"
] | [
35,
0
] | [
62,
5
] | python | en | ['en', 'en', 'en'] | True |
get_lambda_returns | (
rewards: Union[list, np.ndarray, torch.Tensor],
values: Union[list, np.ndarray, torch.Tensor],
discount: float,
lam: float,
k: int = -1
) | Compute lambda returns given reward and value sequences and a k.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
values (Union[list, np.ndarray, torch.Tensor]): Sequence of values for the traversed states in a trajectory.
discount (float): Reward discount as in standard RL.
lam (float): Lambda coefficient involved in computing lambda returns.
k (int): Number of steps where the lambda return series is truncated. If it is -1, no truncating is done and
the lambda return is carried out to the end of the sequence. Defaults to -1.
Returns:
An ndarray or torch.Tensor instance containing the lambda returns for each time step.
| Compute lambda returns given reward and value sequences and a k.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
values (Union[list, np.ndarray, torch.Tensor]): Sequence of values for the traversed states in a trajectory.
discount (float): Reward discount as in standard RL.
lam (float): Lambda coefficient involved in computing lambda returns.
k (int): Number of steps where the lambda return series is truncated. If it is -1, no truncating is done and
the lambda return is carried out to the end of the sequence. Defaults to -1. | def get_lambda_returns(
rewards: Union[list, np.ndarray, torch.Tensor],
values: Union[list, np.ndarray, torch.Tensor],
discount: float,
lam: float,
k: int = -1
):
"""Compute lambda returns given reward and value sequences and a k.
Args:
rewards (Union[list, np.ndarray, torch.Tensor]): Reward sequence from a trajectory.
values (Union[list, np.ndarray, torch.Tensor]): Sequence of values for the traversed states in a trajectory.
discount (float): Reward discount as in standard RL.
lam (float): Lambda coefficient involved in computing lambda returns.
k (int): Number of steps where the lambda return series is truncated. If it is -1, no truncating is done and
the lambda return is carried out to the end of the sequence. Defaults to -1.
Returns:
An ndarray or torch.Tensor instance containing the lambda returns for each time step.
"""
if k < 0:
k = len(rewards) - 1
# If lambda is zero, lambda return reduces to one-step return
if lam == .0:
return get_k_step_returns(rewards, values, discount, k=1)
# If lambda is one, lambda return reduces to k-step return
if lam == 1.0:
return get_k_step_returns(rewards, values, discount, k=k)
k = min(k, len(rewards) - 1)
pre_truncate = reduce(
lambda x, y: x * lam + y,
[get_k_step_returns(rewards, values, discount, k=k) for k in range(k - 1, 0, -1)]
)
post_truncate = get_k_step_returns(rewards, values, discount, k=k) * lam**(k - 1)
return (1 - lam) * pre_truncate + post_truncate | [
"def",
"get_lambda_returns",
"(",
"rewards",
":",
"Union",
"[",
"list",
",",
"np",
".",
"ndarray",
",",
"torch",
".",
"Tensor",
"]",
",",
"values",
":",
"Union",
"[",
"list",
",",
"np",
".",
"ndarray",
",",
"torch",
".",
"Tensor",
"]",
",",
"discount",
":",
"float",
",",
"lam",
":",
"float",
",",
"k",
":",
"int",
"=",
"-",
"1",
")",
":",
"if",
"k",
"<",
"0",
":",
"k",
"=",
"len",
"(",
"rewards",
")",
"-",
"1",
"# If lambda is zero, lambda return reduces to one-step return",
"if",
"lam",
"==",
".0",
":",
"return",
"get_k_step_returns",
"(",
"rewards",
",",
"values",
",",
"discount",
",",
"k",
"=",
"1",
")",
"# If lambda is one, lambda return reduces to k-step return",
"if",
"lam",
"==",
"1.0",
":",
"return",
"get_k_step_returns",
"(",
"rewards",
",",
"values",
",",
"discount",
",",
"k",
"=",
"k",
")",
"k",
"=",
"min",
"(",
"k",
",",
"len",
"(",
"rewards",
")",
"-",
"1",
")",
"pre_truncate",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"*",
"lam",
"+",
"y",
",",
"[",
"get_k_step_returns",
"(",
"rewards",
",",
"values",
",",
"discount",
",",
"k",
"=",
"k",
")",
"for",
"k",
"in",
"range",
"(",
"k",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
"]",
")",
"post_truncate",
"=",
"get_k_step_returns",
"(",
"rewards",
",",
"values",
",",
"discount",
",",
"k",
"=",
"k",
")",
"*",
"lam",
"**",
"(",
"k",
"-",
"1",
")",
"return",
"(",
"1",
"-",
"lam",
")",
"*",
"pre_truncate",
"+",
"post_truncate"
] | [
65,
0
] | [
102,
51
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the KEBA charging station platform. | Set up the KEBA charging station platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the KEBA charging station platform."""
if discovery_info is None:
return
keba = hass.data[DOMAIN]
sensors = [
KebaBinarySensor(
keba, "Online", "Status", "device_state", DEVICE_CLASS_CONNECTIVITY
),
KebaBinarySensor(keba, "Plug", "Plug", "plug_state", DEVICE_CLASS_PLUG),
KebaBinarySensor(
keba, "State", "Charging State", "charging_state", DEVICE_CLASS_POWER
),
KebaBinarySensor(
keba, "Tmo FS", "Failsafe Mode", "failsafe_mode_state", DEVICE_CLASS_SAFETY
),
]
async_add_entities(sensors) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"keba",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"sensors",
"=",
"[",
"KebaBinarySensor",
"(",
"keba",
",",
"\"Online\"",
",",
"\"Status\"",
",",
"\"device_state\"",
",",
"DEVICE_CLASS_CONNECTIVITY",
")",
",",
"KebaBinarySensor",
"(",
"keba",
",",
"\"Plug\"",
",",
"\"Plug\"",
",",
"\"plug_state\"",
",",
"DEVICE_CLASS_PLUG",
")",
",",
"KebaBinarySensor",
"(",
"keba",
",",
"\"State\"",
",",
"\"Charging State\"",
",",
"\"charging_state\"",
",",
"DEVICE_CLASS_POWER",
")",
",",
"KebaBinarySensor",
"(",
"keba",
",",
"\"Tmo FS\"",
",",
"\"Failsafe Mode\"",
",",
"\"failsafe_mode_state\"",
",",
"DEVICE_CLASS_SAFETY",
")",
",",
"]",
"async_add_entities",
"(",
"sensors",
")"
] | [
12,
0
] | [
31,
31
] | python | en | ['en', 'da', 'en'] | True |
KebaBinarySensor.__init__ | (self, keba, key, name, entity_type, device_class) | Initialize the KEBA Sensor. | Initialize the KEBA Sensor. | def __init__(self, keba, key, name, entity_type, device_class):
"""Initialize the KEBA Sensor."""
self._key = key
self._keba = keba
self._name = name
self._entity_type = entity_type
self._device_class = device_class
self._is_on = None
self._attributes = {} | [
"def",
"__init__",
"(",
"self",
",",
"keba",
",",
"key",
",",
"name",
",",
"entity_type",
",",
"device_class",
")",
":",
"self",
".",
"_key",
"=",
"key",
"self",
".",
"_keba",
"=",
"keba",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_entity_type",
"=",
"entity_type",
"self",
".",
"_device_class",
"=",
"device_class",
"self",
".",
"_is_on",
"=",
"None",
"self",
".",
"_attributes",
"=",
"{",
"}"
] | [
37,
4
] | [
45,
29
] | python | en | ['en', 'sq', 'en'] | True |
KebaBinarySensor.should_poll | (self) | Deactivate polling. Data updated by KebaHandler. | Deactivate polling. Data updated by KebaHandler. | def should_poll(self):
"""Deactivate polling. Data updated by KebaHandler."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
48,
4
] | [
50,
20
] | python | en | ['en', 'en', 'en'] | True |
KebaBinarySensor.unique_id | (self) | Return the unique ID of the binary sensor. | Return the unique ID of the binary sensor. | def unique_id(self):
"""Return the unique ID of the binary sensor."""
return f"{self._keba.device_id}_{self._entity_type}" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self._keba.device_id}_{self._entity_type}\""
] | [
53,
4
] | [
55,
60
] | python | en | ['en', 'it', 'en'] | True |
KebaBinarySensor.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return f"{self._keba.device_name} {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self._keba.device_name} {self._name}\""
] | [
58,
4
] | [
60,
55
] | python | en | ['en', 'en', 'en'] | True |
KebaBinarySensor.device_class | (self) | Return the class of this sensor. | Return the class of this sensor. | def device_class(self):
"""Return the class of this sensor."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
63,
4
] | [
65,
33
] | python | en | ['en', 'en', 'en'] | True |
KebaBinarySensor.is_on | (self) | Return true if sensor is on. | Return true if sensor is on. | def is_on(self):
"""Return true if sensor is on."""
return self._is_on | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_on"
] | [
68,
4
] | [
70,
26
] | python | en | ['en', 'et', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.