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
list | start_point
list | end_point
list | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
LcnOutputsCover.assumed_state | (self) | Return True if unable to access real state of the entity. | Return True if unable to access real state of the entity. | def assumed_state(self):
"""Return True if unable to access real state of the entity."""
return True | [
"def",
"assumed_state",
"(",
"self",
")",
":",
"return",
"True"
] | [
82,
4
] | [
84,
19
] | python | en | ['en', 'en', 'en'] | True |
LcnOutputsCover.async_close_cover | (self, **kwargs) | Close the cover. | Close the cover. | async def async_close_cover(self, **kwargs):
"""Close the cover."""
self._is_opening = False
self._is_closing = True
state = pypck.lcn_defs.MotorStateModifier.DOWN
self.address_connection.control_motors_outputs(state, self.reverse_time)
self.async_write_ha_state() | [
"async",
"def",
"async_close_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_opening",
"=",
"False",
"self",
".",
"_is_closing",
"=",
"True",
"state",
"=",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"DOWN",
"self",
".",
"address_connection",
".",
"control_motors_outputs",
"(",
"state",
",",
"self",
".",
"reverse_time",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
86,
4
] | [
92,
35
] | python | en | ['en', 'en', 'en'] | True |
LcnOutputsCover.async_open_cover | (self, **kwargs) | Open the cover. | Open the cover. | async def async_open_cover(self, **kwargs):
"""Open the cover."""
self._is_closed = False
self._is_opening = True
self._is_closing = False
state = pypck.lcn_defs.MotorStateModifier.UP
self.address_connection.control_motors_outputs(state, self.reverse_time)
self.async_write_ha_state() | [
"async",
"def",
"async_open_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_closed",
"=",
"False",
"self",
".",
"_is_opening",
"=",
"True",
"self",
".",
"_is_closing",
"=",
"False",
"state",
"=",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"UP",
"self",
".",
"address_connection",
".",
"control_motors_outputs",
"(",
"state",
",",
"self",
".",
"reverse_time",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
94,
4
] | [
101,
35
] | python | en | ['en', 'en', 'en'] | True |
LcnOutputsCover.async_stop_cover | (self, **kwargs) | Stop the cover. | Stop the cover. | async def async_stop_cover(self, **kwargs):
"""Stop the cover."""
self._is_closing = False
self._is_opening = False
state = pypck.lcn_defs.MotorStateModifier.STOP
self.address_connection.control_motors_outputs(state)
self.async_write_ha_state() | [
"async",
"def",
"async_stop_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_closing",
"=",
"False",
"self",
".",
"_is_opening",
"=",
"False",
"state",
"=",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"STOP",
"self",
".",
"address_connection",
".",
"control_motors_outputs",
"(",
"state",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
103,
4
] | [
109,
35
] | python | en | ['en', 'en', 'en'] | True |
LcnOutputsCover.input_received | (self, input_obj) | Set cover states when LCN input object (command) is received. | Set cover states when LCN input object (command) is received. | def input_received(self, input_obj):
"""Set cover states when LCN input object (command) is received."""
if (
not isinstance(input_obj, pypck.inputs.ModStatusOutput)
or input_obj.get_output_id() not in self.output_ids
):
return
if input_obj.get_percent() > 0: # motor is on
if input_obj.get_output_id() == self.output_ids[0]:
self._is_opening = True
self._is_closing = False
else: # self.output_ids[1]
self._is_opening = False
self._is_closing = True
self._is_closed = self._is_closing
else: # motor is off
# cover is assumed to be closed if we were in closing state before
self._is_closed = self._is_closing
self._is_closing = False
self._is_opening = False
self.async_write_ha_state() | [
"def",
"input_received",
"(",
"self",
",",
"input_obj",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"input_obj",
",",
"pypck",
".",
"inputs",
".",
"ModStatusOutput",
")",
"or",
"input_obj",
".",
"get_output_id",
"(",
")",
"not",
"in",
"self",
".",
"output_ids",
")",
":",
"return",
"if",
"input_obj",
".",
"get_percent",
"(",
")",
">",
"0",
":",
"# motor is on",
"if",
"input_obj",
".",
"get_output_id",
"(",
")",
"==",
"self",
".",
"output_ids",
"[",
"0",
"]",
":",
"self",
".",
"_is_opening",
"=",
"True",
"self",
".",
"_is_closing",
"=",
"False",
"else",
":",
"# self.output_ids[1]",
"self",
".",
"_is_opening",
"=",
"False",
"self",
".",
"_is_closing",
"=",
"True",
"self",
".",
"_is_closed",
"=",
"self",
".",
"_is_closing",
"else",
":",
"# motor is off",
"# cover is assumed to be closed if we were in closing state before",
"self",
".",
"_is_closed",
"=",
"self",
".",
"_is_closing",
"self",
".",
"_is_closing",
"=",
"False",
"self",
".",
"_is_opening",
"=",
"False",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
111,
4
] | [
133,
35
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.__init__ | (self, config, address_connection) | Initialize the LCN cover. | Initialize the LCN cover. | def __init__(self, config, address_connection):
"""Initialize the LCN cover."""
super().__init__(config, address_connection)
self.motor = pypck.lcn_defs.MotorPort[config[CONF_MOTOR]]
self.motor_port_onoff = self.motor.value * 2
self.motor_port_updown = self.motor_port_onoff + 1
self._is_closed = False
self._is_closing = False
self._is_opening = False | [
"def",
"__init__",
"(",
"self",
",",
"config",
",",
"address_connection",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"config",
",",
"address_connection",
")",
"self",
".",
"motor",
"=",
"pypck",
".",
"lcn_defs",
".",
"MotorPort",
"[",
"config",
"[",
"CONF_MOTOR",
"]",
"]",
"self",
".",
"motor_port_onoff",
"=",
"self",
".",
"motor",
".",
"value",
"*",
"2",
"self",
".",
"motor_port_updown",
"=",
"self",
".",
"motor_port_onoff",
"+",
"1",
"self",
".",
"_is_closed",
"=",
"False",
"self",
".",
"_is_closing",
"=",
"False",
"self",
".",
"_is_opening",
"=",
"False"
] | [
139,
4
] | [
149,
32
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.async_added_to_hass | (self) | Run when entity about to be added to hass. | Run when entity about to be added to hass. | async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
await super().async_added_to_hass()
await self.address_connection.activate_status_request_handler(self.motor) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"await",
"self",
".",
"address_connection",
".",
"activate_status_request_handler",
"(",
"self",
".",
"motor",
")"
] | [
151,
4
] | [
154,
81
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.is_closed | (self) | Return if the cover is closed. | Return if the cover is closed. | def is_closed(self):
"""Return if the cover is closed."""
return self._is_closed | [
"def",
"is_closed",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_closed"
] | [
157,
4
] | [
159,
30
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.is_opening | (self) | Return if the cover is opening or not. | Return if the cover is opening or not. | def is_opening(self):
"""Return if the cover is opening or not."""
return self._is_opening | [
"def",
"is_opening",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_opening"
] | [
162,
4
] | [
164,
31
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.is_closing | (self) | Return if the cover is closing or not. | Return if the cover is closing or not. | def is_closing(self):
"""Return if the cover is closing or not."""
return self._is_closing | [
"def",
"is_closing",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_closing"
] | [
167,
4
] | [
169,
31
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.assumed_state | (self) | Return True if unable to access real state of the entity. | Return True if unable to access real state of the entity. | def assumed_state(self):
"""Return True if unable to access real state of the entity."""
return True | [
"def",
"assumed_state",
"(",
"self",
")",
":",
"return",
"True"
] | [
172,
4
] | [
174,
19
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.async_close_cover | (self, **kwargs) | Close the cover. | Close the cover. | async def async_close_cover(self, **kwargs):
"""Close the cover."""
self._is_opening = False
self._is_closing = True
states = [pypck.lcn_defs.MotorStateModifier.NOCHANGE] * 4
states[self.motor.value] = pypck.lcn_defs.MotorStateModifier.DOWN
self.address_connection.control_motors_relays(states)
self.async_write_ha_state() | [
"async",
"def",
"async_close_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_opening",
"=",
"False",
"self",
".",
"_is_closing",
"=",
"True",
"states",
"=",
"[",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"NOCHANGE",
"]",
"*",
"4",
"states",
"[",
"self",
".",
"motor",
".",
"value",
"]",
"=",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"DOWN",
"self",
".",
"address_connection",
".",
"control_motors_relays",
"(",
"states",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
176,
4
] | [
183,
35
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.async_open_cover | (self, **kwargs) | Open the cover. | Open the cover. | async def async_open_cover(self, **kwargs):
"""Open the cover."""
self._is_closed = False
self._is_opening = True
self._is_closing = False
states = [pypck.lcn_defs.MotorStateModifier.NOCHANGE] * 4
states[self.motor.value] = pypck.lcn_defs.MotorStateModifier.UP
self.address_connection.control_motors_relays(states)
self.async_write_ha_state() | [
"async",
"def",
"async_open_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_closed",
"=",
"False",
"self",
".",
"_is_opening",
"=",
"True",
"self",
".",
"_is_closing",
"=",
"False",
"states",
"=",
"[",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"NOCHANGE",
"]",
"*",
"4",
"states",
"[",
"self",
".",
"motor",
".",
"value",
"]",
"=",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"UP",
"self",
".",
"address_connection",
".",
"control_motors_relays",
"(",
"states",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
185,
4
] | [
193,
35
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.async_stop_cover | (self, **kwargs) | Stop the cover. | Stop the cover. | async def async_stop_cover(self, **kwargs):
"""Stop the cover."""
self._is_closing = False
self._is_opening = False
states = [pypck.lcn_defs.MotorStateModifier.NOCHANGE] * 4
states[self.motor.value] = pypck.lcn_defs.MotorStateModifier.STOP
self.address_connection.control_motors_relays(states)
self.async_write_ha_state() | [
"async",
"def",
"async_stop_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_is_closing",
"=",
"False",
"self",
".",
"_is_opening",
"=",
"False",
"states",
"=",
"[",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"NOCHANGE",
"]",
"*",
"4",
"states",
"[",
"self",
".",
"motor",
".",
"value",
"]",
"=",
"pypck",
".",
"lcn_defs",
".",
"MotorStateModifier",
".",
"STOP",
"self",
".",
"address_connection",
".",
"control_motors_relays",
"(",
"states",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
195,
4
] | [
202,
35
] | python | en | ['en', 'en', 'en'] | True |
LcnRelayCover.input_received | (self, input_obj) | Set cover states when LCN input object (command) is received. | Set cover states when LCN input object (command) is received. | def input_received(self, input_obj):
"""Set cover states when LCN input object (command) is received."""
if not isinstance(input_obj, pypck.inputs.ModStatusRelays):
return
states = input_obj.states # list of boolean values (relay on/off)
if states[self.motor_port_onoff]: # motor is on
self._is_opening = not states[self.motor_port_updown] # set direction
self._is_closing = states[self.motor_port_updown] # set direction
else: # motor is off
self._is_opening = False
self._is_closing = False
self._is_closed = states[self.motor_port_updown]
self.async_write_ha_state() | [
"def",
"input_received",
"(",
"self",
",",
"input_obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_obj",
",",
"pypck",
".",
"inputs",
".",
"ModStatusRelays",
")",
":",
"return",
"states",
"=",
"input_obj",
".",
"states",
"# list of boolean values (relay on/off)",
"if",
"states",
"[",
"self",
".",
"motor_port_onoff",
"]",
":",
"# motor is on",
"self",
".",
"_is_opening",
"=",
"not",
"states",
"[",
"self",
".",
"motor_port_updown",
"]",
"# set direction",
"self",
".",
"_is_closing",
"=",
"states",
"[",
"self",
".",
"motor_port_updown",
"]",
"# set direction",
"else",
":",
"# motor is off",
"self",
".",
"_is_opening",
"=",
"False",
"self",
".",
"_is_closing",
"=",
"False",
"self",
".",
"_is_closed",
"=",
"states",
"[",
"self",
".",
"motor_port_updown",
"]",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
204,
4
] | [
218,
35
] | python | en | ['en', 'en', 'en'] | True |
_discovery | (config_info) | Discover receivers from configuration in the network. | Discover receivers from configuration in the network. | def _discovery(config_info):
"""Discover receivers from configuration in the network."""
if config_info.from_discovery:
receivers = rxv.RXV(
config_info.ctrl_url,
model_name=config_info.model,
friendly_name=config_info.name,
unit_desc_url=config_info.desc_url,
).zone_controllers()
_LOGGER.debug("Receivers: %s", receivers)
elif config_info.host is None:
receivers = []
for recv in rxv.find():
receivers.extend(recv.zone_controllers())
else:
receivers = rxv.RXV(config_info.ctrl_url, config_info.name).zone_controllers()
return receivers | [
"def",
"_discovery",
"(",
"config_info",
")",
":",
"if",
"config_info",
".",
"from_discovery",
":",
"receivers",
"=",
"rxv",
".",
"RXV",
"(",
"config_info",
".",
"ctrl_url",
",",
"model_name",
"=",
"config_info",
".",
"model",
",",
"friendly_name",
"=",
"config_info",
".",
"name",
",",
"unit_desc_url",
"=",
"config_info",
".",
"desc_url",
",",
")",
".",
"zone_controllers",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Receivers: %s\"",
",",
"receivers",
")",
"elif",
"config_info",
".",
"host",
"is",
"None",
":",
"receivers",
"=",
"[",
"]",
"for",
"recv",
"in",
"rxv",
".",
"find",
"(",
")",
":",
"receivers",
".",
"extend",
"(",
"recv",
".",
"zone_controllers",
"(",
")",
")",
"else",
":",
"receivers",
"=",
"rxv",
".",
"RXV",
"(",
"config_info",
".",
"ctrl_url",
",",
"config_info",
".",
"name",
")",
".",
"zone_controllers",
"(",
")",
"return",
"receivers"
] | [
98,
0
] | [
115,
20
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Yamaha platform. | Set up the Yamaha platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Yamaha platform."""
# Keep track of configured receivers so that we don't end up
# discovering a receiver dynamically that we have static config
# for. Map each device from its zone_id .
known_zones = hass.data.setdefault(DATA_YAMAHA, set())
# Get the Infos for configuration from config (YAML) or Discovery
config_info = YamahaConfigInfo(config=config, discovery_info=discovery_info)
# Async check if the Receivers are there in the network
receivers = await hass.async_add_executor_job(_discovery, config_info)
entities = []
for receiver in receivers:
if receiver.zone in config_info.zone_ignore:
continue
entity = YamahaDevice(
config_info.name,
receiver,
config_info.source_ignore,
config_info.source_names,
config_info.zone_names,
)
# Only add device if it's not already added
if entity.zone_id not in known_zones:
known_zones.add(entity.zone_id)
entities.append(entity)
else:
_LOGGER.debug("Ignoring duplicate receiver: %s", config_info.name)
async_add_entities(entities)
# Register Service 'select_scene'
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(
SERVICE_SELECT_SCENE,
{vol.Required(ATTR_SCENE): cv.string},
"set_scene",
)
# Register Service 'enable_output'
platform.async_register_entity_service(
SERVICE_ENABLE_OUTPUT,
{vol.Required(ATTR_ENABLED): cv.boolean, vol.Required(ATTR_PORT): cv.string},
"enable_output",
) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"# Keep track of configured receivers so that we don't end up",
"# discovering a receiver dynamically that we have static config",
"# for. Map each device from its zone_id .",
"known_zones",
"=",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DATA_YAMAHA",
",",
"set",
"(",
")",
")",
"# Get the Infos for configuration from config (YAML) or Discovery",
"config_info",
"=",
"YamahaConfigInfo",
"(",
"config",
"=",
"config",
",",
"discovery_info",
"=",
"discovery_info",
")",
"# Async check if the Receivers are there in the network",
"receivers",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"_discovery",
",",
"config_info",
")",
"entities",
"=",
"[",
"]",
"for",
"receiver",
"in",
"receivers",
":",
"if",
"receiver",
".",
"zone",
"in",
"config_info",
".",
"zone_ignore",
":",
"continue",
"entity",
"=",
"YamahaDevice",
"(",
"config_info",
".",
"name",
",",
"receiver",
",",
"config_info",
".",
"source_ignore",
",",
"config_info",
".",
"source_names",
",",
"config_info",
".",
"zone_names",
",",
")",
"# Only add device if it's not already added",
"if",
"entity",
".",
"zone_id",
"not",
"in",
"known_zones",
":",
"known_zones",
".",
"add",
"(",
"entity",
".",
"zone_id",
")",
"entities",
".",
"append",
"(",
"entity",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Ignoring duplicate receiver: %s\"",
",",
"config_info",
".",
"name",
")",
"async_add_entities",
"(",
"entities",
")",
"# Register Service 'select_scene'",
"platform",
"=",
"entity_platform",
".",
"current_platform",
".",
"get",
"(",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_SELECT_SCENE",
",",
"{",
"vol",
".",
"Required",
"(",
"ATTR_SCENE",
")",
":",
"cv",
".",
"string",
"}",
",",
"\"set_scene\"",
",",
")",
"# Register Service 'enable_output'",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_ENABLE_OUTPUT",
",",
"{",
"vol",
".",
"Required",
"(",
"ATTR_ENABLED",
")",
":",
"cv",
".",
"boolean",
",",
"vol",
".",
"Required",
"(",
"ATTR_PORT",
")",
":",
"cv",
".",
"string",
"}",
",",
"\"enable_output\"",
",",
")"
] | [
118,
0
] | [
165,
5
] | python | en | ['en', 'su', 'en'] | True |
YamahaConfigInfo.__init__ | (self, config: None, discovery_info: None) | Initialize the Configuration Info for Yamaha Receiver. | Initialize the Configuration Info for Yamaha Receiver. | def __init__(self, config: None, discovery_info: None):
"""Initialize the Configuration Info for Yamaha Receiver."""
self.name = config.get(CONF_NAME)
self.host = config.get(CONF_HOST)
self.ctrl_url = f"http://{self.host}:80/YamahaRemoteControl/ctrl"
self.source_ignore = config.get(CONF_SOURCE_IGNORE)
self.source_names = config.get(CONF_SOURCE_NAMES)
self.zone_ignore = config.get(CONF_ZONE_IGNORE)
self.zone_names = config.get(CONF_ZONE_NAMES)
self.from_discovery = False
if discovery_info is not None:
self.name = discovery_info.get("name")
self.model = discovery_info.get("model_name")
self.ctrl_url = discovery_info.get("control_url")
self.desc_url = discovery_info.get("description_url")
self.zone_ignore = []
self.from_discovery = True | [
"def",
"__init__",
"(",
"self",
",",
"config",
":",
"None",
",",
"discovery_info",
":",
"None",
")",
":",
"self",
".",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"self",
".",
"host",
"=",
"config",
".",
"get",
"(",
"CONF_HOST",
")",
"self",
".",
"ctrl_url",
"=",
"f\"http://{self.host}:80/YamahaRemoteControl/ctrl\"",
"self",
".",
"source_ignore",
"=",
"config",
".",
"get",
"(",
"CONF_SOURCE_IGNORE",
")",
"self",
".",
"source_names",
"=",
"config",
".",
"get",
"(",
"CONF_SOURCE_NAMES",
")",
"self",
".",
"zone_ignore",
"=",
"config",
".",
"get",
"(",
"CONF_ZONE_IGNORE",
")",
"self",
".",
"zone_names",
"=",
"config",
".",
"get",
"(",
"CONF_ZONE_NAMES",
")",
"self",
".",
"from_discovery",
"=",
"False",
"if",
"discovery_info",
"is",
"not",
"None",
":",
"self",
".",
"name",
"=",
"discovery_info",
".",
"get",
"(",
"\"name\"",
")",
"self",
".",
"model",
"=",
"discovery_info",
".",
"get",
"(",
"\"model_name\"",
")",
"self",
".",
"ctrl_url",
"=",
"discovery_info",
".",
"get",
"(",
"\"control_url\"",
")",
"self",
".",
"desc_url",
"=",
"discovery_info",
".",
"get",
"(",
"\"description_url\"",
")",
"self",
".",
"zone_ignore",
"=",
"[",
"]",
"self",
".",
"from_discovery",
"=",
"True"
] | [
79,
4
] | [
95,
38
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.__init__ | (self, name, receiver, source_ignore, source_names, zone_names) | Initialize the Yamaha Receiver. | Initialize the Yamaha Receiver. | def __init__(self, name, receiver, source_ignore, source_names, zone_names):
"""Initialize the Yamaha Receiver."""
self.receiver = receiver
self._muted = False
self._volume = 0
self._pwstate = STATE_OFF
self._current_source = None
self._sound_mode = None
self._sound_mode_list = None
self._source_list = None
self._source_ignore = source_ignore or []
self._source_names = source_names or {}
self._zone_names = zone_names or {}
self._reverse_mapping = None
self._playback_support = None
self._is_playback_supported = False
self._play_status = None
self._name = name
self._zone = receiver.zone | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"receiver",
",",
"source_ignore",
",",
"source_names",
",",
"zone_names",
")",
":",
"self",
".",
"receiver",
"=",
"receiver",
"self",
".",
"_muted",
"=",
"False",
"self",
".",
"_volume",
"=",
"0",
"self",
".",
"_pwstate",
"=",
"STATE_OFF",
"self",
".",
"_current_source",
"=",
"None",
"self",
".",
"_sound_mode",
"=",
"None",
"self",
".",
"_sound_mode_list",
"=",
"None",
"self",
".",
"_source_list",
"=",
"None",
"self",
".",
"_source_ignore",
"=",
"source_ignore",
"or",
"[",
"]",
"self",
".",
"_source_names",
"=",
"source_names",
"or",
"{",
"}",
"self",
".",
"_zone_names",
"=",
"zone_names",
"or",
"{",
"}",
"self",
".",
"_reverse_mapping",
"=",
"None",
"self",
".",
"_playback_support",
"=",
"None",
"self",
".",
"_is_playback_supported",
"=",
"False",
"self",
".",
"_play_status",
"=",
"None",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_zone",
"=",
"receiver",
".",
"zone"
] | [
171,
4
] | [
189,
34
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.update | (self) | Get the latest details from the device. | Get the latest details from the device. | def update(self):
"""Get the latest details from the device."""
try:
self._play_status = self.receiver.play_status()
except requests.exceptions.ConnectionError:
_LOGGER.info("Receiver is offline: %s", self._name)
return
if self.receiver.on:
if self._play_status is None:
self._pwstate = STATE_ON
elif self._play_status.playing:
self._pwstate = STATE_PLAYING
else:
self._pwstate = STATE_IDLE
else:
self._pwstate = STATE_OFF
self._muted = self.receiver.mute
self._volume = (self.receiver.volume / 100) + 1
if self.source_list is None:
self.build_source_list()
current_source = self.receiver.input
self._current_source = self._source_names.get(current_source, current_source)
self._playback_support = self.receiver.get_playback_support()
self._is_playback_supported = self.receiver.is_playback_supported(
self._current_source
)
surround_programs = self.receiver.surround_programs()
if surround_programs:
self._sound_mode = self.receiver.surround_program
self._sound_mode_list = surround_programs
else:
self._sound_mode = None
self._sound_mode_list = None | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_play_status",
"=",
"self",
".",
"receiver",
".",
"play_status",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"_LOGGER",
".",
"info",
"(",
"\"Receiver is offline: %s\"",
",",
"self",
".",
"_name",
")",
"return",
"if",
"self",
".",
"receiver",
".",
"on",
":",
"if",
"self",
".",
"_play_status",
"is",
"None",
":",
"self",
".",
"_pwstate",
"=",
"STATE_ON",
"elif",
"self",
".",
"_play_status",
".",
"playing",
":",
"self",
".",
"_pwstate",
"=",
"STATE_PLAYING",
"else",
":",
"self",
".",
"_pwstate",
"=",
"STATE_IDLE",
"else",
":",
"self",
".",
"_pwstate",
"=",
"STATE_OFF",
"self",
".",
"_muted",
"=",
"self",
".",
"receiver",
".",
"mute",
"self",
".",
"_volume",
"=",
"(",
"self",
".",
"receiver",
".",
"volume",
"/",
"100",
")",
"+",
"1",
"if",
"self",
".",
"source_list",
"is",
"None",
":",
"self",
".",
"build_source_list",
"(",
")",
"current_source",
"=",
"self",
".",
"receiver",
".",
"input",
"self",
".",
"_current_source",
"=",
"self",
".",
"_source_names",
".",
"get",
"(",
"current_source",
",",
"current_source",
")",
"self",
".",
"_playback_support",
"=",
"self",
".",
"receiver",
".",
"get_playback_support",
"(",
")",
"self",
".",
"_is_playback_supported",
"=",
"self",
".",
"receiver",
".",
"is_playback_supported",
"(",
"self",
".",
"_current_source",
")",
"surround_programs",
"=",
"self",
".",
"receiver",
".",
"surround_programs",
"(",
")",
"if",
"surround_programs",
":",
"self",
".",
"_sound_mode",
"=",
"self",
".",
"receiver",
".",
"surround_program",
"self",
".",
"_sound_mode_list",
"=",
"surround_programs",
"else",
":",
"self",
".",
"_sound_mode",
"=",
"None",
"self",
".",
"_sound_mode_list",
"=",
"None"
] | [
191,
4
] | [
227,
40
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.build_source_list | (self) | Build the source list. | Build the source list. | def build_source_list(self):
"""Build the source list."""
self._reverse_mapping = {
alias: source for source, alias in self._source_names.items()
}
self._source_list = sorted(
self._source_names.get(source, source)
for source in self.receiver.inputs()
if source not in self._source_ignore
) | [
"def",
"build_source_list",
"(",
"self",
")",
":",
"self",
".",
"_reverse_mapping",
"=",
"{",
"alias",
":",
"source",
"for",
"source",
",",
"alias",
"in",
"self",
".",
"_source_names",
".",
"items",
"(",
")",
"}",
"self",
".",
"_source_list",
"=",
"sorted",
"(",
"self",
".",
"_source_names",
".",
"get",
"(",
"source",
",",
"source",
")",
"for",
"source",
"in",
"self",
".",
"receiver",
".",
"inputs",
"(",
")",
"if",
"source",
"not",
"in",
"self",
".",
"_source_ignore",
")"
] | [
229,
4
] | [
239,
9
] | python | en | ['en', 'fr', 'en'] | True |
YamahaDevice.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
name = self._name
zone_name = self._zone_names.get(self._zone, self._zone)
if zone_name != "Main_Zone":
# Zone will be one of Main_Zone, Zone_2, Zone_3
name += f" {zone_name.replace('_', ' ')}"
return name | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_name",
"zone_name",
"=",
"self",
".",
"_zone_names",
".",
"get",
"(",
"self",
".",
"_zone",
",",
"self",
".",
"_zone",
")",
"if",
"zone_name",
"!=",
"\"Main_Zone\"",
":",
"# Zone will be one of Main_Zone, Zone_2, Zone_3",
"name",
"+=",
"f\" {zone_name.replace('_', ' ')}\"",
"return",
"name"
] | [
242,
4
] | [
249,
19
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self._pwstate | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pwstate"
] | [
252,
4
] | [
254,
28
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.volume_level | (self) | Volume level of the media player (0..1). | Volume level of the media player (0..1). | def volume_level(self):
"""Volume level of the media player (0..1)."""
return self._volume | [
"def",
"volume_level",
"(",
"self",
")",
":",
"return",
"self",
".",
"_volume"
] | [
257,
4
] | [
259,
27
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.is_volume_muted | (self) | Boolean if volume is currently muted. | Boolean if volume is currently muted. | def is_volume_muted(self):
"""Boolean if volume is currently muted."""
return self._muted | [
"def",
"is_volume_muted",
"(",
"self",
")",
":",
"return",
"self",
".",
"_muted"
] | [
262,
4
] | [
264,
26
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.source | (self) | Return the current input source. | Return the current input source. | def source(self):
"""Return the current input source."""
return self._current_source | [
"def",
"source",
"(",
"self",
")",
":",
"return",
"self",
".",
"_current_source"
] | [
267,
4
] | [
269,
35
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.sound_mode | (self) | Return the current sound mode. | Return the current sound mode. | def sound_mode(self):
"""Return the current sound mode."""
return self._sound_mode | [
"def",
"sound_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sound_mode"
] | [
272,
4
] | [
274,
31
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.sound_mode_list | (self) | Return the current sound mode. | Return the current sound mode. | def sound_mode_list(self):
"""Return the current sound mode."""
return self._sound_mode_list | [
"def",
"sound_mode_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sound_mode_list"
] | [
277,
4
] | [
279,
36
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.source_list | (self) | List of available input sources. | List of available input sources. | def source_list(self):
"""List of available input sources."""
return self._source_list | [
"def",
"source_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"_source_list"
] | [
282,
4
] | [
284,
32
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.zone_id | (self) | Return a zone_id to ensure 1 media player per zone. | Return a zone_id to ensure 1 media player per zone. | def zone_id(self):
"""Return a zone_id to ensure 1 media player per zone."""
return f"{self.receiver.ctrl_url}:{self._zone}" | [
"def",
"zone_id",
"(",
"self",
")",
":",
"return",
"f\"{self.receiver.ctrl_url}:{self._zone}\""
] | [
287,
4
] | [
289,
55
] | python | en | ['en', 'co', 'en'] | True |
YamahaDevice.supported_features | (self) | Flag media player features that are supported. | Flag media player features that are supported. | def supported_features(self):
"""Flag media player features that are supported."""
supported_features = SUPPORT_YAMAHA
supports = self._playback_support
mapping = {
"play": (SUPPORT_PLAY | SUPPORT_PLAY_MEDIA),
"pause": SUPPORT_PAUSE,
"stop": SUPPORT_STOP,
"skip_f": SUPPORT_NEXT_TRACK,
"skip_r": SUPPORT_PREVIOUS_TRACK,
}
for attr, feature in mapping.items():
if getattr(supports, attr, False):
supported_features |= feature
return supported_features | [
"def",
"supported_features",
"(",
"self",
")",
":",
"supported_features",
"=",
"SUPPORT_YAMAHA",
"supports",
"=",
"self",
".",
"_playback_support",
"mapping",
"=",
"{",
"\"play\"",
":",
"(",
"SUPPORT_PLAY",
"|",
"SUPPORT_PLAY_MEDIA",
")",
",",
"\"pause\"",
":",
"SUPPORT_PAUSE",
",",
"\"stop\"",
":",
"SUPPORT_STOP",
",",
"\"skip_f\"",
":",
"SUPPORT_NEXT_TRACK",
",",
"\"skip_r\"",
":",
"SUPPORT_PREVIOUS_TRACK",
",",
"}",
"for",
"attr",
",",
"feature",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"if",
"getattr",
"(",
"supports",
",",
"attr",
",",
"False",
")",
":",
"supported_features",
"|=",
"feature",
"return",
"supported_features"
] | [
292,
4
] | [
307,
33
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.turn_off | (self) | Turn off media player. | Turn off media player. | def turn_off(self):
"""Turn off media player."""
self.receiver.on = False | [
"def",
"turn_off",
"(",
"self",
")",
":",
"self",
".",
"receiver",
".",
"on",
"=",
"False"
] | [
309,
4
] | [
311,
32
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.set_volume_level | (self, volume) | Set volume level, range 0..1. | Set volume level, range 0..1. | def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
receiver_vol = 100 - (volume * 100)
negative_receiver_vol = -receiver_vol
self.receiver.volume = negative_receiver_vol | [
"def",
"set_volume_level",
"(",
"self",
",",
"volume",
")",
":",
"receiver_vol",
"=",
"100",
"-",
"(",
"volume",
"*",
"100",
")",
"negative_receiver_vol",
"=",
"-",
"receiver_vol",
"self",
".",
"receiver",
".",
"volume",
"=",
"negative_receiver_vol"
] | [
313,
4
] | [
317,
52
] | python | en | ['fr', 'zu', 'en'] | False |
YamahaDevice.mute_volume | (self, mute) | Mute (true) or unmute (false) media player. | Mute (true) or unmute (false) media player. | def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player."""
self.receiver.mute = mute | [
"def",
"mute_volume",
"(",
"self",
",",
"mute",
")",
":",
"self",
".",
"receiver",
".",
"mute",
"=",
"mute"
] | [
319,
4
] | [
321,
33
] | python | en | ['en', 'la', 'it'] | False |
YamahaDevice.turn_on | (self) | Turn the media player on. | Turn the media player on. | def turn_on(self):
"""Turn the media player on."""
self.receiver.on = True
self._volume = (self.receiver.volume / 100) + 1 | [
"def",
"turn_on",
"(",
"self",
")",
":",
"self",
".",
"receiver",
".",
"on",
"=",
"True",
"self",
".",
"_volume",
"=",
"(",
"self",
".",
"receiver",
".",
"volume",
"/",
"100",
")",
"+",
"1"
] | [
323,
4
] | [
326,
55
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.media_play | (self) | Send play command. | Send play command. | def media_play(self):
"""Send play command."""
self._call_playback_function(self.receiver.play, "play") | [
"def",
"media_play",
"(",
"self",
")",
":",
"self",
".",
"_call_playback_function",
"(",
"self",
".",
"receiver",
".",
"play",
",",
"\"play\"",
")"
] | [
328,
4
] | [
330,
64
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.media_pause | (self) | Send pause command. | Send pause command. | def media_pause(self):
"""Send pause command."""
self._call_playback_function(self.receiver.pause, "pause") | [
"def",
"media_pause",
"(",
"self",
")",
":",
"self",
".",
"_call_playback_function",
"(",
"self",
".",
"receiver",
".",
"pause",
",",
"\"pause\"",
")"
] | [
332,
4
] | [
334,
66
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.media_stop | (self) | Send stop command. | Send stop command. | def media_stop(self):
"""Send stop command."""
self._call_playback_function(self.receiver.stop, "stop") | [
"def",
"media_stop",
"(",
"self",
")",
":",
"self",
".",
"_call_playback_function",
"(",
"self",
".",
"receiver",
".",
"stop",
",",
"\"stop\"",
")"
] | [
336,
4
] | [
338,
64
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.media_previous_track | (self) | Send previous track command. | Send previous track command. | def media_previous_track(self):
"""Send previous track command."""
self._call_playback_function(self.receiver.previous, "previous track") | [
"def",
"media_previous_track",
"(",
"self",
")",
":",
"self",
".",
"_call_playback_function",
"(",
"self",
".",
"receiver",
".",
"previous",
",",
"\"previous track\"",
")"
] | [
340,
4
] | [
342,
78
] | python | en | ['en', 'it', 'en'] | True |
YamahaDevice.media_next_track | (self) | Send next track command. | Send next track command. | def media_next_track(self):
"""Send next track command."""
self._call_playback_function(self.receiver.next, "next track") | [
"def",
"media_next_track",
"(",
"self",
")",
":",
"self",
".",
"_call_playback_function",
"(",
"self",
".",
"receiver",
".",
"next",
",",
"\"next track\"",
")"
] | [
344,
4
] | [
346,
70
] | python | en | ['en', 'pt', 'en'] | True |
YamahaDevice.select_source | (self, source) | Select input source. | Select input source. | def select_source(self, source):
"""Select input source."""
self.receiver.input = self._reverse_mapping.get(source, source) | [
"def",
"select_source",
"(",
"self",
",",
"source",
")",
":",
"self",
".",
"receiver",
".",
"input",
"=",
"self",
".",
"_reverse_mapping",
".",
"get",
"(",
"source",
",",
"source",
")"
] | [
354,
4
] | [
356,
71
] | python | en | ['fr', 'su', 'en'] | False |
YamahaDevice.play_media | (self, media_type, media_id, **kwargs) | Play media from an ID.
This exposes a pass through for various input sources in the
Yamaha to direct play certain kinds of media. media_type is
treated as the input type that we are setting, and media id is
specific to it.
For the NET RADIO mediatype the format for ``media_id`` is a
"path" in your vtuner hierarchy. For instance:
``Bookmarks>Internet>Radio Paradise``. The separators are
``>`` and the parts of this are navigated by name behind the
scenes. There is a looping construct built into the yamaha
library to do this with a fallback timeout if the vtuner
service is unresponsive.
NOTE: this might take a while, because the only API interface
for setting the net radio station emulates button pressing and
navigating through the net radio menu hierarchy. And each sub
menu must be fetched by the receiver from the vtuner service.
| Play media from an ID. | def play_media(self, media_type, media_id, **kwargs):
"""Play media from an ID.
This exposes a pass through for various input sources in the
Yamaha to direct play certain kinds of media. media_type is
treated as the input type that we are setting, and media id is
specific to it.
For the NET RADIO mediatype the format for ``media_id`` is a
"path" in your vtuner hierarchy. For instance:
``Bookmarks>Internet>Radio Paradise``. The separators are
``>`` and the parts of this are navigated by name behind the
scenes. There is a looping construct built into the yamaha
library to do this with a fallback timeout if the vtuner
service is unresponsive.
NOTE: this might take a while, because the only API interface
for setting the net radio station emulates button pressing and
navigating through the net radio menu hierarchy. And each sub
menu must be fetched by the receiver from the vtuner service.
"""
if media_type == "NET RADIO":
self.receiver.net_radio(media_id) | [
"def",
"play_media",
"(",
"self",
",",
"media_type",
",",
"media_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"media_type",
"==",
"\"NET RADIO\"",
":",
"self",
".",
"receiver",
".",
"net_radio",
"(",
"media_id",
")"
] | [
358,
4
] | [
378,
45
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.enable_output | (self, port, enabled) | Enable or disable an output port.. | Enable or disable an output port.. | def enable_output(self, port, enabled):
"""Enable or disable an output port.."""
self.receiver.enable_output(port, enabled) | [
"def",
"enable_output",
"(",
"self",
",",
"port",
",",
"enabled",
")",
":",
"self",
".",
"receiver",
".",
"enable_output",
"(",
"port",
",",
"enabled",
")"
] | [
380,
4
] | [
382,
50
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.set_scene | (self, scene) | Set the current scene. | Set the current scene. | def set_scene(self, scene):
"""Set the current scene."""
try:
self.receiver.scene = scene
except AssertionError:
_LOGGER.warning("Scene '%s' does not exist!", scene) | [
"def",
"set_scene",
"(",
"self",
",",
"scene",
")",
":",
"try",
":",
"self",
".",
"receiver",
".",
"scene",
"=",
"scene",
"except",
"AssertionError",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Scene '%s' does not exist!\"",
",",
"scene",
")"
] | [
384,
4
] | [
389,
64
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.select_sound_mode | (self, sound_mode) | Set Sound Mode for Receiver.. | Set Sound Mode for Receiver.. | def select_sound_mode(self, sound_mode):
"""Set Sound Mode for Receiver.."""
self.receiver.surround_program = sound_mode | [
"def",
"select_sound_mode",
"(",
"self",
",",
"sound_mode",
")",
":",
"self",
".",
"receiver",
".",
"surround_program",
"=",
"sound_mode"
] | [
391,
4
] | [
393,
51
] | python | en | ['en', 'pt', 'en'] | True |
YamahaDevice.media_artist | (self) | Artist of current playing media. | Artist of current playing media. | def media_artist(self):
"""Artist of current playing media."""
if self._play_status is not None:
return self._play_status.artist | [
"def",
"media_artist",
"(",
"self",
")",
":",
"if",
"self",
".",
"_play_status",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_play_status",
".",
"artist"
] | [
396,
4
] | [
399,
43
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.media_album_name | (self) | Album of current playing media. | Album of current playing media. | def media_album_name(self):
"""Album of current playing media."""
if self._play_status is not None:
return self._play_status.album | [
"def",
"media_album_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_play_status",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_play_status",
".",
"album"
] | [
402,
4
] | [
405,
42
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.media_content_type | (self) | Content type of current playing media. | Content type of current playing media. | def media_content_type(self):
"""Content type of current playing media."""
# Loose assumption that if playback is supported, we are playing music
if self._is_playback_supported:
return MEDIA_TYPE_MUSIC
return None | [
"def",
"media_content_type",
"(",
"self",
")",
":",
"# Loose assumption that if playback is supported, we are playing music",
"if",
"self",
".",
"_is_playback_supported",
":",
"return",
"MEDIA_TYPE_MUSIC",
"return",
"None"
] | [
408,
4
] | [
413,
19
] | python | en | ['en', 'en', 'en'] | True |
YamahaDevice.media_title | (self) | Artist of current playing media. | Artist of current playing media. | def media_title(self):
"""Artist of current playing media."""
if self._play_status is not None:
song = self._play_status.song
station = self._play_status.station
# If both song and station is available, print both, otherwise
# just the one we have.
if song and station:
return f"{station}: {song}"
return song or station | [
"def",
"media_title",
"(",
"self",
")",
":",
"if",
"self",
".",
"_play_status",
"is",
"not",
"None",
":",
"song",
"=",
"self",
".",
"_play_status",
".",
"song",
"station",
"=",
"self",
".",
"_play_status",
".",
"station",
"# If both song and station is available, print both, otherwise",
"# just the one we have.",
"if",
"song",
"and",
"station",
":",
"return",
"f\"{station}: {song}\"",
"return",
"song",
"or",
"station"
] | [
416,
4
] | [
427,
34
] | python | en | ['en', 'en', 'en'] | True |
test_invalid_base_schema | (schema) | Test base schema validation. | Test base schema validation. | def test_invalid_base_schema(schema):
"""Test base schema validation."""
with pytest.raises(vol.Invalid):
selector.validate_selector(schema) | [
"def",
"test_invalid_base_schema",
"(",
"schema",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"vol",
".",
"Invalid",
")",
":",
"selector",
".",
"validate_selector",
"(",
"schema",
")"
] | [
10,
0
] | [
13,
42
] | python | de | ['de', 'de', 'en'] | True |
test_validate_selector | () | Test return is the same as input. | Test return is the same as input. | def test_validate_selector():
"""Test return is the same as input."""
schema = {"device": {"manufacturer": "mock-manuf", "model": "mock-model"}}
assert schema == selector.validate_selector(schema) | [
"def",
"test_validate_selector",
"(",
")",
":",
"schema",
"=",
"{",
"\"device\"",
":",
"{",
"\"manufacturer\"",
":",
"\"mock-manuf\"",
",",
"\"model\"",
":",
"\"mock-model\"",
"}",
"}",
"assert",
"schema",
"==",
"selector",
".",
"validate_selector",
"(",
"schema",
")"
] | [
16,
0
] | [
19,
55
] | python | en | ['en', 'en', 'en'] | True |
test_device_selector_schema | (schema) | Test device selector. | Test device selector. | def test_device_selector_schema(schema):
"""Test device selector."""
selector.validate_selector({"device": schema}) | [
"def",
"test_device_selector_schema",
"(",
"schema",
")",
":",
"selector",
".",
"validate_selector",
"(",
"{",
"\"device\"",
":",
"schema",
"}",
")"
] | [
33,
0
] | [
35,
50
] | python | en | ['fr', 'en', 'en'] | True |
test_entity_selector_schema | (schema) | Test entity selector. | Test entity selector. | def test_entity_selector_schema(schema):
"""Test entity selector."""
selector.validate_selector({"entity": schema}) | [
"def",
"test_entity_selector_schema",
"(",
"schema",
")",
":",
"selector",
".",
"validate_selector",
"(",
"{",
"\"entity\"",
":",
"schema",
"}",
")"
] | [
47,
0
] | [
49,
50
] | python | en | ['en', 'en', 'en'] | True |
get_entity_state | (config, entity) | Retrieve and convert state and brightness values for an entity. | Retrieve and convert state and brightness values for an entity. | def get_entity_state(config, entity):
"""Retrieve and convert state and brightness values for an entity."""
cached_state_entry = config.cached_states.get(entity.entity_id, None)
cached_state = None
# Check if we have a cached entry, and if so if it hasn't expired.
if cached_state_entry is not None:
entry_state, entry_time = cached_state_entry
if entry_time is None:
# Handle the case where the entity is listed in config.off_maps_to_on_domains.
cached_state = entry_state
elif time.time() - entry_time < STATE_CACHED_TIMEOUT and entry_state[
STATE_ON
] == (entity.state != STATE_OFF):
# We only want to use the cache if the actual state of the entity
# is in sync so that it can be detected as an error by Alexa.
cached_state = entry_state
else:
# Remove the now stale cached entry.
config.cached_states.pop(entity.entity_id)
data = {
STATE_ON: False,
STATE_BRIGHTNESS: None,
STATE_HUE: None,
STATE_SATURATION: None,
STATE_COLOR_TEMP: None,
}
if cached_state is None:
data[STATE_ON] = entity.state != STATE_OFF
if data[STATE_ON]:
data[STATE_BRIGHTNESS] = hass_to_hue_brightness(
entity.attributes.get(ATTR_BRIGHTNESS, 0)
)
hue_sat = entity.attributes.get(ATTR_HS_COLOR)
if hue_sat is not None:
hue = hue_sat[0]
sat = hue_sat[1]
# Convert hass hs values back to hue hs values
data[STATE_HUE] = int((hue / 360.0) * HUE_API_STATE_HUE_MAX)
data[STATE_SATURATION] = int((sat / 100.0) * HUE_API_STATE_SAT_MAX)
else:
data[STATE_HUE] = HUE_API_STATE_HUE_MIN
data[STATE_SATURATION] = HUE_API_STATE_SAT_MIN
data[STATE_COLOR_TEMP] = entity.attributes.get(ATTR_COLOR_TEMP, 0)
else:
data[STATE_BRIGHTNESS] = 0
data[STATE_HUE] = 0
data[STATE_SATURATION] = 0
data[STATE_COLOR_TEMP] = 0
# Get the entity's supported features
entity_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if entity.domain == light.DOMAIN:
if entity_features & SUPPORT_BRIGHTNESS:
pass
elif entity.domain == climate.DOMAIN:
temperature = entity.attributes.get(ATTR_TEMPERATURE, 0)
# Convert 0-100 to 0-254
data[STATE_BRIGHTNESS] = round(temperature * HUE_API_STATE_BRI_MAX / 100)
elif entity.domain == humidifier.DOMAIN:
humidity = entity.attributes.get(ATTR_HUMIDITY, 0)
# Convert 0-100 to 0-254
data[STATE_BRIGHTNESS] = round(humidity * HUE_API_STATE_BRI_MAX / 100)
elif entity.domain == media_player.DOMAIN:
level = entity.attributes.get(
ATTR_MEDIA_VOLUME_LEVEL, 1.0 if data[STATE_ON] else 0.0
)
# Convert 0.0-1.0 to 0-254
data[STATE_BRIGHTNESS] = round(min(1.0, level) * HUE_API_STATE_BRI_MAX)
elif entity.domain == fan.DOMAIN:
speed = entity.attributes.get(ATTR_SPEED, 0)
# Convert 0.0-1.0 to 0-254
data[STATE_BRIGHTNESS] = 0
if speed == SPEED_LOW:
data[STATE_BRIGHTNESS] = 85
elif speed == SPEED_MEDIUM:
data[STATE_BRIGHTNESS] = 170
elif speed == SPEED_HIGH:
data[STATE_BRIGHTNESS] = HUE_API_STATE_BRI_MAX
elif entity.domain == cover.DOMAIN:
level = entity.attributes.get(ATTR_CURRENT_POSITION, 0)
data[STATE_BRIGHTNESS] = round(level / 100 * HUE_API_STATE_BRI_MAX)
else:
data = cached_state
# Make sure brightness is valid
if data[STATE_BRIGHTNESS] is None:
data[STATE_BRIGHTNESS] = HUE_API_STATE_BRI_MAX if data[STATE_ON] else 0
# Make sure hue/saturation are valid
if (data[STATE_HUE] is None) or (data[STATE_SATURATION] is None):
data[STATE_HUE] = 0
data[STATE_SATURATION] = 0
# If the light is off, set the color to off
if data[STATE_BRIGHTNESS] == 0:
data[STATE_HUE] = 0
data[STATE_SATURATION] = 0
# Clamp brightness, hue, saturation, and color temp to valid values
for (key, v_min, v_max) in (
(STATE_BRIGHTNESS, HUE_API_STATE_BRI_MIN, HUE_API_STATE_BRI_MAX),
(STATE_HUE, HUE_API_STATE_HUE_MIN, HUE_API_STATE_HUE_MAX),
(STATE_SATURATION, HUE_API_STATE_SAT_MIN, HUE_API_STATE_SAT_MAX),
(STATE_COLOR_TEMP, HUE_API_STATE_CT_MIN, HUE_API_STATE_CT_MAX),
):
if data[key] is not None:
data[key] = max(v_min, min(data[key], v_max))
return data | [
"def",
"get_entity_state",
"(",
"config",
",",
"entity",
")",
":",
"cached_state_entry",
"=",
"config",
".",
"cached_states",
".",
"get",
"(",
"entity",
".",
"entity_id",
",",
"None",
")",
"cached_state",
"=",
"None",
"# Check if we have a cached entry, and if so if it hasn't expired.",
"if",
"cached_state_entry",
"is",
"not",
"None",
":",
"entry_state",
",",
"entry_time",
"=",
"cached_state_entry",
"if",
"entry_time",
"is",
"None",
":",
"# Handle the case where the entity is listed in config.off_maps_to_on_domains.",
"cached_state",
"=",
"entry_state",
"elif",
"time",
".",
"time",
"(",
")",
"-",
"entry_time",
"<",
"STATE_CACHED_TIMEOUT",
"and",
"entry_state",
"[",
"STATE_ON",
"]",
"==",
"(",
"entity",
".",
"state",
"!=",
"STATE_OFF",
")",
":",
"# We only want to use the cache if the actual state of the entity",
"# is in sync so that it can be detected as an error by Alexa.",
"cached_state",
"=",
"entry_state",
"else",
":",
"# Remove the now stale cached entry.",
"config",
".",
"cached_states",
".",
"pop",
"(",
"entity",
".",
"entity_id",
")",
"data",
"=",
"{",
"STATE_ON",
":",
"False",
",",
"STATE_BRIGHTNESS",
":",
"None",
",",
"STATE_HUE",
":",
"None",
",",
"STATE_SATURATION",
":",
"None",
",",
"STATE_COLOR_TEMP",
":",
"None",
",",
"}",
"if",
"cached_state",
"is",
"None",
":",
"data",
"[",
"STATE_ON",
"]",
"=",
"entity",
".",
"state",
"!=",
"STATE_OFF",
"if",
"data",
"[",
"STATE_ON",
"]",
":",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"hass_to_hue_brightness",
"(",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_BRIGHTNESS",
",",
"0",
")",
")",
"hue_sat",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_HS_COLOR",
")",
"if",
"hue_sat",
"is",
"not",
"None",
":",
"hue",
"=",
"hue_sat",
"[",
"0",
"]",
"sat",
"=",
"hue_sat",
"[",
"1",
"]",
"# Convert hass hs values back to hue hs values",
"data",
"[",
"STATE_HUE",
"]",
"=",
"int",
"(",
"(",
"hue",
"/",
"360.0",
")",
"*",
"HUE_API_STATE_HUE_MAX",
")",
"data",
"[",
"STATE_SATURATION",
"]",
"=",
"int",
"(",
"(",
"sat",
"/",
"100.0",
")",
"*",
"HUE_API_STATE_SAT_MAX",
")",
"else",
":",
"data",
"[",
"STATE_HUE",
"]",
"=",
"HUE_API_STATE_HUE_MIN",
"data",
"[",
"STATE_SATURATION",
"]",
"=",
"HUE_API_STATE_SAT_MIN",
"data",
"[",
"STATE_COLOR_TEMP",
"]",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_COLOR_TEMP",
",",
"0",
")",
"else",
":",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"0",
"data",
"[",
"STATE_HUE",
"]",
"=",
"0",
"data",
"[",
"STATE_SATURATION",
"]",
"=",
"0",
"data",
"[",
"STATE_COLOR_TEMP",
"]",
"=",
"0",
"# Get the entity's supported features",
"entity_features",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_SUPPORTED_FEATURES",
",",
"0",
")",
"if",
"entity",
".",
"domain",
"==",
"light",
".",
"DOMAIN",
":",
"if",
"entity_features",
"&",
"SUPPORT_BRIGHTNESS",
":",
"pass",
"elif",
"entity",
".",
"domain",
"==",
"climate",
".",
"DOMAIN",
":",
"temperature",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_TEMPERATURE",
",",
"0",
")",
"# Convert 0-100 to 0-254",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"round",
"(",
"temperature",
"*",
"HUE_API_STATE_BRI_MAX",
"/",
"100",
")",
"elif",
"entity",
".",
"domain",
"==",
"humidifier",
".",
"DOMAIN",
":",
"humidity",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_HUMIDITY",
",",
"0",
")",
"# Convert 0-100 to 0-254",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"round",
"(",
"humidity",
"*",
"HUE_API_STATE_BRI_MAX",
"/",
"100",
")",
"elif",
"entity",
".",
"domain",
"==",
"media_player",
".",
"DOMAIN",
":",
"level",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_MEDIA_VOLUME_LEVEL",
",",
"1.0",
"if",
"data",
"[",
"STATE_ON",
"]",
"else",
"0.0",
")",
"# Convert 0.0-1.0 to 0-254",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"round",
"(",
"min",
"(",
"1.0",
",",
"level",
")",
"*",
"HUE_API_STATE_BRI_MAX",
")",
"elif",
"entity",
".",
"domain",
"==",
"fan",
".",
"DOMAIN",
":",
"speed",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_SPEED",
",",
"0",
")",
"# Convert 0.0-1.0 to 0-254",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"0",
"if",
"speed",
"==",
"SPEED_LOW",
":",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"85",
"elif",
"speed",
"==",
"SPEED_MEDIUM",
":",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"170",
"elif",
"speed",
"==",
"SPEED_HIGH",
":",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"HUE_API_STATE_BRI_MAX",
"elif",
"entity",
".",
"domain",
"==",
"cover",
".",
"DOMAIN",
":",
"level",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_CURRENT_POSITION",
",",
"0",
")",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"round",
"(",
"level",
"/",
"100",
"*",
"HUE_API_STATE_BRI_MAX",
")",
"else",
":",
"data",
"=",
"cached_state",
"# Make sure brightness is valid",
"if",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"None",
":",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"HUE_API_STATE_BRI_MAX",
"if",
"data",
"[",
"STATE_ON",
"]",
"else",
"0",
"# Make sure hue/saturation are valid",
"if",
"(",
"data",
"[",
"STATE_HUE",
"]",
"is",
"None",
")",
"or",
"(",
"data",
"[",
"STATE_SATURATION",
"]",
"is",
"None",
")",
":",
"data",
"[",
"STATE_HUE",
"]",
"=",
"0",
"data",
"[",
"STATE_SATURATION",
"]",
"=",
"0",
"# If the light is off, set the color to off",
"if",
"data",
"[",
"STATE_BRIGHTNESS",
"]",
"==",
"0",
":",
"data",
"[",
"STATE_HUE",
"]",
"=",
"0",
"data",
"[",
"STATE_SATURATION",
"]",
"=",
"0",
"# Clamp brightness, hue, saturation, and color temp to valid values",
"for",
"(",
"key",
",",
"v_min",
",",
"v_max",
")",
"in",
"(",
"(",
"STATE_BRIGHTNESS",
",",
"HUE_API_STATE_BRI_MIN",
",",
"HUE_API_STATE_BRI_MAX",
")",
",",
"(",
"STATE_HUE",
",",
"HUE_API_STATE_HUE_MIN",
",",
"HUE_API_STATE_HUE_MAX",
")",
",",
"(",
"STATE_SATURATION",
",",
"HUE_API_STATE_SAT_MIN",
",",
"HUE_API_STATE_SAT_MAX",
")",
",",
"(",
"STATE_COLOR_TEMP",
",",
"HUE_API_STATE_CT_MIN",
",",
"HUE_API_STATE_CT_MAX",
")",
",",
")",
":",
"if",
"data",
"[",
"key",
"]",
"is",
"not",
"None",
":",
"data",
"[",
"key",
"]",
"=",
"max",
"(",
"v_min",
",",
"min",
"(",
"data",
"[",
"key",
"]",
",",
"v_max",
")",
")",
"return",
"data"
] | [
578,
0
] | [
691,
15
] | python | en | ['en', 'en', 'en'] | True |
entity_to_json | (config, entity) | Convert an entity to its Hue bridge JSON representation. | Convert an entity to its Hue bridge JSON representation. | def entity_to_json(config, entity):
"""Convert an entity to its Hue bridge JSON representation."""
entity_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
unique_id = hashlib.md5(entity.entity_id.encode()).hexdigest()
unique_id = f"00:{unique_id[0:2]}:{unique_id[2:4]}:{unique_id[4:6]}:{unique_id[6:8]}:{unique_id[8:10]}:{unique_id[10:12]}:{unique_id[12:14]}-{unique_id[14:16]}"
state = get_entity_state(config, entity)
retval = {
"state": {
HUE_API_STATE_ON: state[STATE_ON],
"reachable": entity.state != STATE_UNAVAILABLE,
"mode": "homeautomation",
},
"name": config.get_entity_name(entity),
"uniqueid": unique_id,
"manufacturername": "Home Assistant",
"swversion": "123",
}
if (
(entity_features & SUPPORT_BRIGHTNESS)
and (entity_features & SUPPORT_COLOR)
and (entity_features & SUPPORT_COLOR_TEMP)
):
# Extended Color light (Zigbee Device ID: 0x0210)
# Same as Color light, but which supports additional setting of color temperature
retval["type"] = "Extended color light"
retval["modelid"] = "HASS231"
retval["state"].update(
{
HUE_API_STATE_BRI: state[STATE_BRIGHTNESS],
HUE_API_STATE_HUE: state[STATE_HUE],
HUE_API_STATE_SAT: state[STATE_SATURATION],
HUE_API_STATE_CT: state[STATE_COLOR_TEMP],
HUE_API_STATE_EFFECT: "none",
}
)
if state[STATE_HUE] > 0 or state[STATE_SATURATION] > 0:
retval["state"][HUE_API_STATE_COLORMODE] = "hs"
else:
retval["state"][HUE_API_STATE_COLORMODE] = "ct"
elif (entity_features & SUPPORT_BRIGHTNESS) and (entity_features & SUPPORT_COLOR):
# Color light (Zigbee Device ID: 0x0200)
# Supports on/off, dimming and color control (hue/saturation, enhanced hue, color loop and XY)
retval["type"] = "Color light"
retval["modelid"] = "HASS213"
retval["state"].update(
{
HUE_API_STATE_BRI: state[STATE_BRIGHTNESS],
HUE_API_STATE_COLORMODE: "hs",
HUE_API_STATE_HUE: state[STATE_HUE],
HUE_API_STATE_SAT: state[STATE_SATURATION],
HUE_API_STATE_EFFECT: "none",
}
)
elif (entity_features & SUPPORT_BRIGHTNESS) and (
entity_features & SUPPORT_COLOR_TEMP
):
# Color temperature light (Zigbee Device ID: 0x0220)
# Supports groups, scenes, on/off, dimming, and setting of a color temperature
retval["type"] = "Color temperature light"
retval["modelid"] = "HASS312"
retval["state"].update(
{
HUE_API_STATE_COLORMODE: "ct",
HUE_API_STATE_CT: state[STATE_COLOR_TEMP],
HUE_API_STATE_BRI: state[STATE_BRIGHTNESS],
}
)
elif entity_features & (
SUPPORT_BRIGHTNESS
| SUPPORT_SET_POSITION
| SUPPORT_SET_SPEED
| SUPPORT_VOLUME_SET
| SUPPORT_TARGET_TEMPERATURE
):
# Dimmable light (Zigbee Device ID: 0x0100)
# Supports groups, scenes, on/off and dimming
retval["type"] = "Dimmable light"
retval["modelid"] = "HASS123"
retval["state"].update({HUE_API_STATE_BRI: state[STATE_BRIGHTNESS]})
elif not config.lights_all_dimmable:
# On/Off light (ZigBee Device ID: 0x0000)
# Supports groups, scenes and on/off control
retval["type"] = "On/Off light"
retval["productname"] = "On/Off light"
retval["modelid"] = "HASS321"
else:
# Dimmable light (Zigbee Device ID: 0x0100)
# Supports groups, scenes, on/off and dimming
# Reports fixed brightness for compatibility with Alexa.
retval["type"] = "Dimmable light"
retval["modelid"] = "HASS123"
retval["state"].update({HUE_API_STATE_BRI: HUE_API_STATE_BRI_MAX})
return retval | [
"def",
"entity_to_json",
"(",
"config",
",",
"entity",
")",
":",
"entity_features",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_SUPPORTED_FEATURES",
",",
"0",
")",
"unique_id",
"=",
"hashlib",
".",
"md5",
"(",
"entity",
".",
"entity_id",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"unique_id",
"=",
"f\"00:{unique_id[0:2]}:{unique_id[2:4]}:{unique_id[4:6]}:{unique_id[6:8]}:{unique_id[8:10]}:{unique_id[10:12]}:{unique_id[12:14]}-{unique_id[14:16]}\"",
"state",
"=",
"get_entity_state",
"(",
"config",
",",
"entity",
")",
"retval",
"=",
"{",
"\"state\"",
":",
"{",
"HUE_API_STATE_ON",
":",
"state",
"[",
"STATE_ON",
"]",
",",
"\"reachable\"",
":",
"entity",
".",
"state",
"!=",
"STATE_UNAVAILABLE",
",",
"\"mode\"",
":",
"\"homeautomation\"",
",",
"}",
",",
"\"name\"",
":",
"config",
".",
"get_entity_name",
"(",
"entity",
")",
",",
"\"uniqueid\"",
":",
"unique_id",
",",
"\"manufacturername\"",
":",
"\"Home Assistant\"",
",",
"\"swversion\"",
":",
"\"123\"",
",",
"}",
"if",
"(",
"(",
"entity_features",
"&",
"SUPPORT_BRIGHTNESS",
")",
"and",
"(",
"entity_features",
"&",
"SUPPORT_COLOR",
")",
"and",
"(",
"entity_features",
"&",
"SUPPORT_COLOR_TEMP",
")",
")",
":",
"# Extended Color light (Zigbee Device ID: 0x0210)",
"# Same as Color light, but which supports additional setting of color temperature",
"retval",
"[",
"\"type\"",
"]",
"=",
"\"Extended color light\"",
"retval",
"[",
"\"modelid\"",
"]",
"=",
"\"HASS231\"",
"retval",
"[",
"\"state\"",
"]",
".",
"update",
"(",
"{",
"HUE_API_STATE_BRI",
":",
"state",
"[",
"STATE_BRIGHTNESS",
"]",
",",
"HUE_API_STATE_HUE",
":",
"state",
"[",
"STATE_HUE",
"]",
",",
"HUE_API_STATE_SAT",
":",
"state",
"[",
"STATE_SATURATION",
"]",
",",
"HUE_API_STATE_CT",
":",
"state",
"[",
"STATE_COLOR_TEMP",
"]",
",",
"HUE_API_STATE_EFFECT",
":",
"\"none\"",
",",
"}",
")",
"if",
"state",
"[",
"STATE_HUE",
"]",
">",
"0",
"or",
"state",
"[",
"STATE_SATURATION",
"]",
">",
"0",
":",
"retval",
"[",
"\"state\"",
"]",
"[",
"HUE_API_STATE_COLORMODE",
"]",
"=",
"\"hs\"",
"else",
":",
"retval",
"[",
"\"state\"",
"]",
"[",
"HUE_API_STATE_COLORMODE",
"]",
"=",
"\"ct\"",
"elif",
"(",
"entity_features",
"&",
"SUPPORT_BRIGHTNESS",
")",
"and",
"(",
"entity_features",
"&",
"SUPPORT_COLOR",
")",
":",
"# Color light (Zigbee Device ID: 0x0200)",
"# Supports on/off, dimming and color control (hue/saturation, enhanced hue, color loop and XY)",
"retval",
"[",
"\"type\"",
"]",
"=",
"\"Color light\"",
"retval",
"[",
"\"modelid\"",
"]",
"=",
"\"HASS213\"",
"retval",
"[",
"\"state\"",
"]",
".",
"update",
"(",
"{",
"HUE_API_STATE_BRI",
":",
"state",
"[",
"STATE_BRIGHTNESS",
"]",
",",
"HUE_API_STATE_COLORMODE",
":",
"\"hs\"",
",",
"HUE_API_STATE_HUE",
":",
"state",
"[",
"STATE_HUE",
"]",
",",
"HUE_API_STATE_SAT",
":",
"state",
"[",
"STATE_SATURATION",
"]",
",",
"HUE_API_STATE_EFFECT",
":",
"\"none\"",
",",
"}",
")",
"elif",
"(",
"entity_features",
"&",
"SUPPORT_BRIGHTNESS",
")",
"and",
"(",
"entity_features",
"&",
"SUPPORT_COLOR_TEMP",
")",
":",
"# Color temperature light (Zigbee Device ID: 0x0220)",
"# Supports groups, scenes, on/off, dimming, and setting of a color temperature",
"retval",
"[",
"\"type\"",
"]",
"=",
"\"Color temperature light\"",
"retval",
"[",
"\"modelid\"",
"]",
"=",
"\"HASS312\"",
"retval",
"[",
"\"state\"",
"]",
".",
"update",
"(",
"{",
"HUE_API_STATE_COLORMODE",
":",
"\"ct\"",
",",
"HUE_API_STATE_CT",
":",
"state",
"[",
"STATE_COLOR_TEMP",
"]",
",",
"HUE_API_STATE_BRI",
":",
"state",
"[",
"STATE_BRIGHTNESS",
"]",
",",
"}",
")",
"elif",
"entity_features",
"&",
"(",
"SUPPORT_BRIGHTNESS",
"|",
"SUPPORT_SET_POSITION",
"|",
"SUPPORT_SET_SPEED",
"|",
"SUPPORT_VOLUME_SET",
"|",
"SUPPORT_TARGET_TEMPERATURE",
")",
":",
"# Dimmable light (Zigbee Device ID: 0x0100)",
"# Supports groups, scenes, on/off and dimming",
"retval",
"[",
"\"type\"",
"]",
"=",
"\"Dimmable light\"",
"retval",
"[",
"\"modelid\"",
"]",
"=",
"\"HASS123\"",
"retval",
"[",
"\"state\"",
"]",
".",
"update",
"(",
"{",
"HUE_API_STATE_BRI",
":",
"state",
"[",
"STATE_BRIGHTNESS",
"]",
"}",
")",
"elif",
"not",
"config",
".",
"lights_all_dimmable",
":",
"# On/Off light (ZigBee Device ID: 0x0000)",
"# Supports groups, scenes and on/off control",
"retval",
"[",
"\"type\"",
"]",
"=",
"\"On/Off light\"",
"retval",
"[",
"\"productname\"",
"]",
"=",
"\"On/Off light\"",
"retval",
"[",
"\"modelid\"",
"]",
"=",
"\"HASS321\"",
"else",
":",
"# Dimmable light (Zigbee Device ID: 0x0100)",
"# Supports groups, scenes, on/off and dimming",
"# Reports fixed brightness for compatibility with Alexa.",
"retval",
"[",
"\"type\"",
"]",
"=",
"\"Dimmable light\"",
"retval",
"[",
"\"modelid\"",
"]",
"=",
"\"HASS123\"",
"retval",
"[",
"\"state\"",
"]",
".",
"update",
"(",
"{",
"HUE_API_STATE_BRI",
":",
"HUE_API_STATE_BRI_MAX",
"}",
")",
"return",
"retval"
] | [
694,
0
] | [
790,
17
] | python | en | ['en', 'ht', 'en'] | True |
create_hue_success_response | (entity_number, attr, value) | Create a success response for an attribute set on a light. | Create a success response for an attribute set on a light. | def create_hue_success_response(entity_number, attr, value):
"""Create a success response for an attribute set on a light."""
success_key = f"/lights/{entity_number}/state/{attr}"
return {"success": {success_key: value}} | [
"def",
"create_hue_success_response",
"(",
"entity_number",
",",
"attr",
",",
"value",
")",
":",
"success_key",
"=",
"f\"/lights/{entity_number}/state/{attr}\"",
"return",
"{",
"\"success\"",
":",
"{",
"success_key",
":",
"value",
"}",
"}"
] | [
793,
0
] | [
796,
44
] | python | en | ['en', 'en', 'en'] | True |
create_config_model | (config, request) | Create a config resource. | Create a config resource. | def create_config_model(config, request):
"""Create a config resource."""
return {
"mac": "00:00:00:00:00:00",
"swversion": "01003542",
"apiversion": "1.17.0",
"whitelist": {HUE_API_USERNAME: {"name": "HASS BRIDGE"}},
"ipaddress": f"{config.advertise_ip}:{config.advertise_port}",
"linkbutton": True,
} | [
"def",
"create_config_model",
"(",
"config",
",",
"request",
")",
":",
"return",
"{",
"\"mac\"",
":",
"\"00:00:00:00:00:00\"",
",",
"\"swversion\"",
":",
"\"01003542\"",
",",
"\"apiversion\"",
":",
"\"1.17.0\"",
",",
"\"whitelist\"",
":",
"{",
"HUE_API_USERNAME",
":",
"{",
"\"name\"",
":",
"\"HASS BRIDGE\"",
"}",
"}",
",",
"\"ipaddress\"",
":",
"f\"{config.advertise_ip}:{config.advertise_port}\"",
",",
"\"linkbutton\"",
":",
"True",
",",
"}"
] | [
799,
0
] | [
808,
5
] | python | en | ['en', 'en', 'en'] | True |
create_list_of_entities | (config, request) | Create a list of all entities. | Create a list of all entities. | def create_list_of_entities(config, request):
"""Create a list of all entities."""
hass = request.app["hass"]
json_response = {}
for entity in config.filter_exposed_entities(hass.states.async_all()):
number = config.entity_id_to_number(entity.entity_id)
json_response[number] = entity_to_json(config, entity)
return json_response | [
"def",
"create_list_of_entities",
"(",
"config",
",",
"request",
")",
":",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"json_response",
"=",
"{",
"}",
"for",
"entity",
"in",
"config",
".",
"filter_exposed_entities",
"(",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
")",
":",
"number",
"=",
"config",
".",
"entity_id_to_number",
"(",
"entity",
".",
"entity_id",
")",
"json_response",
"[",
"number",
"]",
"=",
"entity_to_json",
"(",
"config",
",",
"entity",
")",
"return",
"json_response"
] | [
811,
0
] | [
820,
24
] | python | en | ['en', 'en', 'en'] | True |
hue_brightness_to_hass | (value) | Convert hue brightness 1..254 to hass format 0..255. | Convert hue brightness 1..254 to hass format 0..255. | def hue_brightness_to_hass(value):
"""Convert hue brightness 1..254 to hass format 0..255."""
return min(255, round((value / HUE_API_STATE_BRI_MAX) * 255)) | [
"def",
"hue_brightness_to_hass",
"(",
"value",
")",
":",
"return",
"min",
"(",
"255",
",",
"round",
"(",
"(",
"value",
"/",
"HUE_API_STATE_BRI_MAX",
")",
"*",
"255",
")",
")"
] | [
823,
0
] | [
825,
65
] | python | en | ['en', 'en', 'en'] | True |
hass_to_hue_brightness | (value) | Convert hass brightness 0..255 to hue 1..254 scale. | Convert hass brightness 0..255 to hue 1..254 scale. | def hass_to_hue_brightness(value):
"""Convert hass brightness 0..255 to hue 1..254 scale."""
return max(1, round((value / 255) * HUE_API_STATE_BRI_MAX)) | [
"def",
"hass_to_hue_brightness",
"(",
"value",
")",
":",
"return",
"max",
"(",
"1",
",",
"round",
"(",
"(",
"value",
"/",
"255",
")",
"*",
"HUE_API_STATE_BRI_MAX",
")",
")"
] | [
828,
0
] | [
830,
63
] | python | en | ['en', 'en', 'en'] | True |
wait_for_state_change_or_timeout | (hass, entity_id, timeout) | Wait for an entity to change state. | Wait for an entity to change state. | async def wait_for_state_change_or_timeout(hass, entity_id, timeout):
"""Wait for an entity to change state."""
ev = asyncio.Event()
@core.callback
def _async_event_changed(_):
ev.set()
unsub = async_track_state_change_event(hass, [entity_id], _async_event_changed)
try:
await asyncio.wait_for(ev.wait(), timeout=STATE_CHANGE_WAIT_TIMEOUT)
except asyncio.TimeoutError:
pass
finally:
unsub() | [
"async",
"def",
"wait_for_state_change_or_timeout",
"(",
"hass",
",",
"entity_id",
",",
"timeout",
")",
":",
"ev",
"=",
"asyncio",
".",
"Event",
"(",
")",
"@",
"core",
".",
"callback",
"def",
"_async_event_changed",
"(",
"_",
")",
":",
"ev",
".",
"set",
"(",
")",
"unsub",
"=",
"async_track_state_change_event",
"(",
"hass",
",",
"[",
"entity_id",
"]",
",",
"_async_event_changed",
")",
"try",
":",
"await",
"asyncio",
".",
"wait_for",
"(",
"ev",
".",
"wait",
"(",
")",
",",
"timeout",
"=",
"STATE_CHANGE_WAIT_TIMEOUT",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"pass",
"finally",
":",
"unsub",
"(",
")"
] | [
833,
0
] | [
848,
15
] | python | en | ['en', 'en', 'en'] | True |
HueUnauthorizedUser.get | (self, request) | Handle a GET request. | Handle a GET request. | async def get(self, request):
"""Handle a GET request."""
return self.json(UNAUTHORIZED_USER) | [
"async",
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"json",
"(",
"UNAUTHORIZED_USER",
")"
] | [
118,
4
] | [
120,
43
] | python | en | ['en', 'en', 'en'] | True |
HueUsernameView.post | (self, request) | Handle a POST request. | Handle a POST request. | async def post(self, request):
"""Handle a POST request."""
if not is_local(ip_address(request.remote)):
return self.json_message("Only local IPs allowed", HTTP_UNAUTHORIZED)
try:
data = await request.json()
except ValueError:
return self.json_message("Invalid JSON", HTTP_BAD_REQUEST)
if "devicetype" not in data:
return self.json_message("devicetype not specified", HTTP_BAD_REQUEST)
return self.json([{"success": {"username": HUE_API_USERNAME}}]) | [
"async",
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"try",
":",
"data",
"=",
"await",
"request",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Invalid JSON\"",
",",
"HTTP_BAD_REQUEST",
")",
"if",
"\"devicetype\"",
"not",
"in",
"data",
":",
"return",
"self",
".",
"json_message",
"(",
"\"devicetype not specified\"",
",",
"HTTP_BAD_REQUEST",
")",
"return",
"self",
".",
"json",
"(",
"[",
"{",
"\"success\"",
":",
"{",
"\"username\"",
":",
"HUE_API_USERNAME",
"}",
"}",
"]",
")"
] | [
131,
4
] | [
144,
71
] | python | en | ['en', 'en', 'en'] | True |
HueAllGroupsStateView.__init__ | (self, config) | Initialize the instance of the view. | Initialize the instance of the view. | def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config"
] | [
154,
4
] | [
156,
28
] | python | en | ['en', 'en', 'en'] | True |
HueAllGroupsStateView.get | (self, request, username) | Process a request to make the Brilliant Lightpad work. | Process a request to make the Brilliant Lightpad work. | def get(self, request, username):
"""Process a request to make the Brilliant Lightpad work."""
if not is_local(ip_address(request.remote)):
return self.json_message("Only local IPs allowed", HTTP_UNAUTHORIZED)
return self.json({}) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"username",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"return",
"self",
".",
"json",
"(",
"{",
"}",
")"
] | [
159,
4
] | [
164,
28
] | python | en | ['en', 'en', 'en'] | True |
HueGroupView.__init__ | (self, config) | Initialize the instance of the view. | Initialize the instance of the view. | def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config"
] | [
174,
4
] | [
176,
28
] | python | en | ['en', 'en', 'en'] | True |
HueGroupView.put | (self, request, username) | Process a request to make the Logitech Pop working. | Process a request to make the Logitech Pop working. | def put(self, request, username):
"""Process a request to make the Logitech Pop working."""
if not is_local(ip_address(request.remote)):
return self.json_message("Only local IPs allowed", HTTP_UNAUTHORIZED)
return self.json(
[
{
"error": {
"address": "/groups/0/action/scene",
"type": 7,
"description": "invalid value, dummy for parameter, scene",
}
}
]
) | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"username",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"return",
"self",
".",
"json",
"(",
"[",
"{",
"\"error\"",
":",
"{",
"\"address\"",
":",
"\"/groups/0/action/scene\"",
",",
"\"type\"",
":",
"7",
",",
"\"description\"",
":",
"\"invalid value, dummy for parameter, scene\"",
",",
"}",
"}",
"]",
")"
] | [
179,
4
] | [
194,
9
] | python | en | ['en', 'en', 'en'] | True |
HueAllLightsStateView.__init__ | (self, config) | Initialize the instance of the view. | Initialize the instance of the view. | def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config"
] | [
204,
4
] | [
206,
28
] | python | en | ['en', 'en', 'en'] | True |
HueAllLightsStateView.get | (self, request, username) | Process a request to get the list of available lights. | Process a request to get the list of available lights. | def get(self, request, username):
"""Process a request to get the list of available lights."""
if not is_local(ip_address(request.remote)):
return self.json_message("Only local IPs allowed", HTTP_UNAUTHORIZED)
return self.json(create_list_of_entities(self.config, request)) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"username",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"return",
"self",
".",
"json",
"(",
"create_list_of_entities",
"(",
"self",
".",
"config",
",",
"request",
")",
")"
] | [
209,
4
] | [
214,
71
] | python | en | ['en', 'en', 'en'] | True |
HueFullStateView.__init__ | (self, config) | Initialize the instance of the view. | Initialize the instance of the view. | def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config"
] | [
224,
4
] | [
226,
28
] | python | en | ['en', 'en', 'en'] | True |
HueFullStateView.get | (self, request, username) | Process a request to get the list of available lights. | Process a request to get the list of available lights. | def get(self, request, username):
"""Process a request to get the list of available lights."""
if not is_local(ip_address(request.remote)):
return self.json_message("only local IPs allowed", HTTP_UNAUTHORIZED)
if username != HUE_API_USERNAME:
return self.json(UNAUTHORIZED_USER)
json_response = {
"lights": create_list_of_entities(self.config, request),
"config": create_config_model(self.config, request),
}
return self.json(json_response) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"username",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"if",
"username",
"!=",
"HUE_API_USERNAME",
":",
"return",
"self",
".",
"json",
"(",
"UNAUTHORIZED_USER",
")",
"json_response",
"=",
"{",
"\"lights\"",
":",
"create_list_of_entities",
"(",
"self",
".",
"config",
",",
"request",
")",
",",
"\"config\"",
":",
"create_config_model",
"(",
"self",
".",
"config",
",",
"request",
")",
",",
"}",
"return",
"self",
".",
"json",
"(",
"json_response",
")"
] | [
229,
4
] | [
241,
39
] | python | en | ['en', 'en', 'en'] | True |
HueConfigView.__init__ | (self, config) | Initialize the instance of the view. | Initialize the instance of the view. | def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config"
] | [
252,
4
] | [
254,
28
] | python | en | ['en', 'en', 'en'] | True |
HueConfigView.get | (self, request, username="") | Process a request to get the configuration. | Process a request to get the configuration. | def get(self, request, username=""):
"""Process a request to get the configuration."""
if not is_local(ip_address(request.remote)):
return self.json_message("only local IPs allowed", HTTP_UNAUTHORIZED)
json_response = create_config_model(self.config, request)
return self.json(json_response) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"username",
"=",
"\"\"",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"json_response",
"=",
"create_config_model",
"(",
"self",
".",
"config",
",",
"request",
")",
"return",
"self",
".",
"json",
"(",
"json_response",
")"
] | [
257,
4
] | [
264,
39
] | python | en | ['en', 'en', 'en'] | True |
HueOneLightStateView.__init__ | (self, config) | Initialize the instance of the view. | Initialize the instance of the view. | def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config"
] | [
274,
4
] | [
276,
28
] | python | en | ['en', 'en', 'en'] | True |
HueOneLightStateView.get | (self, request, username, entity_id) | Process a request to get the state of an individual light. | Process a request to get the state of an individual light. | def get(self, request, username, entity_id):
"""Process a request to get the state of an individual light."""
if not is_local(ip_address(request.remote)):
return self.json_message("Only local IPs allowed", HTTP_UNAUTHORIZED)
hass = request.app["hass"]
hass_entity_id = self.config.number_to_entity_id(entity_id)
if hass_entity_id is None:
_LOGGER.error(
"Unknown entity number: %s not found in emulated_hue_ids.json",
entity_id,
)
return self.json_message("Entity not found", HTTP_NOT_FOUND)
entity = hass.states.get(hass_entity_id)
if entity is None:
_LOGGER.error("Entity not found: %s", hass_entity_id)
return self.json_message("Entity not found", HTTP_NOT_FOUND)
if not self.config.is_entity_exposed(entity):
_LOGGER.error("Entity not exposed: %s", entity_id)
return self.json_message("Entity not exposed", HTTP_UNAUTHORIZED)
json_response = entity_to_json(self.config, entity)
return self.json(json_response) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"username",
",",
"entity_id",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"hass_entity_id",
"=",
"self",
".",
"config",
".",
"number_to_entity_id",
"(",
"entity_id",
")",
"if",
"hass_entity_id",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unknown entity number: %s not found in emulated_hue_ids.json\"",
",",
"entity_id",
",",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Entity not found\"",
",",
"HTTP_NOT_FOUND",
")",
"entity",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"hass_entity_id",
")",
"if",
"entity",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Entity not found: %s\"",
",",
"hass_entity_id",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Entity not found\"",
",",
"HTTP_NOT_FOUND",
")",
"if",
"not",
"self",
".",
"config",
".",
"is_entity_exposed",
"(",
"entity",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Entity not exposed: %s\"",
",",
"entity_id",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Entity not exposed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"json_response",
"=",
"entity_to_json",
"(",
"self",
".",
"config",
",",
"entity",
")",
"return",
"self",
".",
"json",
"(",
"json_response",
")"
] | [
279,
4
] | [
306,
39
] | python | en | ['en', 'en', 'en'] | True |
HueOneLightChangeView.__init__ | (self, config) | Initialize the instance of the view. | Initialize the instance of the view. | def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config"
] | [
316,
4
] | [
318,
28
] | python | en | ['en', 'en', 'en'] | True |
HueOneLightChangeView.put | (self, request, username, entity_number) | Process a request to set the state of an individual light. | Process a request to set the state of an individual light. | async def put(self, request, username, entity_number):
"""Process a request to set the state of an individual light."""
if not is_local(ip_address(request.remote)):
return self.json_message("Only local IPs allowed", HTTP_UNAUTHORIZED)
config = self.config
hass = request.app["hass"]
entity_id = config.number_to_entity_id(entity_number)
if entity_id is None:
_LOGGER.error("Unknown entity number: %s", entity_number)
return self.json_message("Entity not found", HTTP_NOT_FOUND)
entity = hass.states.get(entity_id)
if entity is None:
_LOGGER.error("Entity not found: %s", entity_id)
return self.json_message("Entity not found", HTTP_NOT_FOUND)
if not config.is_entity_exposed(entity):
_LOGGER.error("Entity not exposed: %s", entity_id)
return self.json_message("Entity not exposed", HTTP_UNAUTHORIZED)
try:
request_json = await request.json()
except ValueError:
_LOGGER.error("Received invalid json")
return self.json_message("Invalid JSON", HTTP_BAD_REQUEST)
# Get the entity's supported features
entity_features = entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
# Parse the request
parsed = {
STATE_ON: False,
STATE_BRIGHTNESS: None,
STATE_HUE: None,
STATE_SATURATION: None,
STATE_COLOR_TEMP: None,
}
if HUE_API_STATE_ON in request_json:
if not isinstance(request_json[HUE_API_STATE_ON], bool):
_LOGGER.error("Unable to parse data: %s", request_json)
return self.json_message("Bad request", HTTP_BAD_REQUEST)
parsed[STATE_ON] = request_json[HUE_API_STATE_ON]
else:
parsed[STATE_ON] = entity.state != STATE_OFF
for (key, attr) in (
(HUE_API_STATE_BRI, STATE_BRIGHTNESS),
(HUE_API_STATE_HUE, STATE_HUE),
(HUE_API_STATE_SAT, STATE_SATURATION),
(HUE_API_STATE_CT, STATE_COLOR_TEMP),
):
if key in request_json:
try:
parsed[attr] = int(request_json[key])
except ValueError:
_LOGGER.error("Unable to parse data (2): %s", request_json)
return self.json_message("Bad request", HTTP_BAD_REQUEST)
if HUE_API_STATE_BRI in request_json:
if entity.domain == light.DOMAIN:
if entity_features & SUPPORT_BRIGHTNESS:
parsed[STATE_ON] = parsed[STATE_BRIGHTNESS] > 0
else:
parsed[STATE_BRIGHTNESS] = None
elif entity.domain == scene.DOMAIN:
parsed[STATE_BRIGHTNESS] = None
parsed[STATE_ON] = True
elif entity.domain in [
script.DOMAIN,
media_player.DOMAIN,
fan.DOMAIN,
cover.DOMAIN,
climate.DOMAIN,
humidifier.DOMAIN,
]:
# Convert 0-254 to 0-100
level = (parsed[STATE_BRIGHTNESS] / HUE_API_STATE_BRI_MAX) * 100
parsed[STATE_BRIGHTNESS] = round(level)
parsed[STATE_ON] = True
# Choose general HA domain
domain = core.DOMAIN
# Entity needs separate call to turn on
turn_on_needed = False
# Convert the resulting "on" status into the service we need to call
service = SERVICE_TURN_ON if parsed[STATE_ON] else SERVICE_TURN_OFF
# Construct what we need to send to the service
data = {ATTR_ENTITY_ID: entity_id}
# If the requested entity is a light, set the brightness, hue,
# saturation and color temp
if entity.domain == light.DOMAIN:
if parsed[STATE_ON]:
if entity_features & SUPPORT_BRIGHTNESS:
if parsed[STATE_BRIGHTNESS] is not None:
data[ATTR_BRIGHTNESS] = hue_brightness_to_hass(
parsed[STATE_BRIGHTNESS]
)
if entity_features & SUPPORT_COLOR:
if any((parsed[STATE_HUE], parsed[STATE_SATURATION])):
if parsed[STATE_HUE] is not None:
hue = parsed[STATE_HUE]
else:
hue = 0
if parsed[STATE_SATURATION] is not None:
sat = parsed[STATE_SATURATION]
else:
sat = 0
# Convert hs values to hass hs values
hue = int((hue / HUE_API_STATE_HUE_MAX) * 360)
sat = int((sat / HUE_API_STATE_SAT_MAX) * 100)
data[ATTR_HS_COLOR] = (hue, sat)
if entity_features & SUPPORT_COLOR_TEMP:
if parsed[STATE_COLOR_TEMP] is not None:
data[ATTR_COLOR_TEMP] = parsed[STATE_COLOR_TEMP]
# If the requested entity is a script, add some variables
elif entity.domain == script.DOMAIN:
data["variables"] = {
"requested_state": STATE_ON if parsed[STATE_ON] else STATE_OFF
}
if parsed[STATE_BRIGHTNESS] is not None:
data["variables"]["requested_level"] = parsed[STATE_BRIGHTNESS]
# If the requested entity is a climate, set the temperature
elif entity.domain == climate.DOMAIN:
# We don't support turning climate devices on or off,
# only setting the temperature
service = None
if entity_features & SUPPORT_TARGET_TEMPERATURE:
if parsed[STATE_BRIGHTNESS] is not None:
domain = entity.domain
service = SERVICE_SET_TEMPERATURE
data[ATTR_TEMPERATURE] = parsed[STATE_BRIGHTNESS]
# If the requested entity is a humidifier, set the humidity
elif entity.domain == humidifier.DOMAIN:
if parsed[STATE_BRIGHTNESS] is not None:
turn_on_needed = True
domain = entity.domain
service = SERVICE_SET_HUMIDITY
data[ATTR_HUMIDITY] = parsed[STATE_BRIGHTNESS]
# If the requested entity is a media player, convert to volume
elif entity.domain == media_player.DOMAIN:
if entity_features & SUPPORT_VOLUME_SET:
if parsed[STATE_BRIGHTNESS] is not None:
turn_on_needed = True
domain = entity.domain
service = SERVICE_VOLUME_SET
# Convert 0-100 to 0.0-1.0
data[ATTR_MEDIA_VOLUME_LEVEL] = parsed[STATE_BRIGHTNESS] / 100.0
# If the requested entity is a cover, convert to open_cover/close_cover
elif entity.domain == cover.DOMAIN:
domain = entity.domain
if service == SERVICE_TURN_ON:
service = SERVICE_OPEN_COVER
else:
service = SERVICE_CLOSE_COVER
if entity_features & SUPPORT_SET_POSITION:
if parsed[STATE_BRIGHTNESS] is not None:
domain = entity.domain
service = SERVICE_SET_COVER_POSITION
data[ATTR_POSITION] = parsed[STATE_BRIGHTNESS]
# If the requested entity is a fan, convert to speed
elif entity.domain == fan.DOMAIN:
if entity_features & SUPPORT_SET_SPEED:
if parsed[STATE_BRIGHTNESS] is not None:
domain = entity.domain
# Convert 0-100 to a fan speed
brightness = parsed[STATE_BRIGHTNESS]
if brightness == 0:
data[ATTR_SPEED] = SPEED_OFF
elif 0 < brightness <= 33.3:
data[ATTR_SPEED] = SPEED_LOW
elif 33.3 < brightness <= 66.6:
data[ATTR_SPEED] = SPEED_MEDIUM
elif 66.6 < brightness <= 100:
data[ATTR_SPEED] = SPEED_HIGH
# Map the off command to on
if entity.domain in config.off_maps_to_on_domains:
service = SERVICE_TURN_ON
# Separate call to turn on needed
if turn_on_needed:
hass.async_create_task(
hass.services.async_call(
core.DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
)
if service is not None:
state_will_change = parsed[STATE_ON] != (entity.state != STATE_OFF)
hass.async_create_task(
hass.services.async_call(domain, service, data, blocking=True)
)
if state_will_change:
# Wait for the state to change.
await wait_for_state_change_or_timeout(
hass, entity_id, STATE_CACHED_TIMEOUT
)
# Create success responses for all received keys
json_response = [
create_hue_success_response(
entity_number, HUE_API_STATE_ON, parsed[STATE_ON]
)
]
for (key, val) in (
(STATE_BRIGHTNESS, HUE_API_STATE_BRI),
(STATE_HUE, HUE_API_STATE_HUE),
(STATE_SATURATION, HUE_API_STATE_SAT),
(STATE_COLOR_TEMP, HUE_API_STATE_CT),
):
if parsed[key] is not None:
json_response.append(
create_hue_success_response(entity_number, val, parsed[key])
)
if entity.domain in config.off_maps_to_on_domains:
# Caching is required because things like scripts and scenes won't
# report as "off" to Alexa if an "off" command is received, because
# they'll map to "on". Thus, instead of reporting its actual
# status, we report what Alexa will want to see, which is the same
# as the actual requested command.
config.cached_states[entity_id] = [parsed, None]
else:
config.cached_states[entity_id] = [parsed, time.time()]
return self.json(json_response) | [
"async",
"def",
"put",
"(",
"self",
",",
"request",
",",
"username",
",",
"entity_number",
")",
":",
"if",
"not",
"is_local",
"(",
"ip_address",
"(",
"request",
".",
"remote",
")",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Only local IPs allowed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"config",
"=",
"self",
".",
"config",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"entity_id",
"=",
"config",
".",
"number_to_entity_id",
"(",
"entity_number",
")",
"if",
"entity_id",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unknown entity number: %s\"",
",",
"entity_number",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Entity not found\"",
",",
"HTTP_NOT_FOUND",
")",
"entity",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"if",
"entity",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Entity not found: %s\"",
",",
"entity_id",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Entity not found\"",
",",
"HTTP_NOT_FOUND",
")",
"if",
"not",
"config",
".",
"is_entity_exposed",
"(",
"entity",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Entity not exposed: %s\"",
",",
"entity_id",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Entity not exposed\"",
",",
"HTTP_UNAUTHORIZED",
")",
"try",
":",
"request_json",
"=",
"await",
"request",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Received invalid json\"",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Invalid JSON\"",
",",
"HTTP_BAD_REQUEST",
")",
"# Get the entity's supported features",
"entity_features",
"=",
"entity",
".",
"attributes",
".",
"get",
"(",
"ATTR_SUPPORTED_FEATURES",
",",
"0",
")",
"# Parse the request",
"parsed",
"=",
"{",
"STATE_ON",
":",
"False",
",",
"STATE_BRIGHTNESS",
":",
"None",
",",
"STATE_HUE",
":",
"None",
",",
"STATE_SATURATION",
":",
"None",
",",
"STATE_COLOR_TEMP",
":",
"None",
",",
"}",
"if",
"HUE_API_STATE_ON",
"in",
"request_json",
":",
"if",
"not",
"isinstance",
"(",
"request_json",
"[",
"HUE_API_STATE_ON",
"]",
",",
"bool",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to parse data: %s\"",
",",
"request_json",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Bad request\"",
",",
"HTTP_BAD_REQUEST",
")",
"parsed",
"[",
"STATE_ON",
"]",
"=",
"request_json",
"[",
"HUE_API_STATE_ON",
"]",
"else",
":",
"parsed",
"[",
"STATE_ON",
"]",
"=",
"entity",
".",
"state",
"!=",
"STATE_OFF",
"for",
"(",
"key",
",",
"attr",
")",
"in",
"(",
"(",
"HUE_API_STATE_BRI",
",",
"STATE_BRIGHTNESS",
")",
",",
"(",
"HUE_API_STATE_HUE",
",",
"STATE_HUE",
")",
",",
"(",
"HUE_API_STATE_SAT",
",",
"STATE_SATURATION",
")",
",",
"(",
"HUE_API_STATE_CT",
",",
"STATE_COLOR_TEMP",
")",
",",
")",
":",
"if",
"key",
"in",
"request_json",
":",
"try",
":",
"parsed",
"[",
"attr",
"]",
"=",
"int",
"(",
"request_json",
"[",
"key",
"]",
")",
"except",
"ValueError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to parse data (2): %s\"",
",",
"request_json",
")",
"return",
"self",
".",
"json_message",
"(",
"\"Bad request\"",
",",
"HTTP_BAD_REQUEST",
")",
"if",
"HUE_API_STATE_BRI",
"in",
"request_json",
":",
"if",
"entity",
".",
"domain",
"==",
"light",
".",
"DOMAIN",
":",
"if",
"entity_features",
"&",
"SUPPORT_BRIGHTNESS",
":",
"parsed",
"[",
"STATE_ON",
"]",
"=",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
">",
"0",
"else",
":",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"None",
"elif",
"entity",
".",
"domain",
"==",
"scene",
".",
"DOMAIN",
":",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"None",
"parsed",
"[",
"STATE_ON",
"]",
"=",
"True",
"elif",
"entity",
".",
"domain",
"in",
"[",
"script",
".",
"DOMAIN",
",",
"media_player",
".",
"DOMAIN",
",",
"fan",
".",
"DOMAIN",
",",
"cover",
".",
"DOMAIN",
",",
"climate",
".",
"DOMAIN",
",",
"humidifier",
".",
"DOMAIN",
",",
"]",
":",
"# Convert 0-254 to 0-100",
"level",
"=",
"(",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"/",
"HUE_API_STATE_BRI_MAX",
")",
"*",
"100",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"=",
"round",
"(",
"level",
")",
"parsed",
"[",
"STATE_ON",
"]",
"=",
"True",
"# Choose general HA domain",
"domain",
"=",
"core",
".",
"DOMAIN",
"# Entity needs separate call to turn on",
"turn_on_needed",
"=",
"False",
"# Convert the resulting \"on\" status into the service we need to call",
"service",
"=",
"SERVICE_TURN_ON",
"if",
"parsed",
"[",
"STATE_ON",
"]",
"else",
"SERVICE_TURN_OFF",
"# Construct what we need to send to the service",
"data",
"=",
"{",
"ATTR_ENTITY_ID",
":",
"entity_id",
"}",
"# If the requested entity is a light, set the brightness, hue,",
"# saturation and color temp",
"if",
"entity",
".",
"domain",
"==",
"light",
".",
"DOMAIN",
":",
"if",
"parsed",
"[",
"STATE_ON",
"]",
":",
"if",
"entity_features",
"&",
"SUPPORT_BRIGHTNESS",
":",
"if",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"not",
"None",
":",
"data",
"[",
"ATTR_BRIGHTNESS",
"]",
"=",
"hue_brightness_to_hass",
"(",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
")",
"if",
"entity_features",
"&",
"SUPPORT_COLOR",
":",
"if",
"any",
"(",
"(",
"parsed",
"[",
"STATE_HUE",
"]",
",",
"parsed",
"[",
"STATE_SATURATION",
"]",
")",
")",
":",
"if",
"parsed",
"[",
"STATE_HUE",
"]",
"is",
"not",
"None",
":",
"hue",
"=",
"parsed",
"[",
"STATE_HUE",
"]",
"else",
":",
"hue",
"=",
"0",
"if",
"parsed",
"[",
"STATE_SATURATION",
"]",
"is",
"not",
"None",
":",
"sat",
"=",
"parsed",
"[",
"STATE_SATURATION",
"]",
"else",
":",
"sat",
"=",
"0",
"# Convert hs values to hass hs values",
"hue",
"=",
"int",
"(",
"(",
"hue",
"/",
"HUE_API_STATE_HUE_MAX",
")",
"*",
"360",
")",
"sat",
"=",
"int",
"(",
"(",
"sat",
"/",
"HUE_API_STATE_SAT_MAX",
")",
"*",
"100",
")",
"data",
"[",
"ATTR_HS_COLOR",
"]",
"=",
"(",
"hue",
",",
"sat",
")",
"if",
"entity_features",
"&",
"SUPPORT_COLOR_TEMP",
":",
"if",
"parsed",
"[",
"STATE_COLOR_TEMP",
"]",
"is",
"not",
"None",
":",
"data",
"[",
"ATTR_COLOR_TEMP",
"]",
"=",
"parsed",
"[",
"STATE_COLOR_TEMP",
"]",
"# If the requested entity is a script, add some variables",
"elif",
"entity",
".",
"domain",
"==",
"script",
".",
"DOMAIN",
":",
"data",
"[",
"\"variables\"",
"]",
"=",
"{",
"\"requested_state\"",
":",
"STATE_ON",
"if",
"parsed",
"[",
"STATE_ON",
"]",
"else",
"STATE_OFF",
"}",
"if",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"not",
"None",
":",
"data",
"[",
"\"variables\"",
"]",
"[",
"\"requested_level\"",
"]",
"=",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"# If the requested entity is a climate, set the temperature",
"elif",
"entity",
".",
"domain",
"==",
"climate",
".",
"DOMAIN",
":",
"# We don't support turning climate devices on or off,",
"# only setting the temperature",
"service",
"=",
"None",
"if",
"entity_features",
"&",
"SUPPORT_TARGET_TEMPERATURE",
":",
"if",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"not",
"None",
":",
"domain",
"=",
"entity",
".",
"domain",
"service",
"=",
"SERVICE_SET_TEMPERATURE",
"data",
"[",
"ATTR_TEMPERATURE",
"]",
"=",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"# If the requested entity is a humidifier, set the humidity",
"elif",
"entity",
".",
"domain",
"==",
"humidifier",
".",
"DOMAIN",
":",
"if",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"not",
"None",
":",
"turn_on_needed",
"=",
"True",
"domain",
"=",
"entity",
".",
"domain",
"service",
"=",
"SERVICE_SET_HUMIDITY",
"data",
"[",
"ATTR_HUMIDITY",
"]",
"=",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"# If the requested entity is a media player, convert to volume",
"elif",
"entity",
".",
"domain",
"==",
"media_player",
".",
"DOMAIN",
":",
"if",
"entity_features",
"&",
"SUPPORT_VOLUME_SET",
":",
"if",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"not",
"None",
":",
"turn_on_needed",
"=",
"True",
"domain",
"=",
"entity",
".",
"domain",
"service",
"=",
"SERVICE_VOLUME_SET",
"# Convert 0-100 to 0.0-1.0",
"data",
"[",
"ATTR_MEDIA_VOLUME_LEVEL",
"]",
"=",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"/",
"100.0",
"# If the requested entity is a cover, convert to open_cover/close_cover",
"elif",
"entity",
".",
"domain",
"==",
"cover",
".",
"DOMAIN",
":",
"domain",
"=",
"entity",
".",
"domain",
"if",
"service",
"==",
"SERVICE_TURN_ON",
":",
"service",
"=",
"SERVICE_OPEN_COVER",
"else",
":",
"service",
"=",
"SERVICE_CLOSE_COVER",
"if",
"entity_features",
"&",
"SUPPORT_SET_POSITION",
":",
"if",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"not",
"None",
":",
"domain",
"=",
"entity",
".",
"domain",
"service",
"=",
"SERVICE_SET_COVER_POSITION",
"data",
"[",
"ATTR_POSITION",
"]",
"=",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"# If the requested entity is a fan, convert to speed",
"elif",
"entity",
".",
"domain",
"==",
"fan",
".",
"DOMAIN",
":",
"if",
"entity_features",
"&",
"SUPPORT_SET_SPEED",
":",
"if",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"is",
"not",
"None",
":",
"domain",
"=",
"entity",
".",
"domain",
"# Convert 0-100 to a fan speed",
"brightness",
"=",
"parsed",
"[",
"STATE_BRIGHTNESS",
"]",
"if",
"brightness",
"==",
"0",
":",
"data",
"[",
"ATTR_SPEED",
"]",
"=",
"SPEED_OFF",
"elif",
"0",
"<",
"brightness",
"<=",
"33.3",
":",
"data",
"[",
"ATTR_SPEED",
"]",
"=",
"SPEED_LOW",
"elif",
"33.3",
"<",
"brightness",
"<=",
"66.6",
":",
"data",
"[",
"ATTR_SPEED",
"]",
"=",
"SPEED_MEDIUM",
"elif",
"66.6",
"<",
"brightness",
"<=",
"100",
":",
"data",
"[",
"ATTR_SPEED",
"]",
"=",
"SPEED_HIGH",
"# Map the off command to on",
"if",
"entity",
".",
"domain",
"in",
"config",
".",
"off_maps_to_on_domains",
":",
"service",
"=",
"SERVICE_TURN_ON",
"# Separate call to turn on needed",
"if",
"turn_on_needed",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"services",
".",
"async_call",
"(",
"core",
".",
"DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
",",
")",
")",
"if",
"service",
"is",
"not",
"None",
":",
"state_will_change",
"=",
"parsed",
"[",
"STATE_ON",
"]",
"!=",
"(",
"entity",
".",
"state",
"!=",
"STATE_OFF",
")",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"services",
".",
"async_call",
"(",
"domain",
",",
"service",
",",
"data",
",",
"blocking",
"=",
"True",
")",
")",
"if",
"state_will_change",
":",
"# Wait for the state to change.",
"await",
"wait_for_state_change_or_timeout",
"(",
"hass",
",",
"entity_id",
",",
"STATE_CACHED_TIMEOUT",
")",
"# Create success responses for all received keys",
"json_response",
"=",
"[",
"create_hue_success_response",
"(",
"entity_number",
",",
"HUE_API_STATE_ON",
",",
"parsed",
"[",
"STATE_ON",
"]",
")",
"]",
"for",
"(",
"key",
",",
"val",
")",
"in",
"(",
"(",
"STATE_BRIGHTNESS",
",",
"HUE_API_STATE_BRI",
")",
",",
"(",
"STATE_HUE",
",",
"HUE_API_STATE_HUE",
")",
",",
"(",
"STATE_SATURATION",
",",
"HUE_API_STATE_SAT",
")",
",",
"(",
"STATE_COLOR_TEMP",
",",
"HUE_API_STATE_CT",
")",
",",
")",
":",
"if",
"parsed",
"[",
"key",
"]",
"is",
"not",
"None",
":",
"json_response",
".",
"append",
"(",
"create_hue_success_response",
"(",
"entity_number",
",",
"val",
",",
"parsed",
"[",
"key",
"]",
")",
")",
"if",
"entity",
".",
"domain",
"in",
"config",
".",
"off_maps_to_on_domains",
":",
"# Caching is required because things like scripts and scenes won't",
"# report as \"off\" to Alexa if an \"off\" command is received, because",
"# they'll map to \"on\". Thus, instead of reporting its actual",
"# status, we report what Alexa will want to see, which is the same",
"# as the actual requested command.",
"config",
".",
"cached_states",
"[",
"entity_id",
"]",
"=",
"[",
"parsed",
",",
"None",
"]",
"else",
":",
"config",
".",
"cached_states",
"[",
"entity_id",
"]",
"=",
"[",
"parsed",
",",
"time",
".",
"time",
"(",
")",
"]",
"return",
"self",
".",
"json",
"(",
"json_response",
")"
] | [
320,
4
] | [
575,
39
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Set up the OpenUV component. | Set up the OpenUV component. | async def async_setup(hass, config):
"""Set up the OpenUV component."""
hass.data[DOMAIN] = {DATA_OPENUV_CLIENT: {}, DATA_OPENUV_LISTENER: {}}
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"DATA_OPENUV_CLIENT",
":",
"{",
"}",
",",
"DATA_OPENUV_LISTENER",
":",
"{",
"}",
"}",
"return",
"True"
] | [
57,
0
] | [
60,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry) | Set up OpenUV as config entry. | Set up OpenUV as config entry. | async def async_setup_entry(hass, config_entry):
"""Set up OpenUV as config entry."""
_verify_domain_control = verify_domain_control(hass, DOMAIN)
try:
websession = aiohttp_client.async_get_clientsession(hass)
openuv = OpenUV(
Client(
config_entry.data[CONF_API_KEY],
config_entry.data.get(CONF_LATITUDE, hass.config.latitude),
config_entry.data.get(CONF_LONGITUDE, hass.config.longitude),
websession,
altitude=config_entry.data.get(CONF_ELEVATION, hass.config.elevation),
)
)
await openuv.async_update()
hass.data[DOMAIN][DATA_OPENUV_CLIENT][config_entry.entry_id] = openuv
except OpenUvError as err:
_LOGGER.error("Config entry failed: %s", err)
raise ConfigEntryNotReady from err
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, component)
)
@_verify_domain_control
async def update_data(service):
"""Refresh all OpenUV data."""
_LOGGER.debug("Refreshing all OpenUV data")
await openuv.async_update()
async_dispatcher_send(hass, TOPIC_UPDATE)
@_verify_domain_control
async def update_uv_index_data(service):
"""Refresh OpenUV UV index data."""
_LOGGER.debug("Refreshing OpenUV UV index data")
await openuv.async_update_uv_index_data()
async_dispatcher_send(hass, TOPIC_UPDATE)
@_verify_domain_control
async def update_protection_data(service):
"""Refresh OpenUV protection window data."""
_LOGGER.debug("Refreshing OpenUV protection window data")
await openuv.async_update_protection_data()
async_dispatcher_send(hass, TOPIC_UPDATE)
for service, method in [
("update_data", update_data),
("update_uv_index_data", update_uv_index_data),
("update_protection_data", update_protection_data),
]:
hass.services.async_register(DOMAIN, service, method)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
")",
":",
"_verify_domain_control",
"=",
"verify_domain_control",
"(",
"hass",
",",
"DOMAIN",
")",
"try",
":",
"websession",
"=",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
"hass",
")",
"openuv",
"=",
"OpenUV",
"(",
"Client",
"(",
"config_entry",
".",
"data",
"[",
"CONF_API_KEY",
"]",
",",
"config_entry",
".",
"data",
".",
"get",
"(",
"CONF_LATITUDE",
",",
"hass",
".",
"config",
".",
"latitude",
")",
",",
"config_entry",
".",
"data",
".",
"get",
"(",
"CONF_LONGITUDE",
",",
"hass",
".",
"config",
".",
"longitude",
")",
",",
"websession",
",",
"altitude",
"=",
"config_entry",
".",
"data",
".",
"get",
"(",
"CONF_ELEVATION",
",",
"hass",
".",
"config",
".",
"elevation",
")",
",",
")",
")",
"await",
"openuv",
".",
"async_update",
"(",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"DATA_OPENUV_CLIENT",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"=",
"openuv",
"except",
"OpenUvError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Config entry failed: %s\"",
",",
"err",
")",
"raise",
"ConfigEntryNotReady",
"from",
"err",
"for",
"component",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"config_entry",
",",
"component",
")",
")",
"@",
"_verify_domain_control",
"async",
"def",
"update_data",
"(",
"service",
")",
":",
"\"\"\"Refresh all OpenUV data.\"\"\"",
"_LOGGER",
".",
"debug",
"(",
"\"Refreshing all OpenUV data\"",
")",
"await",
"openuv",
".",
"async_update",
"(",
")",
"async_dispatcher_send",
"(",
"hass",
",",
"TOPIC_UPDATE",
")",
"@",
"_verify_domain_control",
"async",
"def",
"update_uv_index_data",
"(",
"service",
")",
":",
"\"\"\"Refresh OpenUV UV index data.\"\"\"",
"_LOGGER",
".",
"debug",
"(",
"\"Refreshing OpenUV UV index data\"",
")",
"await",
"openuv",
".",
"async_update_uv_index_data",
"(",
")",
"async_dispatcher_send",
"(",
"hass",
",",
"TOPIC_UPDATE",
")",
"@",
"_verify_domain_control",
"async",
"def",
"update_protection_data",
"(",
"service",
")",
":",
"\"\"\"Refresh OpenUV protection window data.\"\"\"",
"_LOGGER",
".",
"debug",
"(",
"\"Refreshing OpenUV protection window data\"",
")",
"await",
"openuv",
".",
"async_update_protection_data",
"(",
")",
"async_dispatcher_send",
"(",
"hass",
",",
"TOPIC_UPDATE",
")",
"for",
"service",
",",
"method",
"in",
"[",
"(",
"\"update_data\"",
",",
"update_data",
")",
",",
"(",
"\"update_uv_index_data\"",
",",
"update_uv_index_data",
")",
",",
"(",
"\"update_protection_data\"",
",",
"update_protection_data",
")",
",",
"]",
":",
"hass",
".",
"services",
".",
"async_register",
"(",
"DOMAIN",
",",
"service",
",",
"method",
")",
"return",
"True"
] | [
63,
0
] | [
117,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass, config_entry) | Unload an OpenUV config entry. | Unload an OpenUV config entry. | async def async_unload_entry(hass, config_entry):
"""Unload an OpenUV config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(config_entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN][DATA_OPENUV_CLIENT].pop(config_entry.entry_id)
return unload_ok | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
",",
"config_entry",
")",
":",
"unload_ok",
"=",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"config_entry",
",",
"component",
")",
"for",
"component",
"in",
"PLATFORMS",
"]",
")",
")",
"if",
"unload_ok",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"DATA_OPENUV_CLIENT",
"]",
".",
"pop",
"(",
"config_entry",
".",
"entry_id",
")",
"return",
"unload_ok"
] | [
120,
0
] | [
133,
20
] | python | en | ['en', 'en', 'en'] | True |
async_migrate_entry | (hass, config_entry) | Migrate the config entry upon new versions. | Migrate the config entry upon new versions. | async def async_migrate_entry(hass, config_entry):
"""Migrate the config entry upon new versions."""
version = config_entry.version
data = {**config_entry.data}
_LOGGER.debug("Migrating from version %s", version)
# 1 -> 2: Remove unused condition data:
if version == 1:
data.pop(CONF_BINARY_SENSORS, None)
data.pop(CONF_SENSORS, None)
version = config_entry.version = 2
hass.config_entries.async_update_entry(config_entry, data=data)
_LOGGER.debug("Migration to version %s successful", version)
return True | [
"async",
"def",
"async_migrate_entry",
"(",
"hass",
",",
"config_entry",
")",
":",
"version",
"=",
"config_entry",
".",
"version",
"data",
"=",
"{",
"*",
"*",
"config_entry",
".",
"data",
"}",
"_LOGGER",
".",
"debug",
"(",
"\"Migrating from version %s\"",
",",
"version",
")",
"# 1 -> 2: Remove unused condition data:",
"if",
"version",
"==",
"1",
":",
"data",
".",
"pop",
"(",
"CONF_BINARY_SENSORS",
",",
"None",
")",
"data",
".",
"pop",
"(",
"CONF_SENSORS",
",",
"None",
")",
"version",
"=",
"config_entry",
".",
"version",
"=",
"2",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"config_entry",
",",
"data",
"=",
"data",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Migration to version %s successful\"",
",",
"version",
")",
"return",
"True"
] | [
136,
0
] | [
151,
15
] | python | en | ['en', 'en', 'en'] | True |
OpenUV.__init__ | (self, client) | Initialize. | Initialize. | def __init__(self, client):
"""Initialize."""
self.client = client
self.data = {} | [
"def",
"__init__",
"(",
"self",
",",
"client",
")",
":",
"self",
".",
"client",
"=",
"client",
"self",
".",
"data",
"=",
"{",
"}"
] | [
157,
4
] | [
160,
22
] | python | en | ['en', 'en', 'it'] | False |
OpenUV.async_update_protection_data | (self) | Update binary sensor (protection window) data. | Update binary sensor (protection window) data. | async def async_update_protection_data(self):
"""Update binary sensor (protection window) data."""
try:
resp = await self.client.uv_protection_window()
self.data[DATA_PROTECTION_WINDOW] = resp["result"]
except OpenUvError as err:
_LOGGER.error("Error during protection data update: %s", err)
self.data[DATA_PROTECTION_WINDOW] = {} | [
"async",
"def",
"async_update_protection_data",
"(",
"self",
")",
":",
"try",
":",
"resp",
"=",
"await",
"self",
".",
"client",
".",
"uv_protection_window",
"(",
")",
"self",
".",
"data",
"[",
"DATA_PROTECTION_WINDOW",
"]",
"=",
"resp",
"[",
"\"result\"",
"]",
"except",
"OpenUvError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error during protection data update: %s\"",
",",
"err",
")",
"self",
".",
"data",
"[",
"DATA_PROTECTION_WINDOW",
"]",
"=",
"{",
"}"
] | [
162,
4
] | [
169,
50
] | python | en | ['en', 'sn', 'en'] | True |
OpenUV.async_update_uv_index_data | (self) | Update sensor (uv index, etc) data. | Update sensor (uv index, etc) data. | async def async_update_uv_index_data(self):
"""Update sensor (uv index, etc) data."""
try:
data = await self.client.uv_index()
self.data[DATA_UV] = data
except OpenUvError as err:
_LOGGER.error("Error during uv index data update: %s", err)
self.data[DATA_UV] = {} | [
"async",
"def",
"async_update_uv_index_data",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"await",
"self",
".",
"client",
".",
"uv_index",
"(",
")",
"self",
".",
"data",
"[",
"DATA_UV",
"]",
"=",
"data",
"except",
"OpenUvError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error during uv index data update: %s\"",
",",
"err",
")",
"self",
".",
"data",
"[",
"DATA_UV",
"]",
"=",
"{",
"}"
] | [
171,
4
] | [
178,
35
] | python | en | ['et', 'la', 'en'] | False |
OpenUV.async_update | (self) | Update sensor/binary sensor data. | Update sensor/binary sensor data. | async def async_update(self):
"""Update sensor/binary sensor data."""
tasks = [self.async_update_protection_data(), self.async_update_uv_index_data()]
await asyncio.gather(*tasks) | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"tasks",
"=",
"[",
"self",
".",
"async_update_protection_data",
"(",
")",
",",
"self",
".",
"async_update_uv_index_data",
"(",
")",
"]",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")"
] | [
180,
4
] | [
183,
36
] | python | en | ['en', 'bs', 'en'] | True |
OpenUvEntity.__init__ | (self, openuv) | Initialize. | Initialize. | def __init__(self, openuv):
"""Initialize."""
self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION}
self._available = True
self._name = None
self.openuv = openuv | [
"def",
"__init__",
"(",
"self",
",",
"openuv",
")",
":",
"self",
".",
"_attrs",
"=",
"{",
"ATTR_ATTRIBUTION",
":",
"DEFAULT_ATTRIBUTION",
"}",
"self",
".",
"_available",
"=",
"True",
"self",
".",
"_name",
"=",
"None",
"self",
".",
"openuv",
"=",
"openuv"
] | [
189,
4
] | [
194,
28
] | python | en | ['en', 'en', 'it'] | False |
OpenUvEntity.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self) -> bool:
"""Return True if entity is available."""
return self._available | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_available"
] | [
197,
4
] | [
199,
30
] | python | en | ['en', 'en', 'en'] | True |
OpenUvEntity.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return self._attrs | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_attrs"
] | [
202,
4
] | [
204,
26
] | python | en | ['en', 'en', 'en'] | True |
OpenUvEntity.name | (self) | Return the name of the entity. | Return the name of the entity. | def name(self):
"""Return the name of the entity."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
207,
4
] | [
209,
25
] | python | en | ['en', 'en', 'en'] | True |
OpenUvEntity.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def update():
"""Update the state."""
self.update_from_latest_data()
self.async_write_ha_state()
self.async_on_remove(async_dispatcher_connect(self.hass, TOPIC_UPDATE, update))
self.update_from_latest_data() | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"@",
"callback",
"def",
"update",
"(",
")",
":",
"\"\"\"Update the state.\"\"\"",
"self",
".",
"update_from_latest_data",
"(",
")",
"self",
".",
"async_write_ha_state",
"(",
")",
"self",
".",
"async_on_remove",
"(",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"TOPIC_UPDATE",
",",
"update",
")",
")",
"self",
".",
"update_from_latest_data",
"(",
")"
] | [
211,
4
] | [
222,
38
] | python | en | ['en', 'no', 'en'] | False |
OpenUvEntity.update_from_latest_data | (self) | Update the sensor using the latest data. | Update the sensor using the latest data. | def update_from_latest_data(self):
"""Update the sensor using the latest data."""
raise NotImplementedError | [
"def",
"update_from_latest_data",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | [
224,
4
] | [
226,
33
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Activate the Alexa component. | Activate the Alexa component. | async def async_setup(hass, config):
"""Activate the Alexa component."""
if DOMAIN not in config:
return True
config = config[DOMAIN]
flash_briefings_config = config.get(CONF_FLASH_BRIEFINGS)
intent.async_setup(hass)
if flash_briefings_config:
flash_briefings.async_setup(hass, flash_briefings_config)
try:
smart_home_config = config[CONF_SMART_HOME]
except KeyError:
pass
else:
smart_home_config = smart_home_config or SMART_HOME_SCHEMA({})
await smart_home_http.async_setup(hass, smart_home_config)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"if",
"DOMAIN",
"not",
"in",
"config",
":",
"return",
"True",
"config",
"=",
"config",
"[",
"DOMAIN",
"]",
"flash_briefings_config",
"=",
"config",
".",
"get",
"(",
"CONF_FLASH_BRIEFINGS",
")",
"intent",
".",
"async_setup",
"(",
"hass",
")",
"if",
"flash_briefings_config",
":",
"flash_briefings",
".",
"async_setup",
"(",
"hass",
",",
"flash_briefings_config",
")",
"try",
":",
"smart_home_config",
"=",
"config",
"[",
"CONF_SMART_HOME",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"smart_home_config",
"=",
"smart_home_config",
"or",
"SMART_HOME_SCHEMA",
"(",
"{",
"}",
")",
"await",
"smart_home_http",
".",
"async_setup",
"(",
"hass",
",",
"smart_home_config",
")",
"return",
"True"
] | [
76,
0
] | [
98,
15
] | python | en | ['en', 'en', 'en'] | True |
conv3x3 | (in_planes, out_planes, stride=1, dilation=1, padding=1) | 3x3 convolution with padding | 3x3 convolution with padding | def conv3x3(in_planes, out_planes, stride=1, dilation=1, padding=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, dilation=dilation,
padding=padding, bias=False) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
",",
"dilation",
"=",
"1",
",",
"padding",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"dilation",
"=",
"dilation",
",",
"padding",
"=",
"padding",
",",
"bias",
"=",
"False",
")"
] | [
29,
0
] | [
32,
49
] | python | en | ['en', 'ja', 'en'] | True |
resnet18 | (pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, **kwargs) | Constructs a ResNet-18 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| Constructs a ResNet-18 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| def resnet18(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, **kwargs):
"""Constructs a ResNet-18 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
"""
if num_classes is None:
assert expose_stages is not None, "num_class and expose_stages is both None"
assert 6 not in expose_stages, "can't expose the 6th stage for num_classes is None"
if expose_stages is None:
expose_stages = [6]
end_stage = max(expose_stages)
assert end_stage <= 6, "the max expose_stage is out of range"
layers = model_layers['resnet18'][:end_stage - 1]
model = ResNet(block=BasicBlock, layers=layers, num_classes=num_classes, expose_stages=expose_stages, dilations=dilations)
if pretrained:
if pretrained_model_path is not None:
state_dict = torch.load(pretrained_model_path, map_location=lambda storage, loc: storage)
else:
state_dict = model_zoo.load_url(model_urls['resnet18'])
model.load_pretrained_state_dict(state_dict)
return model | [
"def",
"resnet18",
"(",
"pretrained",
"=",
"False",
",",
"pretrained_model_path",
"=",
"None",
",",
"num_classes",
"=",
"None",
",",
"expose_stages",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_classes",
"is",
"None",
":",
"assert",
"expose_stages",
"is",
"not",
"None",
",",
"\"num_class and expose_stages is both None\"",
"assert",
"6",
"not",
"in",
"expose_stages",
",",
"\"can't expose the 6th stage for num_classes is None\"",
"if",
"expose_stages",
"is",
"None",
":",
"expose_stages",
"=",
"[",
"6",
"]",
"end_stage",
"=",
"max",
"(",
"expose_stages",
")",
"assert",
"end_stage",
"<=",
"6",
",",
"\"the max expose_stage is out of range\"",
"layers",
"=",
"model_layers",
"[",
"'resnet18'",
"]",
"[",
":",
"end_stage",
"-",
"1",
"]",
"model",
"=",
"ResNet",
"(",
"block",
"=",
"BasicBlock",
",",
"layers",
"=",
"layers",
",",
"num_classes",
"=",
"num_classes",
",",
"expose_stages",
"=",
"expose_stages",
",",
"dilations",
"=",
"dilations",
")",
"if",
"pretrained",
":",
"if",
"pretrained_model_path",
"is",
"not",
"None",
":",
"state_dict",
"=",
"torch",
".",
"load",
"(",
"pretrained_model_path",
",",
"map_location",
"=",
"lambda",
"storage",
",",
"loc",
":",
"storage",
")",
"else",
":",
"state_dict",
"=",
"model_zoo",
".",
"load_url",
"(",
"model_urls",
"[",
"'resnet18'",
"]",
")",
"model",
".",
"load_pretrained_state_dict",
"(",
"state_dict",
")",
"return",
"model"
] | [
243,
0
] | [
274,
16
] | python | en | ['en', 'en', 'en'] | True |
resnet34 | (pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, **kwargs) | Constructs a ResNet-34 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| Constructs a ResNet-34 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| def resnet34(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, **kwargs):
"""Constructs a ResNet-34 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
"""
if num_classes is None:
assert expose_stages is not None, "num_class and expose_stages is both None"
assert 6 not in expose_stages, "can't expose the 6th stage for num_classes is None"
if expose_stages is None:
expose_stages = [6]
end_stage = max(expose_stages)
assert end_stage <= 6, "the max expose_stage is out of range"
layers = model_layers['resnet34'][:end_stage - 1]
model = ResNet(block=BasicBlock, layers=layers, num_classes=num_classes, expose_stages=expose_stages,
dilations=dilations)
if pretrained:
if pretrained_model_path is not None:
state_dict = torch.load(pretrained_model_path, map_location=lambda storage, loc: storage)
else:
state_dict = model_zoo.load_url(model_urls['resnet34'])
model.load_pretrained_state_dict(state_dict)
return model | [
"def",
"resnet34",
"(",
"pretrained",
"=",
"False",
",",
"pretrained_model_path",
"=",
"None",
",",
"num_classes",
"=",
"None",
",",
"expose_stages",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_classes",
"is",
"None",
":",
"assert",
"expose_stages",
"is",
"not",
"None",
",",
"\"num_class and expose_stages is both None\"",
"assert",
"6",
"not",
"in",
"expose_stages",
",",
"\"can't expose the 6th stage for num_classes is None\"",
"if",
"expose_stages",
"is",
"None",
":",
"expose_stages",
"=",
"[",
"6",
"]",
"end_stage",
"=",
"max",
"(",
"expose_stages",
")",
"assert",
"end_stage",
"<=",
"6",
",",
"\"the max expose_stage is out of range\"",
"layers",
"=",
"model_layers",
"[",
"'resnet34'",
"]",
"[",
":",
"end_stage",
"-",
"1",
"]",
"model",
"=",
"ResNet",
"(",
"block",
"=",
"BasicBlock",
",",
"layers",
"=",
"layers",
",",
"num_classes",
"=",
"num_classes",
",",
"expose_stages",
"=",
"expose_stages",
",",
"dilations",
"=",
"dilations",
")",
"if",
"pretrained",
":",
"if",
"pretrained_model_path",
"is",
"not",
"None",
":",
"state_dict",
"=",
"torch",
".",
"load",
"(",
"pretrained_model_path",
",",
"map_location",
"=",
"lambda",
"storage",
",",
"loc",
":",
"storage",
")",
"else",
":",
"state_dict",
"=",
"model_zoo",
".",
"load_url",
"(",
"model_urls",
"[",
"'resnet34'",
"]",
")",
"model",
".",
"load_pretrained_state_dict",
"(",
"state_dict",
")",
"return",
"model"
] | [
277,
0
] | [
309,
16
] | python | en | ['en', 'en', 'en'] | True |
resnet50 | (pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False) | Constructs a ResNet-50 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| Constructs a ResNet-50 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| def resnet50(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False):
"""Constructs a ResNet-50 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
"""
if num_classes is None:
assert expose_stages is not None, "num_class and expose_stages is both None"
assert 6 not in expose_stages, "can't expose the 6th stage for num_classes is None"
if expose_stages is None:
expose_stages = [6]
end_stage = max(expose_stages)
assert end_stage <= 6, "the max expose_stage is out of range"
layers = model_layers['resnet50'][:end_stage - 1]
model = ResNet(block=Bottleneck, layers=layers, num_classes=num_classes, expose_stages=expose_stages,
dilations=dilations, stride_in_1x1=stride_in_1x1)
if pretrained:
if pretrained_model_path is not None:
state_dict = torch.load(pretrained_model_path, map_location=lambda storage, loc: storage)
else:
state_dict = model_zoo.load_url(model_urls['resnet50'])
model.load_pretrained_state_dict(state_dict)
return model | [
"def",
"resnet50",
"(",
"pretrained",
"=",
"False",
",",
"pretrained_model_path",
"=",
"None",
",",
"num_classes",
"=",
"None",
",",
"expose_stages",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"stride_in_1x1",
"=",
"False",
")",
":",
"if",
"num_classes",
"is",
"None",
":",
"assert",
"expose_stages",
"is",
"not",
"None",
",",
"\"num_class and expose_stages is both None\"",
"assert",
"6",
"not",
"in",
"expose_stages",
",",
"\"can't expose the 6th stage for num_classes is None\"",
"if",
"expose_stages",
"is",
"None",
":",
"expose_stages",
"=",
"[",
"6",
"]",
"end_stage",
"=",
"max",
"(",
"expose_stages",
")",
"assert",
"end_stage",
"<=",
"6",
",",
"\"the max expose_stage is out of range\"",
"layers",
"=",
"model_layers",
"[",
"'resnet50'",
"]",
"[",
":",
"end_stage",
"-",
"1",
"]",
"model",
"=",
"ResNet",
"(",
"block",
"=",
"Bottleneck",
",",
"layers",
"=",
"layers",
",",
"num_classes",
"=",
"num_classes",
",",
"expose_stages",
"=",
"expose_stages",
",",
"dilations",
"=",
"dilations",
",",
"stride_in_1x1",
"=",
"stride_in_1x1",
")",
"if",
"pretrained",
":",
"if",
"pretrained_model_path",
"is",
"not",
"None",
":",
"state_dict",
"=",
"torch",
".",
"load",
"(",
"pretrained_model_path",
",",
"map_location",
"=",
"lambda",
"storage",
",",
"loc",
":",
"storage",
")",
"else",
":",
"state_dict",
"=",
"model_zoo",
".",
"load_url",
"(",
"model_urls",
"[",
"'resnet50'",
"]",
")",
"model",
".",
"load_pretrained_state_dict",
"(",
"state_dict",
")",
"return",
"model"
] | [
312,
0
] | [
344,
16
] | python | en | ['en', 'en', 'en'] | True |
resnet101 | (pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False) | Constructs a ResNet-101 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| Constructs a ResNet-101 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| def resnet101(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False):
"""Constructs a ResNet-101 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
"""
if num_classes is None:
assert expose_stages is not None, "num_class and expose_stages is both None"
assert 6 not in expose_stages, "can't expose the 6th stage for num_classes is None"
if expose_stages is None:
expose_stages = [6]
end_stage = max(expose_stages)
assert end_stage <= 6, "the max expose_stage is out of range"
layers = model_layers['resnet101'][:end_stage - 1]
model = ResNet(block=Bottleneck, layers=layers, num_classes=num_classes, expose_stages=expose_stages,
dilations=dilations, stride_in_1x1=stride_in_1x1)
if pretrained:
if pretrained_model_path is not None:
state_dict = torch.load(pretrained_model_path, map_location=lambda storage, loc: storage)
else:
state_dict = model_zoo.load_url(model_urls['resnet101'])
model.load_pretrained_state_dict(state_dict)
return model | [
"def",
"resnet101",
"(",
"pretrained",
"=",
"False",
",",
"pretrained_model_path",
"=",
"None",
",",
"num_classes",
"=",
"None",
",",
"expose_stages",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"stride_in_1x1",
"=",
"False",
")",
":",
"if",
"num_classes",
"is",
"None",
":",
"assert",
"expose_stages",
"is",
"not",
"None",
",",
"\"num_class and expose_stages is both None\"",
"assert",
"6",
"not",
"in",
"expose_stages",
",",
"\"can't expose the 6th stage for num_classes is None\"",
"if",
"expose_stages",
"is",
"None",
":",
"expose_stages",
"=",
"[",
"6",
"]",
"end_stage",
"=",
"max",
"(",
"expose_stages",
")",
"assert",
"end_stage",
"<=",
"6",
",",
"\"the max expose_stage is out of range\"",
"layers",
"=",
"model_layers",
"[",
"'resnet101'",
"]",
"[",
":",
"end_stage",
"-",
"1",
"]",
"model",
"=",
"ResNet",
"(",
"block",
"=",
"Bottleneck",
",",
"layers",
"=",
"layers",
",",
"num_classes",
"=",
"num_classes",
",",
"expose_stages",
"=",
"expose_stages",
",",
"dilations",
"=",
"dilations",
",",
"stride_in_1x1",
"=",
"stride_in_1x1",
")",
"if",
"pretrained",
":",
"if",
"pretrained_model_path",
"is",
"not",
"None",
":",
"state_dict",
"=",
"torch",
".",
"load",
"(",
"pretrained_model_path",
",",
"map_location",
"=",
"lambda",
"storage",
",",
"loc",
":",
"storage",
")",
"else",
":",
"state_dict",
"=",
"model_zoo",
".",
"load_url",
"(",
"model_urls",
"[",
"'resnet101'",
"]",
")",
"model",
".",
"load_pretrained_state_dict",
"(",
"state_dict",
")",
"return",
"model"
] | [
347,
0
] | [
379,
16
] | python | en | ['en', 'en', 'en'] | True |
resnet152 | (pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False) | Constructs a ResNet-152 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| Constructs a ResNet-152 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
| def resnet152(pretrained=False, pretrained_model_path=None, num_classes=None, expose_stages=None, dilations=None, stride_in_1x1=False):
"""Constructs a ResNet-152 model
Args:
pretrained (bool): if True, load pretrained model. Default: False
pretrained_model_path (str, optional): only effective when pretrained=True,
if not specified, use pretrained model from model_zoo.
num_classes (int): number of classes for the fc output score.
expose_stages (list, optional): list of expose stages, e.g. [4, 5] means expose conv4 and conv5 stage output.
if not specified, only expose output of end_stage.
"""
if num_classes is None:
assert expose_stages is not None, "num_class and expose_stages is both None"
assert 6 not in expose_stages, "can't expose the 6th stage for num_classes is None"
if expose_stages is None:
expose_stages = [6]
end_stage = max(expose_stages)
assert end_stage <= 6, "the max expose_stage is out of range"
layers = model_layers['resnet152'][:end_stage - 1]
model = ResNet(block=Bottleneck, layers=layers, num_classes=num_classes, expose_stages=expose_stages,
dilations=dilations, stride_in_1x1=stride_in_1x1)
if pretrained:
if pretrained_model_path is not None:
state_dict = torch.load(pretrained_model_path, map_location=lambda storage, loc: storage)
else:
state_dict = model_zoo.load_url(model_urls['resnet152'])
model.load_pretrained_state_dict(state_dict)
return model | [
"def",
"resnet152",
"(",
"pretrained",
"=",
"False",
",",
"pretrained_model_path",
"=",
"None",
",",
"num_classes",
"=",
"None",
",",
"expose_stages",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"stride_in_1x1",
"=",
"False",
")",
":",
"if",
"num_classes",
"is",
"None",
":",
"assert",
"expose_stages",
"is",
"not",
"None",
",",
"\"num_class and expose_stages is both None\"",
"assert",
"6",
"not",
"in",
"expose_stages",
",",
"\"can't expose the 6th stage for num_classes is None\"",
"if",
"expose_stages",
"is",
"None",
":",
"expose_stages",
"=",
"[",
"6",
"]",
"end_stage",
"=",
"max",
"(",
"expose_stages",
")",
"assert",
"end_stage",
"<=",
"6",
",",
"\"the max expose_stage is out of range\"",
"layers",
"=",
"model_layers",
"[",
"'resnet152'",
"]",
"[",
":",
"end_stage",
"-",
"1",
"]",
"model",
"=",
"ResNet",
"(",
"block",
"=",
"Bottleneck",
",",
"layers",
"=",
"layers",
",",
"num_classes",
"=",
"num_classes",
",",
"expose_stages",
"=",
"expose_stages",
",",
"dilations",
"=",
"dilations",
",",
"stride_in_1x1",
"=",
"stride_in_1x1",
")",
"if",
"pretrained",
":",
"if",
"pretrained_model_path",
"is",
"not",
"None",
":",
"state_dict",
"=",
"torch",
".",
"load",
"(",
"pretrained_model_path",
",",
"map_location",
"=",
"lambda",
"storage",
",",
"loc",
":",
"storage",
")",
"else",
":",
"state_dict",
"=",
"model_zoo",
".",
"load_url",
"(",
"model_urls",
"[",
"'resnet152'",
"]",
")",
"model",
".",
"load_pretrained_state_dict",
"(",
"state_dict",
")",
"return",
"model"
] | [
382,
0
] | [
414,
16
] | python | en | ['en', 'en', 'en'] | True |
ResNet.load_pretrained_state_dict | (self, state_dict) | Load state dict of pretrained model
Args:
state_dict (dict): state dict to load
| Load state dict of pretrained model
Args:
state_dict (dict): state dict to load
| def load_pretrained_state_dict(self, state_dict):
"""Load state dict of pretrained model
Args:
state_dict (dict): state dict to load
"""
new_state_dict = self.state_dict()
miss_keys = []
for k in new_state_dict.keys():
if k in state_dict.keys():
new_state_dict[k] = state_dict[k]
else:
miss_keys.append(k)
if len(miss_keys) > 0:
warnings.warn('miss keys: {}'.format(miss_keys))
self.load_state_dict(new_state_dict) | [
"def",
"load_pretrained_state_dict",
"(",
"self",
",",
"state_dict",
")",
":",
"new_state_dict",
"=",
"self",
".",
"state_dict",
"(",
")",
"miss_keys",
"=",
"[",
"]",
"for",
"k",
"in",
"new_state_dict",
".",
"keys",
"(",
")",
":",
"if",
"k",
"in",
"state_dict",
".",
"keys",
"(",
")",
":",
"new_state_dict",
"[",
"k",
"]",
"=",
"state_dict",
"[",
"k",
"]",
"else",
":",
"miss_keys",
".",
"append",
"(",
"k",
")",
"if",
"len",
"(",
"miss_keys",
")",
">",
"0",
":",
"warnings",
".",
"warn",
"(",
"'miss keys: {}'",
".",
"format",
"(",
"miss_keys",
")",
")",
"self",
".",
"load_state_dict",
"(",
"new_state_dict",
")"
] | [
200,
4
] | [
214,
44
] | python | en | ['en', 'en', 'en'] | True |
setup_fritzbox | (hass: HomeAssistantType, config: dict) | Set up mock AVM Fritz!Box. | Set up mock AVM Fritz!Box. | async def setup_fritzbox(hass: HomeAssistantType, config: dict):
"""Set up mock AVM Fritz!Box."""
assert await async_setup_component(hass, FB_DOMAIN, config) is True
await hass.async_block_till_done() | [
"async",
"def",
"setup_fritzbox",
"(",
"hass",
":",
"HomeAssistantType",
",",
"config",
":",
"dict",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"FB_DOMAIN",
",",
"config",
")",
"is",
"True",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
49,
0
] | [
52,
38
] | python | en | ['en', 'zu', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.