Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
yaml_to_object
(data: str)
Create object from yaml string.
Create object from yaml string.
def yaml_to_object(data: str) -> JSON_TYPE: """Create object from yaml string.""" yaml = YAML(typ="rt") try: result: Union[List, Dict, str] = yaml.load(data) return result except YAMLError as exc: _LOGGER.error("YAML error: %s", exc) raise HomeAssistantError(exc) from exc
[ "def", "yaml_to_object", "(", "data", ":", "str", ")", "->", "JSON_TYPE", ":", "yaml", "=", "YAML", "(", "typ", "=", "\"rt\"", ")", "try", ":", "result", ":", "Union", "[", "List", ",", "Dict", ",", "str", "]", "=", "yaml", ".", "load", "(", "data", ")", "return", "result", "except", "YAMLError", "as", "exc", ":", "_LOGGER", ".", "error", "(", "\"YAML error: %s\"", ",", "exc", ")", "raise", "HomeAssistantError", "(", "exc", ")", "from", "exc" ]
[ 75, 0 ]
[ 83, 46 ]
python
en
['en', 'en', 'en']
True
load_yaml
(fname: str, round_trip: bool = False)
Load a YAML file.
Load a YAML file.
def load_yaml(fname: str, round_trip: bool = False) -> JSON_TYPE: """Load a YAML file.""" if round_trip: yaml = YAML(typ="rt") yaml.preserve_quotes = True else: if ExtSafeConstructor.name is None: ExtSafeConstructor.name = fname yaml = YAML(typ="safe") yaml.Constructor = ExtSafeConstructor try: with open(fname, encoding="utf-8") as conf_file: # If configuration file is empty YAML returns None # We convert that to an empty dict return yaml.load(conf_file) or OrderedDict() except YAMLError as exc: _LOGGER.error("YAML error in %s: %s", fname, exc) raise HomeAssistantError(exc) from exc except UnicodeDecodeError as exc: _LOGGER.error("Unable to read file %s: %s", fname, exc) raise HomeAssistantError(exc) from exc
[ "def", "load_yaml", "(", "fname", ":", "str", ",", "round_trip", ":", "bool", "=", "False", ")", "->", "JSON_TYPE", ":", "if", "round_trip", ":", "yaml", "=", "YAML", "(", "typ", "=", "\"rt\"", ")", "yaml", ".", "preserve_quotes", "=", "True", "else", ":", "if", "ExtSafeConstructor", ".", "name", "is", "None", ":", "ExtSafeConstructor", ".", "name", "=", "fname", "yaml", "=", "YAML", "(", "typ", "=", "\"safe\"", ")", "yaml", ".", "Constructor", "=", "ExtSafeConstructor", "try", ":", "with", "open", "(", "fname", ",", "encoding", "=", "\"utf-8\"", ")", "as", "conf_file", ":", "# If configuration file is empty YAML returns None", "# We convert that to an empty dict", "return", "yaml", ".", "load", "(", "conf_file", ")", "or", "OrderedDict", "(", ")", "except", "YAMLError", "as", "exc", ":", "_LOGGER", ".", "error", "(", "\"YAML error in %s: %s\"", ",", "fname", ",", "exc", ")", "raise", "HomeAssistantError", "(", "exc", ")", "from", "exc", "except", "UnicodeDecodeError", "as", "exc", ":", "_LOGGER", ".", "error", "(", "\"Unable to read file %s: %s\"", ",", "fname", ",", "exc", ")", "raise", "HomeAssistantError", "(", "exc", ")", "from", "exc" ]
[ 86, 0 ]
[ 107, 46 ]
python
en
['en', 'ny', 'it']
False
save_yaml
(fname: str, data: JSON_TYPE)
Save a YAML file.
Save a YAML file.
def save_yaml(fname: str, data: JSON_TYPE) -> None: """Save a YAML file.""" yaml = YAML(typ="rt") yaml.indent(sequence=4, offset=2) tmp_fname = f"{fname}__TEMP__" try: try: file_stat = os.stat(fname) except OSError: file_stat = stat_result((0o644, -1, -1, -1, -1, -1, -1, -1, -1, -1)) with open( os.open(tmp_fname, O_WRONLY | O_CREAT | O_TRUNC, file_stat.st_mode), "w", encoding="utf-8", ) as temp_file: yaml.dump(data, temp_file) os.replace(tmp_fname, fname) if hasattr(os, "chown") and file_stat.st_ctime > -1: try: os.chown(fname, file_stat.st_uid, file_stat.st_gid) except OSError: pass except YAMLError as exc: _LOGGER.error(str(exc)) raise HomeAssistantError(exc) from exc except OSError as exc: _LOGGER.exception("Saving YAML file %s failed: %s", fname, exc) raise WriteError(exc) from exc finally: if os.path.exists(tmp_fname): try: os.remove(tmp_fname) except OSError as exc: # If we are cleaning up then something else went wrong, so # we should suppress likely follow-on errors in the cleanup _LOGGER.error("YAML replacement cleanup failed: %s", exc)
[ "def", "save_yaml", "(", "fname", ":", "str", ",", "data", ":", "JSON_TYPE", ")", "->", "None", ":", "yaml", "=", "YAML", "(", "typ", "=", "\"rt\"", ")", "yaml", ".", "indent", "(", "sequence", "=", "4", ",", "offset", "=", "2", ")", "tmp_fname", "=", "f\"{fname}__TEMP__\"", "try", ":", "try", ":", "file_stat", "=", "os", ".", "stat", "(", "fname", ")", "except", "OSError", ":", "file_stat", "=", "stat_result", "(", "(", "0o644", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ")", ")", "with", "open", "(", "os", ".", "open", "(", "tmp_fname", ",", "O_WRONLY", "|", "O_CREAT", "|", "O_TRUNC", ",", "file_stat", ".", "st_mode", ")", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ",", ")", "as", "temp_file", ":", "yaml", ".", "dump", "(", "data", ",", "temp_file", ")", "os", ".", "replace", "(", "tmp_fname", ",", "fname", ")", "if", "hasattr", "(", "os", ",", "\"chown\"", ")", "and", "file_stat", ".", "st_ctime", ">", "-", "1", ":", "try", ":", "os", ".", "chown", "(", "fname", ",", "file_stat", ".", "st_uid", ",", "file_stat", ".", "st_gid", ")", "except", "OSError", ":", "pass", "except", "YAMLError", "as", "exc", ":", "_LOGGER", ".", "error", "(", "str", "(", "exc", ")", ")", "raise", "HomeAssistantError", "(", "exc", ")", "from", "exc", "except", "OSError", "as", "exc", ":", "_LOGGER", ".", "exception", "(", "\"Saving YAML file %s failed: %s\"", ",", "fname", ",", "exc", ")", "raise", "WriteError", "(", "exc", ")", "from", "exc", "finally", ":", "if", "os", ".", "path", ".", "exists", "(", "tmp_fname", ")", ":", "try", ":", "os", ".", "remove", "(", "tmp_fname", ")", "except", "OSError", "as", "exc", ":", "# If we are cleaning up then something else went wrong, so", "# we should suppress likely follow-on errors in the cleanup", "_LOGGER", ".", "error", "(", "\"YAML replacement cleanup failed: %s\"", ",", "exc", ")" ]
[ 110, 0 ]
[ 145, 73 ]
python
en
['en', 'ny', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up Homekit lightbulb.
Set up Homekit lightbulb.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Homekit lightbulb.""" hkid = config_entry.data["AccessoryPairingID"] conn = hass.data[KNOWN_DEVICES][hkid] @callback def async_add_service(service): if service.short_type != ServicesTypes.LIGHTBULB: return False info = {"aid": service.accessory.aid, "iid": service.iid} async_add_entities([HomeKitLight(conn, info)], True) return True conn.add_listener(async_add_service)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "hkid", "=", "config_entry", ".", "data", "[", "\"AccessoryPairingID\"", "]", "conn", "=", "hass", ".", "data", "[", "KNOWN_DEVICES", "]", "[", "hkid", "]", "@", "callback", "def", "async_add_service", "(", "service", ")", ":", "if", "service", ".", "short_type", "!=", "ServicesTypes", ".", "LIGHTBULB", ":", "return", "False", "info", "=", "{", "\"aid\"", ":", "service", ".", "accessory", ".", "aid", ",", "\"iid\"", ":", "service", ".", "iid", "}", "async_add_entities", "(", "[", "HomeKitLight", "(", "conn", ",", "info", ")", "]", ",", "True", ")", "return", "True", "conn", ".", "add_listener", "(", "async_add_service", ")" ]
[ 18, 0 ]
[ 31, 40 ]
python
en
['en', 'no', 'en']
True
HomeKitLight.get_characteristic_types
(self)
Define the homekit characteristics the entity cares about.
Define the homekit characteristics the entity cares about.
def get_characteristic_types(self): """Define the homekit characteristics the entity cares about.""" return [ CharacteristicsTypes.ON, CharacteristicsTypes.BRIGHTNESS, CharacteristicsTypes.COLOR_TEMPERATURE, CharacteristicsTypes.HUE, CharacteristicsTypes.SATURATION, ]
[ "def", "get_characteristic_types", "(", "self", ")", ":", "return", "[", "CharacteristicsTypes", ".", "ON", ",", "CharacteristicsTypes", ".", "BRIGHTNESS", ",", "CharacteristicsTypes", ".", "COLOR_TEMPERATURE", ",", "CharacteristicsTypes", ".", "HUE", ",", "CharacteristicsTypes", ".", "SATURATION", ",", "]" ]
[ 37, 4 ]
[ 45, 9 ]
python
en
['en', 'en', 'en']
True
HomeKitLight.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self.service.value(CharacteristicsTypes.ON)
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "service", ".", "value", "(", "CharacteristicsTypes", ".", "ON", ")" ]
[ 48, 4 ]
[ 50, 58 ]
python
en
['en', 'fy', 'en']
True
HomeKitLight.brightness
(self)
Return the brightness of this light between 0..255.
Return the brightness of this light between 0..255.
def brightness(self): """Return the brightness of this light between 0..255.""" return self.service.value(CharacteristicsTypes.BRIGHTNESS) * 255 / 100
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "service", ".", "value", "(", "CharacteristicsTypes", ".", "BRIGHTNESS", ")", "*", "255", "/", "100" ]
[ 53, 4 ]
[ 55, 78 ]
python
en
['en', 'en', 'en']
True
HomeKitLight.hs_color
(self)
Return the color property.
Return the color property.
def hs_color(self): """Return the color property.""" return ( self.service.value(CharacteristicsTypes.HUE), self.service.value(CharacteristicsTypes.SATURATION), )
[ "def", "hs_color", "(", "self", ")", ":", "return", "(", "self", ".", "service", ".", "value", "(", "CharacteristicsTypes", ".", "HUE", ")", ",", "self", ".", "service", ".", "value", "(", "CharacteristicsTypes", ".", "SATURATION", ")", ",", ")" ]
[ 58, 4 ]
[ 63, 9 ]
python
en
['en', 'en', 'en']
True
HomeKitLight.color_temp
(self)
Return the color temperature.
Return the color temperature.
def color_temp(self): """Return the color temperature.""" return self.service.value(CharacteristicsTypes.COLOR_TEMPERATURE)
[ "def", "color_temp", "(", "self", ")", ":", "return", "self", ".", "service", ".", "value", "(", "CharacteristicsTypes", ".", "COLOR_TEMPERATURE", ")" ]
[ 66, 4 ]
[ 68, 73 ]
python
en
['en', 'la', 'en']
True
HomeKitLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" features = 0 if self.service.has(CharacteristicsTypes.BRIGHTNESS): features |= SUPPORT_BRIGHTNESS if self.service.has(CharacteristicsTypes.COLOR_TEMPERATURE): features |= SUPPORT_COLOR_TEMP if self.service.has(CharacteristicsTypes.HUE): features |= SUPPORT_COLOR if self.service.has(CharacteristicsTypes.SATURATION): features |= SUPPORT_COLOR return features
[ "def", "supported_features", "(", "self", ")", ":", "features", "=", "0", "if", "self", ".", "service", ".", "has", "(", "CharacteristicsTypes", ".", "BRIGHTNESS", ")", ":", "features", "|=", "SUPPORT_BRIGHTNESS", "if", "self", ".", "service", ".", "has", "(", "CharacteristicsTypes", ".", "COLOR_TEMPERATURE", ")", ":", "features", "|=", "SUPPORT_COLOR_TEMP", "if", "self", ".", "service", ".", "has", "(", "CharacteristicsTypes", ".", "HUE", ")", ":", "features", "|=", "SUPPORT_COLOR", "if", "self", ".", "service", ".", "has", "(", "CharacteristicsTypes", ".", "SATURATION", ")", ":", "features", "|=", "SUPPORT_COLOR", "return", "features" ]
[ 71, 4 ]
[ 87, 23 ]
python
en
['da', 'en', 'en']
True
HomeKitLight.async_turn_on
(self, **kwargs)
Turn the specified light on.
Turn the specified light on.
async def async_turn_on(self, **kwargs): """Turn the specified light on.""" hs_color = kwargs.get(ATTR_HS_COLOR) temperature = kwargs.get(ATTR_COLOR_TEMP) brightness = kwargs.get(ATTR_BRIGHTNESS) characteristics = {} if hs_color is not None: characteristics.update( { CharacteristicsTypes.HUE: hs_color[0], CharacteristicsTypes.SATURATION: hs_color[1], } ) if brightness is not None: characteristics[CharacteristicsTypes.BRIGHTNESS] = int( brightness * 100 / 255 ) if temperature is not None: characteristics[CharacteristicsTypes.COLOR_TEMPERATURE] = int(temperature) characteristics[CharacteristicsTypes.ON] = True await self.async_put_characteristics(characteristics)
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "hs_color", "=", "kwargs", ".", "get", "(", "ATTR_HS_COLOR", ")", "temperature", "=", "kwargs", ".", "get", "(", "ATTR_COLOR_TEMP", ")", "brightness", "=", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ")", "characteristics", "=", "{", "}", "if", "hs_color", "is", "not", "None", ":", "characteristics", ".", "update", "(", "{", "CharacteristicsTypes", ".", "HUE", ":", "hs_color", "[", "0", "]", ",", "CharacteristicsTypes", ".", "SATURATION", ":", "hs_color", "[", "1", "]", ",", "}", ")", "if", "brightness", "is", "not", "None", ":", "characteristics", "[", "CharacteristicsTypes", ".", "BRIGHTNESS", "]", "=", "int", "(", "brightness", "*", "100", "/", "255", ")", "if", "temperature", "is", "not", "None", ":", "characteristics", "[", "CharacteristicsTypes", ".", "COLOR_TEMPERATURE", "]", "=", "int", "(", "temperature", ")", "characteristics", "[", "CharacteristicsTypes", ".", "ON", "]", "=", "True", "await", "self", ".", "async_put_characteristics", "(", "characteristics", ")" ]
[ 89, 4 ]
[ 115, 61 ]
python
en
['en', 'en', 'en']
True
HomeKitLight.async_turn_off
(self, **kwargs)
Turn the specified light off.
Turn the specified light off.
async def async_turn_off(self, **kwargs): """Turn the specified light off.""" await self.async_put_characteristics({CharacteristicsTypes.ON: False})
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "async_put_characteristics", "(", "{", "CharacteristicsTypes", ".", "ON", ":", "False", "}", ")" ]
[ 117, 4 ]
[ 119, 78 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Insteon covers from a config entry.
Set up the Insteon covers from a config entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Insteon covers from a config entry.""" def add_entities(discovery_info=None): """Add the Insteon entities for the platform.""" async_add_insteon_entities( hass, COVER_DOMAIN, InsteonCoverEntity, async_add_entities, discovery_info ) signal = f"{SIGNAL_ADD_ENTITIES}_{COVER_DOMAIN}" async_dispatcher_connect(hass, signal, add_entities) add_entities()
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "def", "add_entities", "(", "discovery_info", "=", "None", ")", ":", "\"\"\"Add the Insteon entities for the platform.\"\"\"", "async_add_insteon_entities", "(", "hass", ",", "COVER_DOMAIN", ",", "InsteonCoverEntity", ",", "async_add_entities", ",", "discovery_info", ")", "signal", "=", "f\"{SIGNAL_ADD_ENTITIES}_{COVER_DOMAIN}\"", "async_dispatcher_connect", "(", "hass", ",", "signal", ",", "add_entities", ")", "add_entities", "(", ")" ]
[ 20, 0 ]
[ 31, 18 ]
python
en
['en', 'en', 'en']
True
InsteonCoverEntity.current_cover_position
(self)
Return the current cover position.
Return the current cover position.
def current_cover_position(self): """Return the current cover position.""" if self._insteon_device_group.value is not None: pos = self._insteon_device_group.value else: pos = 0 return int(math.ceil(pos * 100 / 255))
[ "def", "current_cover_position", "(", "self", ")", ":", "if", "self", ".", "_insteon_device_group", ".", "value", "is", "not", "None", ":", "pos", "=", "self", ".", "_insteon_device_group", ".", "value", "else", ":", "pos", "=", "0", "return", "int", "(", "math", ".", "ceil", "(", "pos", "*", "100", "/", "255", ")", ")" ]
[ 38, 4 ]
[ 44, 46 ]
python
en
['en', 'en', 'en']
True
InsteonCoverEntity.supported_features
(self)
Return the supported features for this entity.
Return the supported features for this entity.
def supported_features(self): """Return the supported features for this entity.""" return SUPPORTED_FEATURES
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORTED_FEATURES" ]
[ 47, 4 ]
[ 49, 33 ]
python
en
['en', 'en', 'en']
True
InsteonCoverEntity.is_closed
(self)
Return the boolean response if the node is on.
Return the boolean response if the node is on.
def is_closed(self): """Return the boolean response if the node is on.""" return bool(self.current_cover_position)
[ "def", "is_closed", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "current_cover_position", ")" ]
[ 52, 4 ]
[ 54, 48 ]
python
en
['en', 'en', 'en']
True
InsteonCoverEntity.async_open_cover
(self, **kwargs)
Open cover.
Open cover.
async def async_open_cover(self, **kwargs): """Open cover.""" await self._insteon_device.async_open()
[ "async", "def", "async_open_cover", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "_insteon_device", ".", "async_open", "(", ")" ]
[ 56, 4 ]
[ 58, 47 ]
python
en
['es', 'en', 'en']
False
InsteonCoverEntity.async_close_cover
(self, **kwargs)
Close cover.
Close cover.
async def async_close_cover(self, **kwargs): """Close cover.""" await self._insteon_device.async_close()
[ "async", "def", "async_close_cover", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "_insteon_device", ".", "async_close", "(", ")" ]
[ 60, 4 ]
[ 62, 48 ]
python
en
['en', 'la', 'en']
False
InsteonCoverEntity.async_set_cover_position
(self, **kwargs)
Set the cover position.
Set the cover position.
async def async_set_cover_position(self, **kwargs): """Set the cover position.""" position = int(kwargs[ATTR_POSITION] * 255 / 100) if position == 0: await self._insteon_device.async_close() else: await self._insteon_device.async_open( open_level=position, group=self._insteon_device_group.group )
[ "async", "def", "async_set_cover_position", "(", "self", ",", "*", "*", "kwargs", ")", ":", "position", "=", "int", "(", "kwargs", "[", "ATTR_POSITION", "]", "*", "255", "/", "100", ")", "if", "position", "==", "0", ":", "await", "self", ".", "_insteon_device", ".", "async_close", "(", ")", "else", ":", "await", "self", ".", "_insteon_device", ".", "async_open", "(", "open_level", "=", "position", ",", "group", "=", "self", ".", "_insteon_device_group", ".", "group", ")" ]
[ 64, 4 ]
[ 72, 13 ]
python
en
['en', 'en', 'en']
True
create
(hass, message, title=None, notification_id=None)
Generate a notification.
Generate a notification.
def create(hass, message, title=None, notification_id=None): """Generate a notification.""" hass.add_job(async_create, hass, message, title, notification_id)
[ "def", "create", "(", "hass", ",", "message", ",", "title", "=", "None", ",", "notification_id", "=", "None", ")", ":", "hass", ".", "add_job", "(", "async_create", ",", "hass", ",", "message", ",", "title", ",", "notification_id", ")" ]
[ 55, 0 ]
[ 57, 69 ]
python
en
['en', 'en', 'en']
True
dismiss
(hass, notification_id)
Remove a notification.
Remove a notification.
def dismiss(hass, notification_id): """Remove a notification.""" hass.add_job(async_dismiss, hass, notification_id)
[ "def", "dismiss", "(", "hass", ",", "notification_id", ")", ":", "hass", ".", "add_job", "(", "async_dismiss", ",", "hass", ",", "notification_id", ")" ]
[ 61, 0 ]
[ 63, 54 ]
python
en
['en', 'en', 'en']
True
async_create
( hass: HomeAssistant, message: str, title: Optional[str] = None, notification_id: Optional[str] = None, )
Generate a notification.
Generate a notification.
def async_create( hass: HomeAssistant, message: str, title: Optional[str] = None, notification_id: Optional[str] = None, ) -> None: """Generate a notification.""" data = { key: value for key, value in [ (ATTR_TITLE, title), (ATTR_MESSAGE, message), (ATTR_NOTIFICATION_ID, notification_id), ] if value is not None } hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_CREATE, data))
[ "def", "async_create", "(", "hass", ":", "HomeAssistant", ",", "message", ":", "str", ",", "title", ":", "Optional", "[", "str", "]", "=", "None", ",", "notification_id", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "None", ":", "data", "=", "{", "key", ":", "value", "for", "key", ",", "value", "in", "[", "(", "ATTR_TITLE", ",", "title", ")", ",", "(", "ATTR_MESSAGE", ",", "message", ")", ",", "(", "ATTR_NOTIFICATION_ID", ",", "notification_id", ")", ",", "]", "if", "value", "is", "not", "None", "}", "hass", ".", "async_create_task", "(", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_CREATE", ",", "data", ")", ")" ]
[ 68, 0 ]
[ 85, 82 ]
python
en
['en', 'en', 'en']
True
async_dismiss
(hass: HomeAssistant, notification_id: str)
Remove a notification.
Remove a notification.
def async_dismiss(hass: HomeAssistant, notification_id: str) -> None: """Remove a notification.""" data = {ATTR_NOTIFICATION_ID: notification_id} hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_DISMISS, data))
[ "def", "async_dismiss", "(", "hass", ":", "HomeAssistant", ",", "notification_id", ":", "str", ")", "->", "None", ":", "data", "=", "{", "ATTR_NOTIFICATION_ID", ":", "notification_id", "}", "hass", ".", "async_create_task", "(", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_DISMISS", ",", "data", ")", ")" ]
[ 90, 0 ]
[ 94, 83 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass: HomeAssistant, config: dict)
Set up the persistent notification component.
Set up the persistent notification component.
async def async_setup(hass: HomeAssistant, config: dict) -> bool: """Set up the persistent notification component.""" persistent_notifications: MutableMapping[str, MutableMapping] = OrderedDict() hass.data[DOMAIN] = {"notifications": persistent_notifications} @callback def create_service(call): """Handle a create notification service call.""" title = call.data.get(ATTR_TITLE) message = call.data.get(ATTR_MESSAGE) notification_id = call.data.get(ATTR_NOTIFICATION_ID) if notification_id is not None: entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id)) else: entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, DEFAULT_OBJECT_ID, hass=hass ) notification_id = entity_id.split(".")[1] attr = {} if title is not None: try: title.hass = hass title = title.async_render(parse_result=False) except TemplateError as ex: _LOGGER.error("Error rendering title %s: %s", title, ex) title = title.template attr[ATTR_TITLE] = title try: message.hass = hass message = message.async_render(parse_result=False) except TemplateError as ex: _LOGGER.error("Error rendering message %s: %s", message, ex) message = message.template attr[ATTR_MESSAGE] = message hass.states.async_set(entity_id, STATE, attr) # Store notification and fire event # This will eventually replace state machine storage persistent_notifications[entity_id] = { ATTR_MESSAGE: message, ATTR_NOTIFICATION_ID: notification_id, ATTR_STATUS: STATUS_UNREAD, ATTR_TITLE: title, ATTR_CREATED_AT: dt_util.utcnow(), } hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED) @callback def dismiss_service(call): """Handle the dismiss notification service call.""" notification_id = call.data.get(ATTR_NOTIFICATION_ID) entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id)) if entity_id not in persistent_notifications: return hass.states.async_remove(entity_id, call.context) del persistent_notifications[entity_id] hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED) @callback def mark_read_service(call): """Handle the mark_read notification service call.""" notification_id = call.data.get(ATTR_NOTIFICATION_ID) entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id)) if entity_id not in persistent_notifications: _LOGGER.error( "Marking persistent_notification read failed: " "Notification ID %s not found", notification_id, ) return persistent_notifications[entity_id][ATTR_STATUS] = STATUS_READ hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED) hass.services.async_register( DOMAIN, SERVICE_CREATE, create_service, SCHEMA_SERVICE_CREATE ) hass.services.async_register( DOMAIN, SERVICE_DISMISS, dismiss_service, SCHEMA_SERVICE_DISMISS ) hass.services.async_register( DOMAIN, SERVICE_MARK_READ, mark_read_service, SCHEMA_SERVICE_MARK_READ ) hass.components.websocket_api.async_register_command(websocket_get_notifications) return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", "->", "bool", ":", "persistent_notifications", ":", "MutableMapping", "[", "str", ",", "MutableMapping", "]", "=", "OrderedDict", "(", ")", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "\"notifications\"", ":", "persistent_notifications", "}", "@", "callback", "def", "create_service", "(", "call", ")", ":", "\"\"\"Handle a create notification service call.\"\"\"", "title", "=", "call", ".", "data", ".", "get", "(", "ATTR_TITLE", ")", "message", "=", "call", ".", "data", ".", "get", "(", "ATTR_MESSAGE", ")", "notification_id", "=", "call", ".", "data", ".", "get", "(", "ATTR_NOTIFICATION_ID", ")", "if", "notification_id", "is", "not", "None", ":", "entity_id", "=", "ENTITY_ID_FORMAT", ".", "format", "(", "slugify", "(", "notification_id", ")", ")", "else", ":", "entity_id", "=", "async_generate_entity_id", "(", "ENTITY_ID_FORMAT", ",", "DEFAULT_OBJECT_ID", ",", "hass", "=", "hass", ")", "notification_id", "=", "entity_id", ".", "split", "(", "\".\"", ")", "[", "1", "]", "attr", "=", "{", "}", "if", "title", "is", "not", "None", ":", "try", ":", "title", ".", "hass", "=", "hass", "title", "=", "title", ".", "async_render", "(", "parse_result", "=", "False", ")", "except", "TemplateError", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Error rendering title %s: %s\"", ",", "title", ",", "ex", ")", "title", "=", "title", ".", "template", "attr", "[", "ATTR_TITLE", "]", "=", "title", "try", ":", "message", ".", "hass", "=", "hass", "message", "=", "message", ".", "async_render", "(", "parse_result", "=", "False", ")", "except", "TemplateError", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Error rendering message %s: %s\"", ",", "message", ",", "ex", ")", "message", "=", "message", ".", "template", "attr", "[", "ATTR_MESSAGE", "]", "=", "message", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE", ",", "attr", ")", "# Store notification and fire event", "# This will eventually replace state machine storage", "persistent_notifications", "[", "entity_id", "]", "=", "{", "ATTR_MESSAGE", ":", "message", ",", "ATTR_NOTIFICATION_ID", ":", "notification_id", ",", "ATTR_STATUS", ":", "STATUS_UNREAD", ",", "ATTR_TITLE", ":", "title", ",", "ATTR_CREATED_AT", ":", "dt_util", ".", "utcnow", "(", ")", ",", "}", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_PERSISTENT_NOTIFICATIONS_UPDATED", ")", "@", "callback", "def", "dismiss_service", "(", "call", ")", ":", "\"\"\"Handle the dismiss notification service call.\"\"\"", "notification_id", "=", "call", ".", "data", ".", "get", "(", "ATTR_NOTIFICATION_ID", ")", "entity_id", "=", "ENTITY_ID_FORMAT", ".", "format", "(", "slugify", "(", "notification_id", ")", ")", "if", "entity_id", "not", "in", "persistent_notifications", ":", "return", "hass", ".", "states", ".", "async_remove", "(", "entity_id", ",", "call", ".", "context", ")", "del", "persistent_notifications", "[", "entity_id", "]", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_PERSISTENT_NOTIFICATIONS_UPDATED", ")", "@", "callback", "def", "mark_read_service", "(", "call", ")", ":", "\"\"\"Handle the mark_read notification service call.\"\"\"", "notification_id", "=", "call", ".", "data", ".", "get", "(", "ATTR_NOTIFICATION_ID", ")", "entity_id", "=", "ENTITY_ID_FORMAT", ".", "format", "(", "slugify", "(", "notification_id", ")", ")", "if", "entity_id", "not", "in", "persistent_notifications", ":", "_LOGGER", ".", "error", "(", "\"Marking persistent_notification read failed: \"", "\"Notification ID %s not found\"", ",", "notification_id", ",", ")", "return", "persistent_notifications", "[", "entity_id", "]", "[", "ATTR_STATUS", "]", "=", "STATUS_READ", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_PERSISTENT_NOTIFICATIONS_UPDATED", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_CREATE", ",", "create_service", ",", "SCHEMA_SERVICE_CREATE", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_DISMISS", ",", "dismiss_service", ",", "SCHEMA_SERVICE_DISMISS", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_MARK_READ", ",", "mark_read_service", ",", "SCHEMA_SERVICE_MARK_READ", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "websocket_get_notifications", ")", "return", "True" ]
[ 97, 0 ]
[ 196, 15 ]
python
en
['en', 'en', 'en']
True
websocket_get_notifications
( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: Mapping[str, Any], )
Return a list of persistent_notifications.
Return a list of persistent_notifications.
def websocket_get_notifications( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: Mapping[str, Any], ) -> None: """Return a list of persistent_notifications.""" connection.send_message( websocket_api.result_message( msg["id"], [ { key: data[key] for key in ( ATTR_NOTIFICATION_ID, ATTR_MESSAGE, ATTR_STATUS, ATTR_TITLE, ATTR_CREATED_AT, ) } for data in hass.data[DOMAIN]["notifications"].values() ], ) )
[ "def", "websocket_get_notifications", "(", "hass", ":", "HomeAssistant", ",", "connection", ":", "websocket_api", ".", "ActiveConnection", ",", "msg", ":", "Mapping", "[", "str", ",", "Any", "]", ",", ")", "->", "None", ":", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "[", "{", "key", ":", "data", "[", "key", "]", "for", "key", "in", "(", "ATTR_NOTIFICATION_ID", ",", "ATTR_MESSAGE", ",", "ATTR_STATUS", ",", "ATTR_TITLE", ",", "ATTR_CREATED_AT", ",", ")", "}", "for", "data", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"notifications\"", "]", ".", "values", "(", ")", "]", ",", ")", ")" ]
[ 201, 0 ]
[ 224, 5 ]
python
en
['en', 'en', 'en']
True
_TemplateAttribute.__init__
( self, entity: Entity, attribute: str, template: Template, validator: Callable[[Any], Any] = None, on_update: Optional[Callable[[Any], None]] = None, none_on_template_error: Optional[bool] = False, )
Template attribute.
Template attribute.
def __init__( self, entity: Entity, attribute: str, template: Template, validator: Callable[[Any], Any] = None, on_update: Optional[Callable[[Any], None]] = None, none_on_template_error: Optional[bool] = False, ): """Template attribute.""" self._entity = entity self._attribute = attribute self.template = template self.validator = validator self.on_update = on_update self.async_update = None self.none_on_template_error = none_on_template_error
[ "def", "__init__", "(", "self", ",", "entity", ":", "Entity", ",", "attribute", ":", "str", ",", "template", ":", "Template", ",", "validator", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", "=", "None", ",", "on_update", ":", "Optional", "[", "Callable", "[", "[", "Any", "]", ",", "None", "]", "]", "=", "None", ",", "none_on_template_error", ":", "Optional", "[", "bool", "]", "=", "False", ",", ")", ":", "self", ".", "_entity", "=", "entity", "self", ".", "_attribute", "=", "attribute", "self", ".", "template", "=", "template", "self", ".", "validator", "=", "validator", "self", ".", "on_update", "=", "on_update", "self", ".", "async_update", "=", "None", "self", ".", "none_on_template_error", "=", "none_on_template_error" ]
[ 26, 4 ]
[ 42, 60 ]
python
en
['en', 'co', 'en']
False
_TemplateAttribute.async_setup
(self)
Config update path for the attribute.
Config update path for the attribute.
def async_setup(self): """Config update path for the attribute.""" if self.on_update: return if not hasattr(self._entity, self._attribute): raise AttributeError(f"Attribute '{self._attribute}' does not exist.") self.on_update = self._default_update
[ "def", "async_setup", "(", "self", ")", ":", "if", "self", ".", "on_update", ":", "return", "if", "not", "hasattr", "(", "self", ".", "_entity", ",", "self", ".", "_attribute", ")", ":", "raise", "AttributeError", "(", "f\"Attribute '{self._attribute}' does not exist.\"", ")", "self", ".", "on_update", "=", "self", ".", "_default_update" ]
[ 45, 4 ]
[ 53, 45 ]
python
en
['en', 'en', 'en']
True
_TemplateAttribute.handle_result
( self, event: Optional[Event], template: Template, last_result: Union[str, None, TemplateError], result: Union[str, TemplateError], )
Handle a template result event callback.
Handle a template result event callback.
def handle_result( self, event: Optional[Event], template: Template, last_result: Union[str, None, TemplateError], result: Union[str, TemplateError], ) -> None: """Handle a template result event callback.""" if isinstance(result, TemplateError): _LOGGER.error( "TemplateError('%s') " "while processing template '%s' " "for attribute '%s' in entity '%s'", result, self.template, self._attribute, self._entity.entity_id, ) if self.none_on_template_error: self._default_update(result) else: self.on_update(result) return if not self.validator: self.on_update(result) return try: validated = self.validator(result) except vol.Invalid as ex: _LOGGER.error( "Error validating template result '%s' " "from template '%s' " "for attribute '%s' in entity %s " "validation message '%s'", result, self.template, self._attribute, self._entity.entity_id, ex.msg, ) self.on_update(None) return self.on_update(validated) return
[ "def", "handle_result", "(", "self", ",", "event", ":", "Optional", "[", "Event", "]", ",", "template", ":", "Template", ",", "last_result", ":", "Union", "[", "str", ",", "None", ",", "TemplateError", "]", ",", "result", ":", "Union", "[", "str", ",", "TemplateError", "]", ",", ")", "->", "None", ":", "if", "isinstance", "(", "result", ",", "TemplateError", ")", ":", "_LOGGER", ".", "error", "(", "\"TemplateError('%s') \"", "\"while processing template '%s' \"", "\"for attribute '%s' in entity '%s'\"", ",", "result", ",", "self", ".", "template", ",", "self", ".", "_attribute", ",", "self", ".", "_entity", ".", "entity_id", ",", ")", "if", "self", ".", "none_on_template_error", ":", "self", ".", "_default_update", "(", "result", ")", "else", ":", "self", ".", "on_update", "(", "result", ")", "return", "if", "not", "self", ".", "validator", ":", "self", ".", "on_update", "(", "result", ")", "return", "try", ":", "validated", "=", "self", ".", "validator", "(", "result", ")", "except", "vol", ".", "Invalid", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Error validating template result '%s' \"", "\"from template '%s' \"", "\"for attribute '%s' in entity %s \"", "\"validation message '%s'\"", ",", "result", ",", "self", ".", "template", ",", "self", ".", "_attribute", ",", "self", ".", "_entity", ".", "entity_id", ",", "ex", ".", "msg", ",", ")", "self", ".", "on_update", "(", "None", ")", "return", "self", ".", "on_update", "(", "validated", ")", "return" ]
[ 61, 4 ]
[ 107, 14 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.__init__
( self, *, availability_template=None, icon_template=None, entity_picture_template=None, attribute_templates=None, )
Template Entity.
Template Entity.
def __init__( self, *, availability_template=None, icon_template=None, entity_picture_template=None, attribute_templates=None, ): """Template Entity.""" self._template_attrs = {} self._async_update = None self._attribute_templates = attribute_templates self._attributes = {} self._availability_template = availability_template self._available = True self._icon_template = icon_template self._entity_picture_template = entity_picture_template self._icon = None self._entity_picture = None self._self_ref_update_count = 0
[ "def", "__init__", "(", "self", ",", "*", ",", "availability_template", "=", "None", ",", "icon_template", "=", "None", ",", "entity_picture_template", "=", "None", ",", "attribute_templates", "=", "None", ",", ")", ":", "self", ".", "_template_attrs", "=", "{", "}", "self", ".", "_async_update", "=", "None", "self", ".", "_attribute_templates", "=", "attribute_templates", "self", ".", "_attributes", "=", "{", "}", "self", ".", "_availability_template", "=", "availability_template", "self", ".", "_available", "=", "True", "self", ".", "_icon_template", "=", "icon_template", "self", ".", "_entity_picture_template", "=", "entity_picture_template", "self", ".", "_icon", "=", "None", "self", ".", "_entity_picture", "=", "None", "self", ".", "_self_ref_update_count", "=", "0" ]
[ 113, 4 ]
[ 132, 39 ]
python
en
['en', 'en', 'en']
False
TemplateEntity.should_poll
(self)
No polling needed.
No polling needed.
def should_poll(self): """No polling needed.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 135, 4 ]
[ 137, 20 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.available
(self)
Return if the device is available.
Return if the device is available.
def available(self) -> bool: """Return if the device is available.""" return self._available
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_available" ]
[ 155, 4 ]
[ 157, 30 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.icon
(self)
Return the icon to use in the frontend, if any.
Return the icon to use in the frontend, if any.
def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 160, 4 ]
[ 162, 25 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.entity_picture
(self)
Return the entity_picture to use in the frontend, if any.
Return the entity_picture to use in the frontend, if any.
def entity_picture(self): """Return the entity_picture to use in the frontend, if any.""" return self._entity_picture
[ "def", "entity_picture", "(", "self", ")", ":", "return", "self", ".", "_entity_picture" ]
[ 165, 4 ]
[ 167, 35 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return self._attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_attributes" ]
[ 170, 4 ]
[ 172, 31 ]
python
en
['en', 'en', 'en']
True
TemplateEntity._add_attribute_template
(self, attribute_key, attribute_template)
Create a template tracker for the attribute.
Create a template tracker for the attribute.
def _add_attribute_template(self, attribute_key, attribute_template): """Create a template tracker for the attribute.""" def _update_attribute(result): attr_result = None if isinstance(result, TemplateError) else result self._attributes[attribute_key] = attr_result self.add_template_attribute( attribute_key, attribute_template, None, _update_attribute )
[ "def", "_add_attribute_template", "(", "self", ",", "attribute_key", ",", "attribute_template", ")", ":", "def", "_update_attribute", "(", "result", ")", ":", "attr_result", "=", "None", "if", "isinstance", "(", "result", ",", "TemplateError", ")", "else", "result", "self", ".", "_attributes", "[", "attribute_key", "]", "=", "attr_result", "self", ".", "add_template_attribute", "(", "attribute_key", ",", "attribute_template", ",", "None", ",", "_update_attribute", ")" ]
[ 175, 4 ]
[ 184, 9 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.add_template_attribute
( self, attribute: str, template: Template, validator: Callable[[Any], Any] = None, on_update: Optional[Callable[[Any], None]] = None, none_on_template_error: bool = False, )
Call in the constructor to add a template linked to a attribute. Parameters ---------- attribute The name of the attribute to link to. This attribute must exist unless a custom on_update method is supplied. template The template to calculate. validator Validator function to parse the result and ensure it's valid. on_update Called to store the template result rather than storing it the supplied attribute. Passed the result of the validator, or None if the template or validator resulted in an error.
Call in the constructor to add a template linked to a attribute.
def add_template_attribute( self, attribute: str, template: Template, validator: Callable[[Any], Any] = None, on_update: Optional[Callable[[Any], None]] = None, none_on_template_error: bool = False, ) -> None: """ Call in the constructor to add a template linked to a attribute. Parameters ---------- attribute The name of the attribute to link to. This attribute must exist unless a custom on_update method is supplied. template The template to calculate. validator Validator function to parse the result and ensure it's valid. on_update Called to store the template result rather than storing it the supplied attribute. Passed the result of the validator, or None if the template or validator resulted in an error. """ attribute = _TemplateAttribute( self, attribute, template, validator, on_update, none_on_template_error ) self._template_attrs.setdefault(template, []) self._template_attrs[template].append(attribute)
[ "def", "add_template_attribute", "(", "self", ",", "attribute", ":", "str", ",", "template", ":", "Template", ",", "validator", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", "=", "None", ",", "on_update", ":", "Optional", "[", "Callable", "[", "[", "Any", "]", ",", "None", "]", "]", "=", "None", ",", "none_on_template_error", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "attribute", "=", "_TemplateAttribute", "(", "self", ",", "attribute", ",", "template", ",", "validator", ",", "on_update", ",", "none_on_template_error", ")", "self", ".", "_template_attrs", ".", "setdefault", "(", "template", ",", "[", "]", ")", "self", ".", "_template_attrs", "[", "template", "]", ".", "append", "(", "attribute", ")" ]
[ 186, 4 ]
[ 216, 56 ]
python
en
['en', 'error', 'th']
False
TemplateEntity._handle_results
( self, event: Optional[Event], updates: List[TrackTemplateResult], )
Call back the results to the attributes.
Call back the results to the attributes.
def _handle_results( self, event: Optional[Event], updates: List[TrackTemplateResult], ) -> None: """Call back the results to the attributes.""" if event: self.async_set_context(event.context) entity_id = event and event.data.get(ATTR_ENTITY_ID) if entity_id and entity_id == self.entity_id: self._self_ref_update_count += 1 else: self._self_ref_update_count = 0 if self._self_ref_update_count > len(self._template_attrs): for update in updates: _LOGGER.warning( "Template loop detected while processing event: %s, skipping template render for Template[%s]", event, update.template.template, ) return for update in updates: for attr in self._template_attrs[update.template]: attr.handle_result( event, update.template, update.last_result, update.result ) self.async_write_ha_state()
[ "def", "_handle_results", "(", "self", ",", "event", ":", "Optional", "[", "Event", "]", ",", "updates", ":", "List", "[", "TrackTemplateResult", "]", ",", ")", "->", "None", ":", "if", "event", ":", "self", ".", "async_set_context", "(", "event", ".", "context", ")", "entity_id", "=", "event", "and", "event", ".", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "if", "entity_id", "and", "entity_id", "==", "self", ".", "entity_id", ":", "self", ".", "_self_ref_update_count", "+=", "1", "else", ":", "self", ".", "_self_ref_update_count", "=", "0", "if", "self", ".", "_self_ref_update_count", ">", "len", "(", "self", ".", "_template_attrs", ")", ":", "for", "update", "in", "updates", ":", "_LOGGER", ".", "warning", "(", "\"Template loop detected while processing event: %s, skipping template render for Template[%s]\"", ",", "event", ",", "update", ".", "template", ".", "template", ",", ")", "return", "for", "update", "in", "updates", ":", "for", "attr", "in", "self", ".", "_template_attrs", "[", "update", ".", "template", "]", ":", "attr", ".", "handle_result", "(", "event", ",", "update", ".", "template", ",", "update", ".", "last_result", ",", "update", ".", "result", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 219, 4 ]
[ 251, 35 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.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) -> None: """Run when entity about to be added to hass.""" if self._availability_template is not None: self.add_template_attribute( "_available", self._availability_template, None, self._update_available ) if self._attribute_templates is not None: for key, value in self._attribute_templates.items(): self._add_attribute_template(key, value) if self._icon_template is not None: self.add_template_attribute( "_icon", self._icon_template, vol.Or(cv.whitespace, cv.icon) ) if self._entity_picture_template is not None: self.add_template_attribute( "_entity_picture", self._entity_picture_template ) if self.hass.state == CoreState.running: await self._async_template_startup() return self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, self._async_template_startup )
[ "async", "def", "async_added_to_hass", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_availability_template", "is", "not", "None", ":", "self", ".", "add_template_attribute", "(", "\"_available\"", ",", "self", ".", "_availability_template", ",", "None", ",", "self", ".", "_update_available", ")", "if", "self", ".", "_attribute_templates", "is", "not", "None", ":", "for", "key", ",", "value", "in", "self", ".", "_attribute_templates", ".", "items", "(", ")", ":", "self", ".", "_add_attribute_template", "(", "key", ",", "value", ")", "if", "self", ".", "_icon_template", "is", "not", "None", ":", "self", ".", "add_template_attribute", "(", "\"_icon\"", ",", "self", ".", "_icon_template", ",", "vol", ".", "Or", "(", "cv", ".", "whitespace", ",", "cv", ".", "icon", ")", ")", "if", "self", ".", "_entity_picture_template", "is", "not", "None", ":", "self", ".", "add_template_attribute", "(", "\"_entity_picture\"", ",", "self", ".", "_entity_picture_template", ")", "if", "self", ".", "hass", ".", "state", "==", "CoreState", ".", "running", ":", "await", "self", ".", "_async_template_startup", "(", ")", "return", "self", ".", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_START", ",", "self", ".", "_async_template_startup", ")" ]
[ 267, 4 ]
[ 290, 9 ]
python
en
['en', 'en', 'en']
True
TemplateEntity.async_update
(self)
Call for forced update.
Call for forced update.
async def async_update(self) -> None: """Call for forced update.""" self._async_update()
[ "async", "def", "async_update", "(", "self", ")", "->", "None", ":", "self", ".", "_async_update", "(", ")" ]
[ 292, 4 ]
[ 294, 28 ]
python
en
['en', 'en', 'en']
True
KeywordMessage.__init__
(self, fmt: Any, args: Any, kwargs: Mapping[str, Any])
Initialize a new KeywordMessage object.
Initialize a new KeywordMessage object.
def __init__(self, fmt: Any, args: Any, kwargs: Mapping[str, Any]) -> None: """Initialize a new KeywordMessage object.""" self._fmt = fmt self._args = args self._kwargs = kwargs
[ "def", "__init__", "(", "self", ",", "fmt", ":", "Any", ",", "args", ":", "Any", ",", "kwargs", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "self", ".", "_fmt", "=", "fmt", "self", ".", "_args", "=", "args", "self", ".", "_kwargs", "=", "kwargs" ]
[ 13, 4 ]
[ 17, 29 ]
python
en
['en', 'en', 'en']
True
KeywordMessage.__str__
(self)
Convert the object to a string for logging.
Convert the object to a string for logging.
def __str__(self) -> str: """Convert the object to a string for logging.""" return str(self._fmt).format(*self._args, **self._kwargs)
[ "def", "__str__", "(", "self", ")", "->", "str", ":", "return", "str", "(", "self", ".", "_fmt", ")", ".", "format", "(", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
[ 19, 4 ]
[ 21, 65 ]
python
en
['en', 'en', 'en']
True
KeywordStyleAdapter.__init__
( self, logger: logging.Logger, extra: Optional[Mapping[str, Any]] = None )
Initialize a new StyleAdapter for the provided logger.
Initialize a new StyleAdapter for the provided logger.
def __init__( self, logger: logging.Logger, extra: Optional[Mapping[str, Any]] = None ) -> None: """Initialize a new StyleAdapter for the provided logger.""" super().__init__(logger, extra or {})
[ "def", "__init__", "(", "self", ",", "logger", ":", "logging", ".", "Logger", ",", "extra", ":", "Optional", "[", "Mapping", "[", "str", ",", "Any", "]", "]", "=", "None", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "logger", ",", "extra", "or", "{", "}", ")" ]
[ 27, 4 ]
[ 31, 45 ]
python
en
['en', 'en', 'en']
True
KeywordStyleAdapter.log
(self, level: int, msg: Any, *args: Any, **kwargs: Any)
Log the message provided at the appropriate level.
Log the message provided at the appropriate level.
def log(self, level: int, msg: Any, *args: Any, **kwargs: Any) -> None: """Log the message provided at the appropriate level.""" if self.isEnabledFor(level): msg, log_kwargs = self.process(msg, kwargs) self.logger._log( # pylint: disable=protected-access level, KeywordMessage(msg, args, kwargs), (), **log_kwargs )
[ "def", "log", "(", "self", ",", "level", ":", "int", ",", "msg", ":", "Any", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "isEnabledFor", "(", "level", ")", ":", "msg", ",", "log_kwargs", "=", "self", ".", "process", "(", "msg", ",", "kwargs", ")", "self", ".", "logger", ".", "_log", "(", "# pylint: disable=protected-access", "level", ",", "KeywordMessage", "(", "msg", ",", "args", ",", "kwargs", ")", ",", "(", ")", ",", "*", "*", "log_kwargs", ")" ]
[ 33, 4 ]
[ 39, 13 ]
python
en
['en', 'en', 'en']
True
KeywordStyleAdapter.process
( self, msg: Any, kwargs: MutableMapping[str, Any] )
Process the keyword args in preparation for logging.
Process the keyword args in preparation for logging.
def process( self, msg: Any, kwargs: MutableMapping[str, Any] ) -> Tuple[Any, MutableMapping[str, Any]]: """Process the keyword args in preparation for logging.""" return ( msg, { k: kwargs[k] for k in inspect.getfullargspec( self.logger._log # pylint: disable=protected-access ).args[1:] if k in kwargs }, )
[ "def", "process", "(", "self", ",", "msg", ":", "Any", ",", "kwargs", ":", "MutableMapping", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Any", ",", "MutableMapping", "[", "str", ",", "Any", "]", "]", ":", "return", "(", "msg", ",", "{", "k", ":", "kwargs", "[", "k", "]", "for", "k", "in", "inspect", ".", "getfullargspec", "(", "self", ".", "logger", ".", "_log", "# pylint: disable=protected-access", ")", ".", "args", "[", "1", ":", "]", "if", "k", "in", "kwargs", "}", ",", ")" ]
[ 41, 4 ]
[ 54, 9 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the oemthermostat platform.
Set up the oemthermostat platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the oemthermostat platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) try: therm = Thermostat(host, port=port, username=username, password=password) except (ValueError, AssertionError, requests.RequestException): return False add_entities((ThermostatDevice(therm, name),), True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "host", "=", "config", ".", "get", "(", "CONF_HOST", ")", "port", "=", "config", ".", "get", "(", "CONF_PORT", ")", "username", "=", "config", ".", "get", "(", "CONF_USERNAME", ")", "password", "=", "config", ".", "get", "(", "CONF_PASSWORD", ")", "try", ":", "therm", "=", "Thermostat", "(", "host", ",", "port", "=", "port", ",", "username", "=", "username", ",", "password", "=", "password", ")", "except", "(", "ValueError", ",", "AssertionError", ",", "requests", ".", "RequestException", ")", ":", "return", "False", "add_entities", "(", "(", "ThermostatDevice", "(", "therm", ",", "name", ")", ",", ")", ",", "True", ")" ]
[ 40, 0 ]
[ 53, 56 ]
python
en
['en', 'da', 'en']
True
ThermostatDevice.__init__
(self, thermostat, name)
Initialize the device.
Initialize the device.
def __init__(self, thermostat, name): """Initialize the device.""" self._name = name self.thermostat = thermostat # set up internal state varS self._state = None self._temperature = None self._setpoint = None self._mode = None
[ "def", "__init__", "(", "self", ",", "thermostat", ",", "name", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "thermostat", "=", "thermostat", "# set up internal state varS", "self", ".", "_state", "=", "None", "self", ".", "_temperature", "=", "None", "self", ".", "_setpoint", "=", "None", "self", ".", "_mode", "=", "None" ]
[ 59, 4 ]
[ 68, 25 ]
python
en
['en', 'en', 'en']
True
ThermostatDevice.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_FLAGS" ]
[ 71, 4 ]
[ 73, 28 ]
python
en
['en', 'en', 'en']
True
ThermostatDevice.hvac_mode
(self)
Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*.
Return hvac operation ie. heat, cool mode.
def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self._mode == 2: return HVAC_MODE_HEAT if self._mode == 1: return HVAC_MODE_AUTO return HVAC_MODE_OFF
[ "def", "hvac_mode", "(", "self", ")", ":", "if", "self", ".", "_mode", "==", "2", ":", "return", "HVAC_MODE_HEAT", "if", "self", ".", "_mode", "==", "1", ":", "return", "HVAC_MODE_AUTO", "return", "HVAC_MODE_OFF" ]
[ 76, 4 ]
[ 85, 28 ]
python
bg
['en', 'bg', 'bg']
True
ThermostatDevice.hvac_modes
(self)
Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES.
Return the list of available hvac operation modes.
def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return SUPPORT_HVAC
[ "def", "hvac_modes", "(", "self", ")", ":", "return", "SUPPORT_HVAC" ]
[ 88, 4 ]
[ 93, 27 ]
python
en
['en', 'en', 'en']
True
ThermostatDevice.name
(self)
Return the name of this Thermostat.
Return the name of this Thermostat.
def name(self): """Return the name of this Thermostat.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 96, 4 ]
[ 98, 25 ]
python
en
['en', 'en', 'en']
True
ThermostatDevice.temperature_unit
(self)
Return the unit of measurement used by the platform.
Return the unit of measurement used by the platform.
def temperature_unit(self): """Return the unit of measurement used by the platform.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "TEMP_CELSIUS" ]
[ 101, 4 ]
[ 103, 27 ]
python
en
['en', 'en', 'en']
True
ThermostatDevice.hvac_action
(self)
Return current hvac i.e. heat, cool, idle.
Return current hvac i.e. heat, cool, idle.
def hvac_action(self): """Return current hvac i.e. heat, cool, idle.""" if not self._mode: return CURRENT_HVAC_OFF if self._state: return CURRENT_HVAC_HEAT return CURRENT_HVAC_IDLE
[ "def", "hvac_action", "(", "self", ")", ":", "if", "not", "self", ".", "_mode", ":", "return", "CURRENT_HVAC_OFF", "if", "self", ".", "_state", ":", "return", "CURRENT_HVAC_HEAT", "return", "CURRENT_HVAC_IDLE" ]
[ 106, 4 ]
[ 112, 32 ]
python
en
['en', 'bg', 'en']
True
ThermostatDevice.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self): """Return the current temperature.""" return self._temperature
[ "def", "current_temperature", "(", "self", ")", ":", "return", "self", ".", "_temperature" ]
[ 115, 4 ]
[ 117, 32 ]
python
en
['en', 'la', 'en']
True
ThermostatDevice.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self): """Return the temperature we try to reach.""" return self._setpoint
[ "def", "target_temperature", "(", "self", ")", ":", "return", "self", ".", "_setpoint" ]
[ 120, 4 ]
[ 122, 29 ]
python
en
['en', 'en', 'en']
True
ThermostatDevice.set_hvac_mode
(self, hvac_mode)
Set new target hvac mode.
Set new target hvac mode.
def set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_AUTO: self.thermostat.mode = 1 elif hvac_mode == HVAC_MODE_HEAT: self.thermostat.mode = 2 elif hvac_mode == HVAC_MODE_OFF: self.thermostat.mode = 0
[ "def", "set_hvac_mode", "(", "self", ",", "hvac_mode", ")", ":", "if", "hvac_mode", "==", "HVAC_MODE_AUTO", ":", "self", ".", "thermostat", ".", "mode", "=", "1", "elif", "hvac_mode", "==", "HVAC_MODE_HEAT", ":", "self", ".", "thermostat", ".", "mode", "=", "2", "elif", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "self", ".", "thermostat", ".", "mode", "=", "0" ]
[ 124, 4 ]
[ 131, 36 ]
python
da
['da', 'su', 'en']
False
ThermostatDevice.set_temperature
(self, **kwargs)
Set the temperature.
Set the temperature.
def set_temperature(self, **kwargs): """Set the temperature.""" temp = kwargs.get(ATTR_TEMPERATURE) self.thermostat.setpoint = temp
[ "def", "set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "temp", "=", "kwargs", ".", "get", "(", "ATTR_TEMPERATURE", ")", "self", ".", "thermostat", ".", "setpoint", "=", "temp" ]
[ 133, 4 ]
[ 136, 39 ]
python
en
['en', 'la', 'en']
True
ThermostatDevice.update
(self)
Update local state.
Update local state.
def update(self): """Update local state.""" self._setpoint = self.thermostat.setpoint self._temperature = self.thermostat.temperature self._state = self.thermostat.state self._mode = self.thermostat.mode
[ "def", "update", "(", "self", ")", ":", "self", ".", "_setpoint", "=", "self", ".", "thermostat", ".", "setpoint", "self", ".", "_temperature", "=", "self", ".", "thermostat", ".", "temperature", "self", ".", "_state", "=", "self", ".", "thermostat", ".", "state", "self", ".", "_mode", "=", "self", ".", "thermostat", ".", "mode" ]
[ 138, 4 ]
[ 143, 41 ]
python
en
['en', 'co', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Osram Lightify lights.
Set up the Osram Lightify lights.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Osram Lightify lights.""" host = config[CONF_HOST] try: bridge = Lightify(host, log_level=logging.NOTSET) except OSError as err: _LOGGER.exception("Error connecting to bridge: %s due to: %s", host, err) return setup_bridge(bridge, add_entities, config)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "host", "=", "config", "[", "CONF_HOST", "]", "try", ":", "bridge", "=", "Lightify", "(", "host", ",", "log_level", "=", "logging", ".", "NOTSET", ")", "except", "OSError", "as", "err", ":", "_LOGGER", ".", "exception", "(", "\"Error connecting to bridge: %s due to: %s\"", ",", "host", ",", "err", ")", "return", "setup_bridge", "(", "bridge", ",", "add_entities", ",", "config", ")" ]
[ 70, 0 ]
[ 79, 46 ]
python
en
['en', 'ky', 'en']
True
setup_bridge
(bridge, add_entities, config)
Set up the Lightify bridge.
Set up the Lightify bridge.
def setup_bridge(bridge, add_entities, config): """Set up the Lightify bridge.""" lights = {} groups = {} groups_last_updated = [0] def update_lights(): """Update the lights objects with the latest info from the bridge.""" try: new_lights = bridge.update_all_light_status( config[CONF_INTERVAL_LIGHTIFY_STATUS] ) lights_changed = bridge.lights_changed() except TimeoutError: _LOGGER.error("Timeout during updating of lights") return 0 except OSError: _LOGGER.error("OSError during updating of lights") return 0 if new_lights and config[CONF_ALLOW_LIGHTIFY_NODES]: new_entities = [] for addr, light in new_lights.items(): if ( light.devicetype().name == "SENSOR" and not config[CONF_ALLOW_LIGHTIFY_SENSORS] ) or ( light.devicetype().name == "SWITCH" and not config[CONF_ALLOW_LIGHTIFY_SWITCHES] ): continue if addr not in lights: osram_light = OsramLightifyLight( light, update_lights, lights_changed ) lights[addr] = osram_light new_entities.append(osram_light) else: lights[addr].update_luminary(light) add_entities(new_entities) return lights_changed def update_groups(): """Update the groups objects with the latest info from the bridge.""" lights_changed = update_lights() try: bridge.update_scene_list(config[CONF_INTERVAL_LIGHTIFY_CONF]) new_groups = bridge.update_group_list(config[CONF_INTERVAL_LIGHTIFY_CONF]) groups_updated = bridge.groups_updated() except TimeoutError: _LOGGER.error("Timeout during updating of scenes/groups") return 0 except OSError: _LOGGER.error("OSError during updating of scenes/groups") return 0 if new_groups: new_groups = {group.idx(): group for group in new_groups.values()} new_entities = [] for idx, group in new_groups.items(): if idx not in groups: osram_group = OsramLightifyGroup( group, update_groups, groups_updated ) groups[idx] = osram_group new_entities.append(osram_group) else: groups[idx].update_luminary(group) add_entities(new_entities) if groups_updated > groups_last_updated[0]: groups_last_updated[0] = groups_updated for idx, osram_group in groups.items(): if idx not in new_groups: osram_group.update_static_attributes() return max(lights_changed, groups_updated) update_lights() if config[CONF_ALLOW_LIGHTIFY_GROUPS]: update_groups()
[ "def", "setup_bridge", "(", "bridge", ",", "add_entities", ",", "config", ")", ":", "lights", "=", "{", "}", "groups", "=", "{", "}", "groups_last_updated", "=", "[", "0", "]", "def", "update_lights", "(", ")", ":", "\"\"\"Update the lights objects with the latest info from the bridge.\"\"\"", "try", ":", "new_lights", "=", "bridge", ".", "update_all_light_status", "(", "config", "[", "CONF_INTERVAL_LIGHTIFY_STATUS", "]", ")", "lights_changed", "=", "bridge", ".", "lights_changed", "(", ")", "except", "TimeoutError", ":", "_LOGGER", ".", "error", "(", "\"Timeout during updating of lights\"", ")", "return", "0", "except", "OSError", ":", "_LOGGER", ".", "error", "(", "\"OSError during updating of lights\"", ")", "return", "0", "if", "new_lights", "and", "config", "[", "CONF_ALLOW_LIGHTIFY_NODES", "]", ":", "new_entities", "=", "[", "]", "for", "addr", ",", "light", "in", "new_lights", ".", "items", "(", ")", ":", "if", "(", "light", ".", "devicetype", "(", ")", ".", "name", "==", "\"SENSOR\"", "and", "not", "config", "[", "CONF_ALLOW_LIGHTIFY_SENSORS", "]", ")", "or", "(", "light", ".", "devicetype", "(", ")", ".", "name", "==", "\"SWITCH\"", "and", "not", "config", "[", "CONF_ALLOW_LIGHTIFY_SWITCHES", "]", ")", ":", "continue", "if", "addr", "not", "in", "lights", ":", "osram_light", "=", "OsramLightifyLight", "(", "light", ",", "update_lights", ",", "lights_changed", ")", "lights", "[", "addr", "]", "=", "osram_light", "new_entities", ".", "append", "(", "osram_light", ")", "else", ":", "lights", "[", "addr", "]", ".", "update_luminary", "(", "light", ")", "add_entities", "(", "new_entities", ")", "return", "lights_changed", "def", "update_groups", "(", ")", ":", "\"\"\"Update the groups objects with the latest info from the bridge.\"\"\"", "lights_changed", "=", "update_lights", "(", ")", "try", ":", "bridge", ".", "update_scene_list", "(", "config", "[", "CONF_INTERVAL_LIGHTIFY_CONF", "]", ")", "new_groups", "=", "bridge", ".", "update_group_list", "(", "config", "[", "CONF_INTERVAL_LIGHTIFY_CONF", "]", ")", "groups_updated", "=", "bridge", ".", "groups_updated", "(", ")", "except", "TimeoutError", ":", "_LOGGER", ".", "error", "(", "\"Timeout during updating of scenes/groups\"", ")", "return", "0", "except", "OSError", ":", "_LOGGER", ".", "error", "(", "\"OSError during updating of scenes/groups\"", ")", "return", "0", "if", "new_groups", ":", "new_groups", "=", "{", "group", ".", "idx", "(", ")", ":", "group", "for", "group", "in", "new_groups", ".", "values", "(", ")", "}", "new_entities", "=", "[", "]", "for", "idx", ",", "group", "in", "new_groups", ".", "items", "(", ")", ":", "if", "idx", "not", "in", "groups", ":", "osram_group", "=", "OsramLightifyGroup", "(", "group", ",", "update_groups", ",", "groups_updated", ")", "groups", "[", "idx", "]", "=", "osram_group", "new_entities", ".", "append", "(", "osram_group", ")", "else", ":", "groups", "[", "idx", "]", ".", "update_luminary", "(", "group", ")", "add_entities", "(", "new_entities", ")", "if", "groups_updated", ">", "groups_last_updated", "[", "0", "]", ":", "groups_last_updated", "[", "0", "]", "=", "groups_updated", "for", "idx", ",", "osram_group", "in", "groups", ".", "items", "(", ")", ":", "if", "idx", "not", "in", "new_groups", ":", "osram_group", ".", "update_static_attributes", "(", ")", "return", "max", "(", "lights_changed", ",", "groups_updated", ")", "update_lights", "(", ")", "if", "config", "[", "CONF_ALLOW_LIGHTIFY_GROUPS", "]", ":", "update_groups", "(", ")" ]
[ 82, 0 ]
[ 167, 23 ]
python
en
['en', 'zh', 'en']
True
Luminary.__init__
(self, luminary, update_func, changed)
Initialize a Luminary Light.
Initialize a Luminary Light.
def __init__(self, luminary, update_func, changed): """Initialize a Luminary Light.""" self.update_func = update_func self._luminary = luminary self._changed = changed self._unique_id = None self._supported_features = [] self._effect_list = [] self._is_on = False self._available = True self._min_mireds = None self._max_mireds = None self._brightness = None self._color_temp = None self._rgb_color = None self._device_attributes = None self.update_static_attributes() self.update_dynamic_attributes()
[ "def", "__init__", "(", "self", ",", "luminary", ",", "update_func", ",", "changed", ")", ":", "self", ".", "update_func", "=", "update_func", "self", ".", "_luminary", "=", "luminary", "self", ".", "_changed", "=", "changed", "self", ".", "_unique_id", "=", "None", "self", ".", "_supported_features", "=", "[", "]", "self", ".", "_effect_list", "=", "[", "]", "self", ".", "_is_on", "=", "False", "self", ".", "_available", "=", "True", "self", ".", "_min_mireds", "=", "None", "self", ".", "_max_mireds", "=", "None", "self", ".", "_brightness", "=", "None", "self", ".", "_color_temp", "=", "None", "self", ".", "_rgb_color", "=", "None", "self", ".", "_device_attributes", "=", "None", "self", ".", "update_static_attributes", "(", ")", "self", ".", "update_dynamic_attributes", "(", ")" ]
[ 173, 4 ]
[ 192, 40 ]
python
en
['en', 'ny', 'it']
False
Luminary._get_unique_id
(self)
Get a unique ID (not implemented).
Get a unique ID (not implemented).
def _get_unique_id(self): """Get a unique ID (not implemented).""" raise NotImplementedError
[ "def", "_get_unique_id", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 194, 4 ]
[ 196, 33 ]
python
en
['fr', 'en', 'en']
True
Luminary._get_supported_features
(self)
Get list of supported features.
Get list of supported features.
def _get_supported_features(self): """Get list of supported features.""" features = 0 if "lum" in self._luminary.supported_features(): features = features | SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION if "temp" in self._luminary.supported_features(): features = features | SUPPORT_COLOR_TEMP | SUPPORT_TRANSITION if "rgb" in self._luminary.supported_features(): features = features | SUPPORT_COLOR | SUPPORT_TRANSITION | SUPPORT_EFFECT return features
[ "def", "_get_supported_features", "(", "self", ")", ":", "features", "=", "0", "if", "\"lum\"", "in", "self", ".", "_luminary", ".", "supported_features", "(", ")", ":", "features", "=", "features", "|", "SUPPORT_BRIGHTNESS", "|", "SUPPORT_TRANSITION", "if", "\"temp\"", "in", "self", ".", "_luminary", ".", "supported_features", "(", ")", ":", "features", "=", "features", "|", "SUPPORT_COLOR_TEMP", "|", "SUPPORT_TRANSITION", "if", "\"rgb\"", "in", "self", ".", "_luminary", ".", "supported_features", "(", ")", ":", "features", "=", "features", "|", "SUPPORT_COLOR", "|", "SUPPORT_TRANSITION", "|", "SUPPORT_EFFECT", "return", "features" ]
[ 198, 4 ]
[ 210, 23 ]
python
en
['en', 'en', 'en']
True
Luminary._get_effect_list
(self)
Get list of supported effects.
Get list of supported effects.
def _get_effect_list(self): """Get list of supported effects.""" effects = [] if "rgb" in self._luminary.supported_features(): effects.append(EFFECT_RANDOM) return effects
[ "def", "_get_effect_list", "(", "self", ")", ":", "effects", "=", "[", "]", "if", "\"rgb\"", "in", "self", ".", "_luminary", ".", "supported_features", "(", ")", ":", "effects", ".", "append", "(", "EFFECT_RANDOM", ")", "return", "effects" ]
[ 212, 4 ]
[ 218, 22 ]
python
en
['en', 'en', 'en']
True
Luminary.name
(self)
Return the name of the luminary.
Return the name of the luminary.
def name(self): """Return the name of the luminary.""" return self._luminary.name()
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_luminary", ".", "name", "(", ")" ]
[ 221, 4 ]
[ 223, 36 ]
python
en
['en', 'mi', 'en']
True
Luminary.hs_color
(self)
Return last hs color value set.
Return last hs color value set.
def hs_color(self): """Return last hs color value set.""" return color_util.color_RGB_to_hs(*self._rgb_color)
[ "def", "hs_color", "(", "self", ")", ":", "return", "color_util", ".", "color_RGB_to_hs", "(", "*", "self", ".", "_rgb_color", ")" ]
[ 226, 4 ]
[ 228, 59 ]
python
en
['es', 'fr', 'en']
False
Luminary.color_temp
(self)
Return the color temperature.
Return the color temperature.
def color_temp(self): """Return the color temperature.""" return self._color_temp
[ "def", "color_temp", "(", "self", ")", ":", "return", "self", ".", "_color_temp" ]
[ 231, 4 ]
[ 233, 31 ]
python
en
['en', 'la', 'en']
True
Luminary.brightness
(self)
Return brightness of the luminary (0..255).
Return brightness of the luminary (0..255).
def brightness(self): """Return brightness of the luminary (0..255).""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 236, 4 ]
[ 238, 31 ]
python
en
['en', 'sn', 'en']
True
Luminary.is_on
(self)
Return True if the device is on.
Return True if the device is on.
def is_on(self): """Return True if the device is on.""" return self._is_on
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_is_on" ]
[ 241, 4 ]
[ 243, 26 ]
python
en
['en', 'en', 'en']
True
Luminary.supported_features
(self)
List of supported features.
List of supported features.
def supported_features(self): """List of supported features.""" return self._supported_features
[ "def", "supported_features", "(", "self", ")", ":", "return", "self", ".", "_supported_features" ]
[ 246, 4 ]
[ 248, 39 ]
python
en
['en', 'en', 'en']
True
Luminary.effect_list
(self)
List of supported effects.
List of supported effects.
def effect_list(self): """List of supported effects.""" return self._effect_list
[ "def", "effect_list", "(", "self", ")", ":", "return", "self", ".", "_effect_list" ]
[ 251, 4 ]
[ 253, 32 ]
python
en
['en', 'en', 'en']
True
Luminary.min_mireds
(self)
Return the coldest color_temp that this light supports.
Return the coldest color_temp that this light supports.
def min_mireds(self): """Return the coldest color_temp that this light supports.""" return self._min_mireds
[ "def", "min_mireds", "(", "self", ")", ":", "return", "self", ".", "_min_mireds" ]
[ 256, 4 ]
[ 258, 31 ]
python
en
['en', 'en', 'en']
True
Luminary.max_mireds
(self)
Return the warmest color_temp that this light supports.
Return the warmest color_temp that this light supports.
def max_mireds(self): """Return the warmest color_temp that this light supports.""" return self._max_mireds
[ "def", "max_mireds", "(", "self", ")", ":", "return", "self", ".", "_max_mireds" ]
[ 261, 4 ]
[ 263, 31 ]
python
en
['en', 'en', 'en']
True
Luminary.unique_id
(self)
Return a unique ID.
Return a unique ID.
def unique_id(self): """Return a unique ID.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 266, 4 ]
[ 268, 30 ]
python
ca
['fr', 'ca', 'en']
False
Luminary.device_state_attributes
(self)
Return device specific state attributes.
Return device specific state attributes.
def device_state_attributes(self): """Return device specific state attributes.""" return self._device_attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_device_attributes" ]
[ 271, 4 ]
[ 273, 38 ]
python
en
['fr', 'en', 'en']
True
Luminary.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self): """Return True if entity is available.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 276, 4 ]
[ 278, 30 ]
python
en
['en', 'en', 'en']
True
Luminary.play_effect
(self, effect, transition)
Play selected effect.
Play selected effect.
def play_effect(self, effect, transition): """Play selected effect.""" if effect == EFFECT_RANDOM: self._rgb_color = ( random.randrange(0, 256), random.randrange(0, 256), random.randrange(0, 256), ) self._luminary.set_rgb(*self._rgb_color, transition) self._luminary.set_onoff(True) return True return False
[ "def", "play_effect", "(", "self", ",", "effect", ",", "transition", ")", ":", "if", "effect", "==", "EFFECT_RANDOM", ":", "self", ".", "_rgb_color", "=", "(", "random", ".", "randrange", "(", "0", ",", "256", ")", ",", "random", ".", "randrange", "(", "0", ",", "256", ")", ",", "random", ".", "randrange", "(", "0", ",", "256", ")", ",", ")", "self", ".", "_luminary", ".", "set_rgb", "(", "*", "self", ".", "_rgb_color", ",", "transition", ")", "self", ".", "_luminary", ".", "set_onoff", "(", "True", ")", "return", "True", "return", "False" ]
[ 280, 4 ]
[ 292, 20 ]
python
en
['en', 'en', 'en']
True
Luminary.turn_on
(self, **kwargs)
Turn the device on.
Turn the device on.
def turn_on(self, **kwargs): """Turn the device on.""" transition = int(kwargs.get(ATTR_TRANSITION, 0) * 10) if ATTR_EFFECT in kwargs: self.play_effect(kwargs[ATTR_EFFECT], transition) return if ATTR_HS_COLOR in kwargs: self._rgb_color = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR]) self._luminary.set_rgb(*self._rgb_color, transition) if ATTR_COLOR_TEMP in kwargs: self._color_temp = kwargs[ATTR_COLOR_TEMP] self._luminary.set_temperature( int(color_util.color_temperature_mired_to_kelvin(self._color_temp)), transition, ) self._is_on = True if ATTR_BRIGHTNESS in kwargs: self._brightness = kwargs[ATTR_BRIGHTNESS] self._luminary.set_luminance(int(self._brightness / 2.55), transition) else: self._luminary.set_onoff(True)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "transition", "=", "int", "(", "kwargs", ".", "get", "(", "ATTR_TRANSITION", ",", "0", ")", "*", "10", ")", "if", "ATTR_EFFECT", "in", "kwargs", ":", "self", ".", "play_effect", "(", "kwargs", "[", "ATTR_EFFECT", "]", ",", "transition", ")", "return", "if", "ATTR_HS_COLOR", "in", "kwargs", ":", "self", ".", "_rgb_color", "=", "color_util", ".", "color_hs_to_RGB", "(", "*", "kwargs", "[", "ATTR_HS_COLOR", "]", ")", "self", ".", "_luminary", ".", "set_rgb", "(", "*", "self", ".", "_rgb_color", ",", "transition", ")", "if", "ATTR_COLOR_TEMP", "in", "kwargs", ":", "self", ".", "_color_temp", "=", "kwargs", "[", "ATTR_COLOR_TEMP", "]", "self", ".", "_luminary", ".", "set_temperature", "(", "int", "(", "color_util", ".", "color_temperature_mired_to_kelvin", "(", "self", ".", "_color_temp", ")", ")", ",", "transition", ",", ")", "self", ".", "_is_on", "=", "True", "if", "ATTR_BRIGHTNESS", "in", "kwargs", ":", "self", ".", "_brightness", "=", "kwargs", "[", "ATTR_BRIGHTNESS", "]", "self", ".", "_luminary", ".", "set_luminance", "(", "int", "(", "self", ".", "_brightness", "/", "2.55", ")", ",", "transition", ")", "else", ":", "self", ".", "_luminary", ".", "set_onoff", "(", "True", ")" ]
[ 294, 4 ]
[ 317, 42 ]
python
en
['en', 'en', 'en']
True
Luminary.turn_off
(self, **kwargs)
Turn the device off.
Turn the device off.
def turn_off(self, **kwargs): """Turn the device off.""" self._is_on = False if ATTR_TRANSITION in kwargs: transition = int(kwargs[ATTR_TRANSITION] * 10) self._brightness = DEFAULT_BRIGHTNESS self._luminary.set_luminance(0, transition) else: self._luminary.set_onoff(False)
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_is_on", "=", "False", "if", "ATTR_TRANSITION", "in", "kwargs", ":", "transition", "=", "int", "(", "kwargs", "[", "ATTR_TRANSITION", "]", "*", "10", ")", "self", ".", "_brightness", "=", "DEFAULT_BRIGHTNESS", "self", ".", "_luminary", ".", "set_luminance", "(", "0", ",", "transition", ")", "else", ":", "self", ".", "_luminary", ".", "set_onoff", "(", "False", ")" ]
[ 319, 4 ]
[ 327, 43 ]
python
en
['en', 'en', 'en']
True
Luminary.update_luminary
(self, luminary)
Update internal luminary object.
Update internal luminary object.
def update_luminary(self, luminary): """Update internal luminary object.""" self._luminary = luminary self.update_static_attributes()
[ "def", "update_luminary", "(", "self", ",", "luminary", ")", ":", "self", ".", "_luminary", "=", "luminary", "self", ".", "update_static_attributes", "(", ")" ]
[ 329, 4 ]
[ 332, 39 ]
python
en
['en', 'ny', 'en']
True
Luminary.update_static_attributes
(self)
Update static attributes of the luminary.
Update static attributes of the luminary.
def update_static_attributes(self): """Update static attributes of the luminary.""" self._unique_id = self._get_unique_id() self._supported_features = self._get_supported_features() self._effect_list = self._get_effect_list() if self._supported_features & SUPPORT_COLOR_TEMP: self._min_mireds = color_util.color_temperature_kelvin_to_mired( self._luminary.max_temp() or DEFAULT_KELVIN ) self._max_mireds = color_util.color_temperature_kelvin_to_mired( self._luminary.min_temp() or DEFAULT_KELVIN )
[ "def", "update_static_attributes", "(", "self", ")", ":", "self", ".", "_unique_id", "=", "self", ".", "_get_unique_id", "(", ")", "self", ".", "_supported_features", "=", "self", ".", "_get_supported_features", "(", ")", "self", ".", "_effect_list", "=", "self", ".", "_get_effect_list", "(", ")", "if", "self", ".", "_supported_features", "&", "SUPPORT_COLOR_TEMP", ":", "self", ".", "_min_mireds", "=", "color_util", ".", "color_temperature_kelvin_to_mired", "(", "self", ".", "_luminary", ".", "max_temp", "(", ")", "or", "DEFAULT_KELVIN", ")", "self", ".", "_max_mireds", "=", "color_util", ".", "color_temperature_kelvin_to_mired", "(", "self", ".", "_luminary", ".", "min_temp", "(", ")", "or", "DEFAULT_KELVIN", ")" ]
[ 334, 4 ]
[ 345, 13 ]
python
en
['en', 'en', 'en']
True
Luminary.update_dynamic_attributes
(self)
Update dynamic attributes of the luminary.
Update dynamic attributes of the luminary.
def update_dynamic_attributes(self): """Update dynamic attributes of the luminary.""" self._is_on = self._luminary.on() self._available = self._luminary.reachable() and not self._luminary.deleted() if self._supported_features & SUPPORT_BRIGHTNESS: self._brightness = int(self._luminary.lum() * 2.55) if self._supported_features & SUPPORT_COLOR_TEMP: self._color_temp = color_util.color_temperature_kelvin_to_mired( self._luminary.temp() or DEFAULT_KELVIN ) if self._supported_features & SUPPORT_COLOR: self._rgb_color = self._luminary.rgb()
[ "def", "update_dynamic_attributes", "(", "self", ")", ":", "self", ".", "_is_on", "=", "self", ".", "_luminary", ".", "on", "(", ")", "self", ".", "_available", "=", "self", ".", "_luminary", ".", "reachable", "(", ")", "and", "not", "self", ".", "_luminary", ".", "deleted", "(", ")", "if", "self", ".", "_supported_features", "&", "SUPPORT_BRIGHTNESS", ":", "self", ".", "_brightness", "=", "int", "(", "self", ".", "_luminary", ".", "lum", "(", ")", "*", "2.55", ")", "if", "self", ".", "_supported_features", "&", "SUPPORT_COLOR_TEMP", ":", "self", ".", "_color_temp", "=", "color_util", ".", "color_temperature_kelvin_to_mired", "(", "self", ".", "_luminary", ".", "temp", "(", ")", "or", "DEFAULT_KELVIN", ")", "if", "self", ".", "_supported_features", "&", "SUPPORT_COLOR", ":", "self", ".", "_rgb_color", "=", "self", ".", "_luminary", ".", "rgb", "(", ")" ]
[ 347, 4 ]
[ 360, 50 ]
python
en
['en', 'en', 'en']
True
Luminary.update
(self)
Synchronize state with bridge.
Synchronize state with bridge.
def update(self): """Synchronize state with bridge.""" changed = self.update_func() if changed > self._changed: self._changed = changed self.update_dynamic_attributes()
[ "def", "update", "(", "self", ")", ":", "changed", "=", "self", ".", "update_func", "(", ")", "if", "changed", ">", "self", ".", "_changed", ":", "self", ".", "_changed", "=", "changed", "self", ".", "update_dynamic_attributes", "(", ")" ]
[ 362, 4 ]
[ 367, 44 ]
python
en
['en', 'en', 'en']
True
OsramLightifyLight._get_unique_id
(self)
Get a unique ID.
Get a unique ID.
def _get_unique_id(self): """Get a unique ID.""" return self._luminary.addr()
[ "def", "_get_unique_id", "(", "self", ")", ":", "return", "self", ".", "_luminary", ".", "addr", "(", ")" ]
[ 373, 4 ]
[ 375, 36 ]
python
en
['fr', 'es', 'en']
False
OsramLightifyLight.update_static_attributes
(self)
Update static attributes of the luminary.
Update static attributes of the luminary.
def update_static_attributes(self): """Update static attributes of the luminary.""" super().update_static_attributes() attrs = { "device_type": f"{self._luminary.type_id()} ({self._luminary.devicename()})", "firmware_version": self._luminary.version(), } if self._luminary.devicetype().name == "SENSOR": attrs["sensor_values"] = self._luminary.raw_values() self._device_attributes = attrs
[ "def", "update_static_attributes", "(", "self", ")", ":", "super", "(", ")", ".", "update_static_attributes", "(", ")", "attrs", "=", "{", "\"device_type\"", ":", "f\"{self._luminary.type_id()} ({self._luminary.devicename()})\"", ",", "\"firmware_version\"", ":", "self", ".", "_luminary", ".", "version", "(", ")", ",", "}", "if", "self", ".", "_luminary", ".", "devicetype", "(", ")", ".", "name", "==", "\"SENSOR\"", ":", "attrs", "[", "\"sensor_values\"", "]", "=", "self", ".", "_luminary", ".", "raw_values", "(", ")", "self", ".", "_device_attributes", "=", "attrs" ]
[ 377, 4 ]
[ 387, 39 ]
python
en
['en', 'en', 'en']
True
OsramLightifyGroup._get_unique_id
(self)
Get a unique ID for the group.
Get a unique ID for the group.
def _get_unique_id(self): """Get a unique ID for the group.""" # Actually, it's a wrong choice for a unique ID, because a combination of # lights is NOT unique (Osram Lightify allows to create different groups # with the same lights). Also a combination of lights may easily change, # but the group remains the same from the user's perspective. # It should be something like "<gateway host>-<group.idx()>" # For now keeping it as is for backward compatibility with existing # users. return f"{self._luminary.lights()}"
[ "def", "_get_unique_id", "(", "self", ")", ":", "# Actually, it's a wrong choice for a unique ID, because a combination of", "# lights is NOT unique (Osram Lightify allows to create different groups", "# with the same lights). Also a combination of lights may easily change,", "# but the group remains the same from the user's perspective.", "# It should be something like \"<gateway host>-<group.idx()>\"", "# For now keeping it as is for backward compatibility with existing", "# users.", "return", "f\"{self._luminary.lights()}\"" ]
[ 393, 4 ]
[ 402, 43 ]
python
en
['en', 'en', 'en']
True
OsramLightifyGroup._get_supported_features
(self)
Get list of supported features.
Get list of supported features.
def _get_supported_features(self): """Get list of supported features.""" features = super()._get_supported_features() if self._luminary.scenes(): features = features | SUPPORT_EFFECT return features
[ "def", "_get_supported_features", "(", "self", ")", ":", "features", "=", "super", "(", ")", ".", "_get_supported_features", "(", ")", "if", "self", ".", "_luminary", ".", "scenes", "(", ")", ":", "features", "=", "features", "|", "SUPPORT_EFFECT", "return", "features" ]
[ 404, 4 ]
[ 410, 23 ]
python
en
['en', 'en', 'en']
True
OsramLightifyGroup._get_effect_list
(self)
Get list of supported effects.
Get list of supported effects.
def _get_effect_list(self): """Get list of supported effects.""" effects = super()._get_effect_list() effects.extend(self._luminary.scenes()) return sorted(effects)
[ "def", "_get_effect_list", "(", "self", ")", ":", "effects", "=", "super", "(", ")", ".", "_get_effect_list", "(", ")", "effects", ".", "extend", "(", "self", ".", "_luminary", ".", "scenes", "(", ")", ")", "return", "sorted", "(", "effects", ")" ]
[ 412, 4 ]
[ 416, 30 ]
python
en
['en', 'en', 'en']
True
OsramLightifyGroup.play_effect
(self, effect, transition)
Play selected effect.
Play selected effect.
def play_effect(self, effect, transition): """Play selected effect.""" if super().play_effect(effect, transition): return True if effect in self._luminary.scenes(): self._luminary.activate_scene(effect) return True return False
[ "def", "play_effect", "(", "self", ",", "effect", ",", "transition", ")", ":", "if", "super", "(", ")", ".", "play_effect", "(", "effect", ",", "transition", ")", ":", "return", "True", "if", "effect", "in", "self", ".", "_luminary", ".", "scenes", "(", ")", ":", "self", ".", "_luminary", ".", "activate_scene", "(", "effect", ")", "return", "True", "return", "False" ]
[ 418, 4 ]
[ 427, 20 ]
python
en
['en', 'en', 'en']
True
OsramLightifyGroup.update_static_attributes
(self)
Update static attributes of the luminary.
Update static attributes of the luminary.
def update_static_attributes(self): """Update static attributes of the luminary.""" super().update_static_attributes() self._device_attributes = {"lights": self._luminary.light_names()}
[ "def", "update_static_attributes", "(", "self", ")", ":", "super", "(", ")", ".", "update_static_attributes", "(", ")", "self", ".", "_device_attributes", "=", "{", "\"lights\"", ":", "self", ".", "_luminary", ".", "light_names", "(", ")", "}" ]
[ 429, 4 ]
[ 432, 74 ]
python
en
['en', 'en', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the BME680 sensor.
Set up the BME680 sensor.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the BME680 sensor.""" SENSOR_TYPES[SENSOR_TEMP][1] = hass.config.units.temperature_unit name = config[CONF_NAME] sensor_handler = await hass.async_add_executor_job(_setup_bme680, config) if sensor_handler is None: return dev = [] for variable in config[CONF_MONITORED_CONDITIONS]: dev.append( BME680Sensor(sensor_handler, variable, SENSOR_TYPES[variable][1], name) ) async_add_entities(dev) return
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "SENSOR_TYPES", "[", "SENSOR_TEMP", "]", "[", "1", "]", "=", "hass", ".", "config", ".", "units", ".", "temperature_unit", "name", "=", "config", "[", "CONF_NAME", "]", "sensor_handler", "=", "await", "hass", ".", "async_add_executor_job", "(", "_setup_bme680", ",", "config", ")", "if", "sensor_handler", "is", "None", ":", "return", "dev", "=", "[", "]", "for", "variable", "in", "config", "[", "CONF_MONITORED_CONDITIONS", "]", ":", "dev", ".", "append", "(", "BME680Sensor", "(", "sensor_handler", ",", "variable", ",", "SENSOR_TYPES", "[", "variable", "]", "[", "1", "]", ",", "name", ")", ")", "async_add_entities", "(", "dev", ")", "return" ]
[ 108, 0 ]
[ 124, 10 ]
python
en
['en', 'da', 'en']
True
_setup_bme680
(config)
Set up and configure the BME680 sensor.
Set up and configure the BME680 sensor.
def _setup_bme680(config): """Set up and configure the BME680 sensor.""" sensor_handler = None sensor = None try: # pylint: disable=no-member i2c_address = config[CONF_I2C_ADDRESS] bus = SMBus(config[CONF_I2C_BUS]) sensor = bme680.BME680(i2c_address, bus) # Configure Oversampling os_lookup = { 0: bme680.OS_NONE, 1: bme680.OS_1X, 2: bme680.OS_2X, 4: bme680.OS_4X, 8: bme680.OS_8X, 16: bme680.OS_16X, } sensor.set_temperature_oversample(os_lookup[config[CONF_OVERSAMPLING_TEMP]]) sensor.set_temp_offset(config[CONF_TEMP_OFFSET]) sensor.set_humidity_oversample(os_lookup[config[CONF_OVERSAMPLING_HUM]]) sensor.set_pressure_oversample(os_lookup[config[CONF_OVERSAMPLING_PRES]]) # Configure IIR Filter filter_lookup = { 0: bme680.FILTER_SIZE_0, 1: bme680.FILTER_SIZE_1, 3: bme680.FILTER_SIZE_3, 7: bme680.FILTER_SIZE_7, 15: bme680.FILTER_SIZE_15, 31: bme680.FILTER_SIZE_31, 63: bme680.FILTER_SIZE_63, 127: bme680.FILTER_SIZE_127, } sensor.set_filter(filter_lookup[config[CONF_FILTER_SIZE]]) # Configure the Gas Heater if ( SENSOR_GAS in config[CONF_MONITORED_CONDITIONS] or SENSOR_AQ in config[CONF_MONITORED_CONDITIONS] ): sensor.set_gas_status(bme680.ENABLE_GAS_MEAS) sensor.set_gas_heater_duration(config[CONF_GAS_HEATER_DURATION]) sensor.set_gas_heater_temperature(config[CONF_GAS_HEATER_TEMP]) sensor.select_gas_heater_profile(0) else: sensor.set_gas_status(bme680.DISABLE_GAS_MEAS) except (RuntimeError, OSError): _LOGGER.error("BME680 sensor not detected at 0x%02x", i2c_address) return None sensor_handler = BME680Handler( sensor, ( SENSOR_GAS in config[CONF_MONITORED_CONDITIONS] or SENSOR_AQ in config[CONF_MONITORED_CONDITIONS] ), config[CONF_AQ_BURN_IN_TIME], config[CONF_AQ_HUM_BASELINE], config[CONF_AQ_HUM_WEIGHTING], ) sleep(0.5) # Wait for device to stabilize if not sensor_handler.sensor_data.temperature: _LOGGER.error("BME680 sensor failed to Initialize") return None return sensor_handler
[ "def", "_setup_bme680", "(", "config", ")", ":", "sensor_handler", "=", "None", "sensor", "=", "None", "try", ":", "# pylint: disable=no-member", "i2c_address", "=", "config", "[", "CONF_I2C_ADDRESS", "]", "bus", "=", "SMBus", "(", "config", "[", "CONF_I2C_BUS", "]", ")", "sensor", "=", "bme680", ".", "BME680", "(", "i2c_address", ",", "bus", ")", "# Configure Oversampling", "os_lookup", "=", "{", "0", ":", "bme680", ".", "OS_NONE", ",", "1", ":", "bme680", ".", "OS_1X", ",", "2", ":", "bme680", ".", "OS_2X", ",", "4", ":", "bme680", ".", "OS_4X", ",", "8", ":", "bme680", ".", "OS_8X", ",", "16", ":", "bme680", ".", "OS_16X", ",", "}", "sensor", ".", "set_temperature_oversample", "(", "os_lookup", "[", "config", "[", "CONF_OVERSAMPLING_TEMP", "]", "]", ")", "sensor", ".", "set_temp_offset", "(", "config", "[", "CONF_TEMP_OFFSET", "]", ")", "sensor", ".", "set_humidity_oversample", "(", "os_lookup", "[", "config", "[", "CONF_OVERSAMPLING_HUM", "]", "]", ")", "sensor", ".", "set_pressure_oversample", "(", "os_lookup", "[", "config", "[", "CONF_OVERSAMPLING_PRES", "]", "]", ")", "# Configure IIR Filter", "filter_lookup", "=", "{", "0", ":", "bme680", ".", "FILTER_SIZE_0", ",", "1", ":", "bme680", ".", "FILTER_SIZE_1", ",", "3", ":", "bme680", ".", "FILTER_SIZE_3", ",", "7", ":", "bme680", ".", "FILTER_SIZE_7", ",", "15", ":", "bme680", ".", "FILTER_SIZE_15", ",", "31", ":", "bme680", ".", "FILTER_SIZE_31", ",", "63", ":", "bme680", ".", "FILTER_SIZE_63", ",", "127", ":", "bme680", ".", "FILTER_SIZE_127", ",", "}", "sensor", ".", "set_filter", "(", "filter_lookup", "[", "config", "[", "CONF_FILTER_SIZE", "]", "]", ")", "# Configure the Gas Heater", "if", "(", "SENSOR_GAS", "in", "config", "[", "CONF_MONITORED_CONDITIONS", "]", "or", "SENSOR_AQ", "in", "config", "[", "CONF_MONITORED_CONDITIONS", "]", ")", ":", "sensor", ".", "set_gas_status", "(", "bme680", ".", "ENABLE_GAS_MEAS", ")", "sensor", ".", "set_gas_heater_duration", "(", "config", "[", "CONF_GAS_HEATER_DURATION", "]", ")", "sensor", ".", "set_gas_heater_temperature", "(", "config", "[", "CONF_GAS_HEATER_TEMP", "]", ")", "sensor", ".", "select_gas_heater_profile", "(", "0", ")", "else", ":", "sensor", ".", "set_gas_status", "(", "bme680", ".", "DISABLE_GAS_MEAS", ")", "except", "(", "RuntimeError", ",", "OSError", ")", ":", "_LOGGER", ".", "error", "(", "\"BME680 sensor not detected at 0x%02x\"", ",", "i2c_address", ")", "return", "None", "sensor_handler", "=", "BME680Handler", "(", "sensor", ",", "(", "SENSOR_GAS", "in", "config", "[", "CONF_MONITORED_CONDITIONS", "]", "or", "SENSOR_AQ", "in", "config", "[", "CONF_MONITORED_CONDITIONS", "]", ")", ",", "config", "[", "CONF_AQ_BURN_IN_TIME", "]", ",", "config", "[", "CONF_AQ_HUM_BASELINE", "]", ",", "config", "[", "CONF_AQ_HUM_WEIGHTING", "]", ",", ")", "sleep", "(", "0.5", ")", "# Wait for device to stabilize", "if", "not", "sensor_handler", ".", "sensor_data", ".", "temperature", ":", "_LOGGER", ".", "error", "(", "\"BME680 sensor failed to Initialize\"", ")", "return", "None", "return", "sensor_handler" ]
[ 127, 0 ]
[ 195, 25 ]
python
en
['en', 'pt', 'en']
True
BME680Handler.__init__
( self, sensor, gas_measurement=False, burn_in_time=300, hum_baseline=40, hum_weighting=25, )
Initialize the sensor handler.
Initialize the sensor handler.
def __init__( self, sensor, gas_measurement=False, burn_in_time=300, hum_baseline=40, hum_weighting=25, ): """Initialize the sensor handler.""" self.sensor_data = BME680Handler.SensorData() self._sensor = sensor self._gas_sensor_running = False self._hum_baseline = hum_baseline self._hum_weighting = hum_weighting self._gas_baseline = None if gas_measurement: threading.Thread( target=self._run_gas_sensor, kwargs={"burn_in_time": burn_in_time}, name="BME680Handler_run_gas_sensor", ).start() self.update(first_read=True)
[ "def", "__init__", "(", "self", ",", "sensor", ",", "gas_measurement", "=", "False", ",", "burn_in_time", "=", "300", ",", "hum_baseline", "=", "40", ",", "hum_weighting", "=", "25", ",", ")", ":", "self", ".", "sensor_data", "=", "BME680Handler", ".", "SensorData", "(", ")", "self", ".", "_sensor", "=", "sensor", "self", ".", "_gas_sensor_running", "=", "False", "self", ".", "_hum_baseline", "=", "hum_baseline", "self", ".", "_hum_weighting", "=", "hum_weighting", "self", ".", "_gas_baseline", "=", "None", "if", "gas_measurement", ":", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_run_gas_sensor", ",", "kwargs", "=", "{", "\"burn_in_time\"", ":", "burn_in_time", "}", ",", "name", "=", "\"BME680Handler_run_gas_sensor\"", ",", ")", ".", "start", "(", ")", "self", ".", "update", "(", "first_read", "=", "True", ")" ]
[ 212, 4 ]
[ 235, 36 ]
python
en
['en', 'pt', 'en']
True
BME680Handler._run_gas_sensor
(self, burn_in_time)
Calibrate the Air Quality Gas Baseline.
Calibrate the Air Quality Gas Baseline.
def _run_gas_sensor(self, burn_in_time): """Calibrate the Air Quality Gas Baseline.""" if self._gas_sensor_running: return self._gas_sensor_running = True # Pause to allow initial data read for device validation. sleep(1) start_time = monotonic() curr_time = monotonic() burn_in_data = [] _LOGGER.info( "Beginning %d second gas sensor burn in for Air Quality", burn_in_time ) while curr_time - start_time < burn_in_time: curr_time = monotonic() if self._sensor.get_sensor_data() and self._sensor.data.heat_stable: gas_resistance = self._sensor.data.gas_resistance burn_in_data.append(gas_resistance) self.sensor_data.gas_resistance = gas_resistance _LOGGER.debug( "AQ Gas Resistance Baseline reading %2f Ohms", gas_resistance ) sleep(1) _LOGGER.debug( "AQ Gas Resistance Burn In Data (Size: %d): \n\t%s", len(burn_in_data), burn_in_data, ) self._gas_baseline = sum(burn_in_data[-50:]) / 50.0 _LOGGER.info("Completed gas sensor burn in for Air Quality") _LOGGER.info("AQ Gas Resistance Baseline: %f", self._gas_baseline) while True: if self._sensor.get_sensor_data() and self._sensor.data.heat_stable: self.sensor_data.gas_resistance = self._sensor.data.gas_resistance self.sensor_data.air_quality = self._calculate_aq_score() sleep(1)
[ "def", "_run_gas_sensor", "(", "self", ",", "burn_in_time", ")", ":", "if", "self", ".", "_gas_sensor_running", ":", "return", "self", ".", "_gas_sensor_running", "=", "True", "# Pause to allow initial data read for device validation.", "sleep", "(", "1", ")", "start_time", "=", "monotonic", "(", ")", "curr_time", "=", "monotonic", "(", ")", "burn_in_data", "=", "[", "]", "_LOGGER", ".", "info", "(", "\"Beginning %d second gas sensor burn in for Air Quality\"", ",", "burn_in_time", ")", "while", "curr_time", "-", "start_time", "<", "burn_in_time", ":", "curr_time", "=", "monotonic", "(", ")", "if", "self", ".", "_sensor", ".", "get_sensor_data", "(", ")", "and", "self", ".", "_sensor", ".", "data", ".", "heat_stable", ":", "gas_resistance", "=", "self", ".", "_sensor", ".", "data", ".", "gas_resistance", "burn_in_data", ".", "append", "(", "gas_resistance", ")", "self", ".", "sensor_data", ".", "gas_resistance", "=", "gas_resistance", "_LOGGER", ".", "debug", "(", "\"AQ Gas Resistance Baseline reading %2f Ohms\"", ",", "gas_resistance", ")", "sleep", "(", "1", ")", "_LOGGER", ".", "debug", "(", "\"AQ Gas Resistance Burn In Data (Size: %d): \\n\\t%s\"", ",", "len", "(", "burn_in_data", ")", ",", "burn_in_data", ",", ")", "self", ".", "_gas_baseline", "=", "sum", "(", "burn_in_data", "[", "-", "50", ":", "]", ")", "/", "50.0", "_LOGGER", ".", "info", "(", "\"Completed gas sensor burn in for Air Quality\"", ")", "_LOGGER", ".", "info", "(", "\"AQ Gas Resistance Baseline: %f\"", ",", "self", ".", "_gas_baseline", ")", "while", "True", ":", "if", "self", ".", "_sensor", ".", "get_sensor_data", "(", ")", "and", "self", ".", "_sensor", ".", "data", ".", "heat_stable", ":", "self", ".", "sensor_data", ".", "gas_resistance", "=", "self", ".", "_sensor", ".", "data", ".", "gas_resistance", "self", ".", "sensor_data", ".", "air_quality", "=", "self", ".", "_calculate_aq_score", "(", ")", "sleep", "(", "1", ")" ]
[ 237, 4 ]
[ 277, 24 ]
python
en
['en', 'en', 'en']
True
BME680Handler.update
(self, first_read=False)
Read sensor data.
Read sensor data.
def update(self, first_read=False): """Read sensor data.""" if first_read: # Attempt first read, it almost always fails first attempt self._sensor.get_sensor_data() if self._sensor.get_sensor_data(): self.sensor_data.temperature = self._sensor.data.temperature self.sensor_data.humidity = self._sensor.data.humidity self.sensor_data.pressure = self._sensor.data.pressure
[ "def", "update", "(", "self", ",", "first_read", "=", "False", ")", ":", "if", "first_read", ":", "# Attempt first read, it almost always fails first attempt", "self", ".", "_sensor", ".", "get_sensor_data", "(", ")", "if", "self", ".", "_sensor", ".", "get_sensor_data", "(", ")", ":", "self", ".", "sensor_data", ".", "temperature", "=", "self", ".", "_sensor", ".", "data", ".", "temperature", "self", ".", "sensor_data", ".", "humidity", "=", "self", ".", "_sensor", ".", "data", ".", "humidity", "self", ".", "sensor_data", ".", "pressure", "=", "self", ".", "_sensor", ".", "data", ".", "pressure" ]
[ 279, 4 ]
[ 287, 66 ]
python
ca
['nl', 'ca', 'en']
False
BME680Handler._calculate_aq_score
(self)
Calculate the Air Quality Score.
Calculate the Air Quality Score.
def _calculate_aq_score(self): """Calculate the Air Quality Score.""" hum_baseline = self._hum_baseline hum_weighting = self._hum_weighting gas_baseline = self._gas_baseline gas_resistance = self.sensor_data.gas_resistance gas_offset = gas_baseline - gas_resistance hum = self.sensor_data.humidity hum_offset = hum - hum_baseline # Calculate hum_score as the distance from the hum_baseline. if hum_offset > 0: hum_score = ( (100 - hum_baseline - hum_offset) / (100 - hum_baseline) * hum_weighting ) else: hum_score = (hum_baseline + hum_offset) / hum_baseline * hum_weighting # Calculate gas_score as the distance from the gas_baseline. if gas_offset > 0: gas_score = (gas_resistance / gas_baseline) * (100 - hum_weighting) else: gas_score = 100 - hum_weighting # Calculate air quality score. return hum_score + gas_score
[ "def", "_calculate_aq_score", "(", "self", ")", ":", "hum_baseline", "=", "self", ".", "_hum_baseline", "hum_weighting", "=", "self", ".", "_hum_weighting", "gas_baseline", "=", "self", ".", "_gas_baseline", "gas_resistance", "=", "self", ".", "sensor_data", ".", "gas_resistance", "gas_offset", "=", "gas_baseline", "-", "gas_resistance", "hum", "=", "self", ".", "sensor_data", ".", "humidity", "hum_offset", "=", "hum", "-", "hum_baseline", "# Calculate hum_score as the distance from the hum_baseline.", "if", "hum_offset", ">", "0", ":", "hum_score", "=", "(", "(", "100", "-", "hum_baseline", "-", "hum_offset", ")", "/", "(", "100", "-", "hum_baseline", ")", "*", "hum_weighting", ")", "else", ":", "hum_score", "=", "(", "hum_baseline", "+", "hum_offset", ")", "/", "hum_baseline", "*", "hum_weighting", "# Calculate gas_score as the distance from the gas_baseline.", "if", "gas_offset", ">", "0", ":", "gas_score", "=", "(", "gas_resistance", "/", "gas_baseline", ")", "*", "(", "100", "-", "hum_weighting", ")", "else", ":", "gas_score", "=", "100", "-", "hum_weighting", "# Calculate air quality score.", "return", "hum_score", "+", "gas_score" ]
[ 289, 4 ]
[ 316, 36 ]
python
en
['en', 'en', 'en']
True
BME680Sensor.__init__
(self, bme680_client, sensor_type, temp_unit, name)
Initialize the sensor.
Initialize the sensor.
def __init__(self, bme680_client, sensor_type, temp_unit, name): """Initialize the sensor.""" self.client_name = name self._name = SENSOR_TYPES[sensor_type][0] self.bme680_client = bme680_client self.temp_unit = temp_unit self.type = sensor_type self._state = None self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
[ "def", "__init__", "(", "self", ",", "bme680_client", ",", "sensor_type", ",", "temp_unit", ",", "name", ")", ":", "self", ".", "client_name", "=", "name", "self", ".", "_name", "=", "SENSOR_TYPES", "[", "sensor_type", "]", "[", "0", "]", "self", ".", "bme680_client", "=", "bme680_client", "self", ".", "temp_unit", "=", "temp_unit", "self", ".", "type", "=", "sensor_type", "self", ".", "_state", "=", "None", "self", ".", "_unit_of_measurement", "=", "SENSOR_TYPES", "[", "sensor_type", "]", "[", "1", "]" ]
[ 322, 4 ]
[ 330, 64 ]
python
en
['en', 'en', 'en']
True
BME680Sensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return f"{self.client_name} {self._name}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self.client_name} {self._name}\"" ]
[ 333, 4 ]
[ 335, 49 ]
python
en
['en', 'mi', 'en']
True
BME680Sensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 338, 4 ]
[ 340, 26 ]
python
en
['en', 'en', 'en']
True
BME680Sensor.unit_of_measurement
(self)
Return the unit of measurement of the sensor.
Return the unit of measurement of the sensor.
def unit_of_measurement(self): """Return the unit of measurement of the sensor.""" return self._unit_of_measurement
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "_unit_of_measurement" ]
[ 343, 4 ]
[ 345, 40 ]
python
en
['en', 'bg', 'en']
True
BME680Sensor.async_update
(self)
Get the latest data from the BME680 and update the states.
Get the latest data from the BME680 and update the states.
async def async_update(self): """Get the latest data from the BME680 and update the states.""" await self.hass.async_add_executor_job(self.bme680_client.update) if self.type == SENSOR_TEMP: temperature = round(self.bme680_client.sensor_data.temperature, 1) if self.temp_unit == TEMP_FAHRENHEIT: temperature = round(celsius_to_fahrenheit(temperature), 1) self._state = temperature elif self.type == SENSOR_HUMID: self._state = round(self.bme680_client.sensor_data.humidity, 1) elif self.type == SENSOR_PRESS: self._state = round(self.bme680_client.sensor_data.pressure, 1) elif self.type == SENSOR_GAS: self._state = int(round(self.bme680_client.sensor_data.gas_resistance, 0)) elif self.type == SENSOR_AQ: aq_score = self.bme680_client.sensor_data.air_quality if aq_score is not None: self._state = round(aq_score, 1)
[ "async", "def", "async_update", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "bme680_client", ".", "update", ")", "if", "self", ".", "type", "==", "SENSOR_TEMP", ":", "temperature", "=", "round", "(", "self", ".", "bme680_client", ".", "sensor_data", ".", "temperature", ",", "1", ")", "if", "self", ".", "temp_unit", "==", "TEMP_FAHRENHEIT", ":", "temperature", "=", "round", "(", "celsius_to_fahrenheit", "(", "temperature", ")", ",", "1", ")", "self", ".", "_state", "=", "temperature", "elif", "self", ".", "type", "==", "SENSOR_HUMID", ":", "self", ".", "_state", "=", "round", "(", "self", ".", "bme680_client", ".", "sensor_data", ".", "humidity", ",", "1", ")", "elif", "self", ".", "type", "==", "SENSOR_PRESS", ":", "self", ".", "_state", "=", "round", "(", "self", ".", "bme680_client", ".", "sensor_data", ".", "pressure", ",", "1", ")", "elif", "self", ".", "type", "==", "SENSOR_GAS", ":", "self", ".", "_state", "=", "int", "(", "round", "(", "self", ".", "bme680_client", ".", "sensor_data", ".", "gas_resistance", ",", "0", ")", ")", "elif", "self", ".", "type", "==", "SENSOR_AQ", ":", "aq_score", "=", "self", ".", "bme680_client", ".", "sensor_data", ".", "air_quality", "if", "aq_score", "is", "not", "None", ":", "self", ".", "_state", "=", "round", "(", "aq_score", ",", "1", ")" ]
[ 347, 4 ]
[ 364, 48 ]
python
en
['en', 'en', 'en']
True