Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_operation_value_changed_mapping_preset
(device_mapping)
Test values changed for climate device. Mapping with presets.
Test values changed for climate device. Mapping with presets.
def test_operation_value_changed_mapping_preset(device_mapping): """Test values changed for climate device. Mapping with presets.""" device = device_mapping assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = "Full Power" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == PRESET_BOOST device.values.primary = None assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == PRESET_NONE
[ "def", "test_operation_value_changed_mapping_preset", "(", "device_mapping", ")", ":", "device", "=", "device_mapping", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_HEAT", "assert", "device", ".", "preset_mode", "==", "PRESET_NONE", "device", ".", "values", ".", "primary", ".", "data", "=", "\"Full Power\"", "value_changed", "(", "device", ".", "values", ".", "primary", ")", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_HEAT_COOL", "assert", "device", ".", "preset_mode", "==", "PRESET_BOOST", "device", ".", "values", ".", "primary", "=", "None", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_HEAT_COOL", "assert", "device", ".", "preset_mode", "==", "PRESET_NONE" ]
[ 771, 0 ]
[ 782, 44 ]
python
en
['en', 'en', 'en']
True
test_operation_value_changed_unknown
(device_unknown)
Test preset changed for climate device. Unknown.
Test preset changed for climate device. Unknown.
def test_operation_value_changed_unknown(device_unknown): """Test preset changed for climate device. Unknown.""" device = device_unknown assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = "Abcdefg" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_HEAT_COOL assert device.preset_mode == "Abcdefg"
[ "def", "test_operation_value_changed_unknown", "(", "device_unknown", ")", ":", "device", "=", "device_unknown", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_HEAT", "assert", "device", ".", "preset_mode", "==", "PRESET_NONE", "device", ".", "values", ".", "primary", ".", "data", "=", "\"Abcdefg\"", "value_changed", "(", "device", ".", "values", ".", "primary", ")", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_HEAT_COOL", "assert", "device", ".", "preset_mode", "==", "\"Abcdefg\"" ]
[ 785, 0 ]
[ 793, 42 ]
python
en
['en', 'en', 'en']
True
test_operation_value_changed_heat_cool
(device_heat_cool)
Test preset changed for climate device. Heat/Cool only.
Test preset changed for climate device. Heat/Cool only.
def test_operation_value_changed_heat_cool(device_heat_cool): """Test preset changed for climate device. Heat/Cool only.""" device = device_heat_cool assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == PRESET_NONE device.values.primary.data = "Cool Eco" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_COOL assert device.preset_mode == "Cool Eco" device.values.primary.data = "Heat Eco" value_changed(device.values.primary) assert device.hvac_mode == HVAC_MODE_HEAT assert device.preset_mode == "Heat Eco"
[ "def", "test_operation_value_changed_heat_cool", "(", "device_heat_cool", ")", ":", "device", "=", "device_heat_cool", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_HEAT", "assert", "device", ".", "preset_mode", "==", "PRESET_NONE", "device", ".", "values", ".", "primary", ".", "data", "=", "\"Cool Eco\"", "value_changed", "(", "device", ".", "values", ".", "primary", ")", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_COOL", "assert", "device", ".", "preset_mode", "==", "\"Cool Eco\"", "device", ".", "values", ".", "primary", ".", "data", "=", "\"Heat Eco\"", "value_changed", "(", "device", ".", "values", ".", "primary", ")", "assert", "device", ".", "hvac_mode", "==", "HVAC_MODE_HEAT", "assert", "device", ".", "preset_mode", "==", "\"Heat Eco\"" ]
[ 796, 0 ]
[ 808, 43 ]
python
en
['en', 'en', 'en']
True
test_fan_mode_value_changed
(device)
Test values changed for climate device.
Test values changed for climate device.
def test_fan_mode_value_changed(device): """Test values changed for climate device.""" assert device.fan_mode == "test2" device.values.fan_mode.data = "test_updated_fan" value_changed(device.values.fan_mode) assert device.fan_mode == "test_updated_fan"
[ "def", "test_fan_mode_value_changed", "(", "device", ")", ":", "assert", "device", ".", "fan_mode", "==", "\"test2\"", "device", ".", "values", ".", "fan_mode", ".", "data", "=", "\"test_updated_fan\"", "value_changed", "(", "device", ".", "values", ".", "fan_mode", ")", "assert", "device", ".", "fan_mode", "==", "\"test_updated_fan\"" ]
[ 811, 0 ]
[ 816, 48 ]
python
en
['en', 'en', 'en']
True
test_hvac_action_value_changed
(device)
Test values changed for climate device.
Test values changed for climate device.
def test_hvac_action_value_changed(device): """Test values changed for climate device.""" assert device.hvac_action == CURRENT_HVAC_HEAT device.values.operating_state.data = CURRENT_HVAC_COOL value_changed(device.values.operating_state) assert device.hvac_action == CURRENT_HVAC_COOL
[ "def", "test_hvac_action_value_changed", "(", "device", ")", ":", "assert", "device", ".", "hvac_action", "==", "CURRENT_HVAC_HEAT", "device", ".", "values", ".", "operating_state", ".", "data", "=", "CURRENT_HVAC_COOL", "value_changed", "(", "device", ".", "values", ".", "operating_state", ")", "assert", "device", ".", "hvac_action", "==", "CURRENT_HVAC_COOL" ]
[ 819, 0 ]
[ 824, 50 ]
python
en
['en', 'en', 'en']
True
test_hvac_action_value_changed_mapping
(device_mapping)
Test values changed for climate device.
Test values changed for climate device.
def test_hvac_action_value_changed_mapping(device_mapping): """Test values changed for climate device.""" device = device_mapping assert device.hvac_action == CURRENT_HVAC_HEAT device.values.operating_state.data = "cooling" value_changed(device.values.operating_state) assert device.hvac_action == CURRENT_HVAC_COOL
[ "def", "test_hvac_action_value_changed_mapping", "(", "device_mapping", ")", ":", "device", "=", "device_mapping", "assert", "device", ".", "hvac_action", "==", "CURRENT_HVAC_HEAT", "device", ".", "values", ".", "operating_state", ".", "data", "=", "\"cooling\"", "value_changed", "(", "device", ".", "values", ".", "operating_state", ")", "assert", "device", ".", "hvac_action", "==", "CURRENT_HVAC_COOL" ]
[ 827, 0 ]
[ 833, 50 ]
python
en
['en', 'en', 'en']
True
test_hvac_action_value_changed_unknown
(device_unknown)
Test values changed for climate device.
Test values changed for climate device.
def test_hvac_action_value_changed_unknown(device_unknown): """Test values changed for climate device.""" device = device_unknown assert device.hvac_action == "test4" device.values.operating_state.data = "another_hvac_action" value_changed(device.values.operating_state) assert device.hvac_action == "another_hvac_action"
[ "def", "test_hvac_action_value_changed_unknown", "(", "device_unknown", ")", ":", "device", "=", "device_unknown", "assert", "device", ".", "hvac_action", "==", "\"test4\"", "device", ".", "values", ".", "operating_state", ".", "data", "=", "\"another_hvac_action\"", "value_changed", "(", "device", ".", "values", ".", "operating_state", ")", "assert", "device", ".", "hvac_action", "==", "\"another_hvac_action\"" ]
[ 836, 0 ]
[ 842, 54 ]
python
en
['en', 'en', 'en']
True
test_fan_action_value_changed
(device)
Test values changed for climate device.
Test values changed for climate device.
def test_fan_action_value_changed(device): """Test values changed for climate device.""" assert device.device_state_attributes[climate.ATTR_FAN_ACTION] == 7 device.values.fan_action.data = 9 value_changed(device.values.fan_action) assert device.device_state_attributes[climate.ATTR_FAN_ACTION] == 9
[ "def", "test_fan_action_value_changed", "(", "device", ")", ":", "assert", "device", ".", "device_state_attributes", "[", "climate", ".", "ATTR_FAN_ACTION", "]", "==", "7", "device", ".", "values", ".", "fan_action", ".", "data", "=", "9", "value_changed", "(", "device", ".", "values", ".", "fan_action", ")", "assert", "device", ".", "device_state_attributes", "[", "climate", ".", "ATTR_FAN_ACTION", "]", "==", "9" ]
[ 845, 0 ]
[ 850, 71 ]
python
en
['en', 'en', 'en']
True
test_aux_heat_unsupported_set
(device)
Test aux heat for climate device.
Test aux heat for climate device.
def test_aux_heat_unsupported_set(device): """Test aux heat for climate device.""" assert device.values.primary.data == HVAC_MODE_HEAT device.turn_aux_heat_on() assert device.values.primary.data == HVAC_MODE_HEAT device.turn_aux_heat_off() assert device.values.primary.data == HVAC_MODE_HEAT
[ "def", "test_aux_heat_unsupported_set", "(", "device", ")", ":", "assert", "device", ".", "values", ".", "primary", ".", "data", "==", "HVAC_MODE_HEAT", "device", ".", "turn_aux_heat_on", "(", ")", "assert", "device", ".", "values", ".", "primary", ".", "data", "==", "HVAC_MODE_HEAT", "device", ".", "turn_aux_heat_off", "(", ")", "assert", "device", ".", "values", ".", "primary", ".", "data", "==", "HVAC_MODE_HEAT" ]
[ 853, 0 ]
[ 859, 55 ]
python
fr
['fr', 'en', 'fr']
True
test_aux_heat_unsupported_value_changed
(device)
Test aux heat for climate device.
Test aux heat for climate device.
def test_aux_heat_unsupported_value_changed(device): """Test aux heat for climate device.""" assert device.is_aux_heat is None device.values.primary.data = HVAC_MODE_HEAT value_changed(device.values.primary) assert device.is_aux_heat is None
[ "def", "test_aux_heat_unsupported_value_changed", "(", "device", ")", ":", "assert", "device", ".", "is_aux_heat", "is", "None", "device", ".", "values", ".", "primary", ".", "data", "=", "HVAC_MODE_HEAT", "value_changed", "(", "device", ".", "values", ".", "primary", ")", "assert", "device", ".", "is_aux_heat", "is", "None" ]
[ 862, 0 ]
[ 867, 37 ]
python
fr
['fr', 'en', 'fr']
True
test_aux_heat_set
(device_aux_heat)
Test aux heat for climate device.
Test aux heat for climate device.
def test_aux_heat_set(device_aux_heat): """Test aux heat for climate device.""" device = device_aux_heat assert device.values.primary.data == HVAC_MODE_HEAT device.turn_aux_heat_on() assert device.values.primary.data == AUX_HEAT_ZWAVE_MODE device.turn_aux_heat_off() assert device.values.primary.data == HVAC_MODE_HEAT
[ "def", "test_aux_heat_set", "(", "device_aux_heat", ")", ":", "device", "=", "device_aux_heat", "assert", "device", ".", "values", ".", "primary", ".", "data", "==", "HVAC_MODE_HEAT", "device", ".", "turn_aux_heat_on", "(", ")", "assert", "device", ".", "values", ".", "primary", ".", "data", "==", "AUX_HEAT_ZWAVE_MODE", "device", ".", "turn_aux_heat_off", "(", ")", "assert", "device", ".", "values", ".", "primary", ".", "data", "==", "HVAC_MODE_HEAT" ]
[ 870, 0 ]
[ 877, 55 ]
python
fr
['fr', 'en', 'fr']
True
test_aux_heat_value_changed
(device_aux_heat)
Test aux heat for climate device.
Test aux heat for climate device.
def test_aux_heat_value_changed(device_aux_heat): """Test aux heat for climate device.""" device = device_aux_heat assert device.is_aux_heat is False device.values.primary.data = AUX_HEAT_ZWAVE_MODE value_changed(device.values.primary) assert device.is_aux_heat is True device.values.primary.data = HVAC_MODE_HEAT value_changed(device.values.primary) assert device.is_aux_heat is False
[ "def", "test_aux_heat_value_changed", "(", "device_aux_heat", ")", ":", "device", "=", "device_aux_heat", "assert", "device", ".", "is_aux_heat", "is", "False", "device", ".", "values", ".", "primary", ".", "data", "=", "AUX_HEAT_ZWAVE_MODE", "value_changed", "(", "device", ".", "values", ".", "primary", ")", "assert", "device", ".", "is_aux_heat", "is", "True", "device", ".", "values", ".", "primary", ".", "data", "=", "HVAC_MODE_HEAT", "value_changed", "(", "device", ".", "values", ".", "primary", ")", "assert", "device", ".", "is_aux_heat", "is", "False" ]
[ 880, 0 ]
[ 889, 38 ]
python
fr
['fr', 'en', 'fr']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], )
Set up WLED light based on a config entry.
Set up WLED light based on a config entry.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up WLED light based on a config entry.""" coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] platform = entity_platform.current_platform.get() platform.async_register_entity_service( SERVICE_EFFECT, { vol.Optional(ATTR_EFFECT): vol.Any(cv.positive_int, cv.string), vol.Optional(ATTR_INTENSITY): vol.All( vol.Coerce(int), vol.Range(min=0, max=255) ), vol.Optional(ATTR_PALETTE): vol.Any(cv.positive_int, cv.string), vol.Optional(ATTR_REVERSE): cv.boolean, vol.Optional(ATTR_SPEED): vol.All( vol.Coerce(int), vol.Range(min=0, max=255) ), }, "async_effect", ) platform.async_register_entity_service( SERVICE_PRESET, { vol.Required(ATTR_PRESET): vol.All( vol.Coerce(int), vol.Range(min=-1, max=65535) ), }, "async_preset", ) update_segments = partial( async_update_segments, entry, coordinator, {}, async_add_entities ) coordinator.async_add_listener(update_segments) update_segments()
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "Callable", "[", "[", "List", "[", "Entity", "]", ",", "bool", "]", ",", "None", "]", ",", ")", "->", "None", ":", "coordinator", ":", "WLEDDataUpdateCoordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "platform", "=", "entity_platform", ".", "current_platform", ".", "get", "(", ")", "platform", ".", "async_register_entity_service", "(", "SERVICE_EFFECT", ",", "{", "vol", ".", "Optional", "(", "ATTR_EFFECT", ")", ":", "vol", ".", "Any", "(", "cv", ".", "positive_int", ",", "cv", ".", "string", ")", ",", "vol", ".", "Optional", "(", "ATTR_INTENSITY", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=", "0", ",", "max", "=", "255", ")", ")", ",", "vol", ".", "Optional", "(", "ATTR_PALETTE", ")", ":", "vol", ".", "Any", "(", "cv", ".", "positive_int", ",", "cv", ".", "string", ")", ",", "vol", ".", "Optional", "(", "ATTR_REVERSE", ")", ":", "cv", ".", "boolean", ",", "vol", ".", "Optional", "(", "ATTR_SPEED", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=", "0", ",", "max", "=", "255", ")", ")", ",", "}", ",", "\"async_effect\"", ",", ")", "platform", ".", "async_register_entity_service", "(", "SERVICE_PRESET", ",", "{", "vol", ".", "Required", "(", "ATTR_PRESET", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=", "-", "1", ",", "max", "=", "65535", ")", ")", ",", "}", ",", "\"async_preset\"", ",", ")", "update_segments", "=", "partial", "(", "async_update_segments", ",", "entry", ",", "coordinator", ",", "{", "}", ",", "async_add_entities", ")", "coordinator", ".", "async_add_listener", "(", "update_segments", ")", "update_segments", "(", ")" ]
[ 50, 0 ]
[ 91, 21 ]
python
en
['en', 'da', 'en']
True
async_update_segments
( entry: ConfigEntry, coordinator: WLEDDataUpdateCoordinator, current: Dict[int, WLEDSegmentLight], async_add_entities, )
Update segments.
Update segments.
def async_update_segments( entry: ConfigEntry, coordinator: WLEDDataUpdateCoordinator, current: Dict[int, WLEDSegmentLight], async_add_entities, ) -> None: """Update segments.""" segment_ids = {light.segment_id for light in coordinator.data.state.segments} current_ids = set(current) # Discard master (if present) current_ids.discard(-1) # Process new segments, add them to Home Assistant new_entities = [] for segment_id in segment_ids - current_ids: current[segment_id] = WLEDSegmentLight(entry.entry_id, coordinator, segment_id) new_entities.append(current[segment_id]) # More than 1 segment now? Add master controls if len(current_ids) < 2 and len(segment_ids) > 1: current[-1] = WLEDMasterLight(entry.entry_id, coordinator) new_entities.append(current[-1]) if new_entities: async_add_entities(new_entities) # Process deleted segments, remove them from Home Assistant for segment_id in current_ids - segment_ids: coordinator.hass.async_create_task( async_remove_entity(segment_id, coordinator, current) ) # Remove master if there is only 1 segment left if len(current_ids) > 1 and len(segment_ids) < 2: coordinator.hass.async_create_task( async_remove_entity(-1, coordinator, current) )
[ "def", "async_update_segments", "(", "entry", ":", "ConfigEntry", ",", "coordinator", ":", "WLEDDataUpdateCoordinator", ",", "current", ":", "Dict", "[", "int", ",", "WLEDSegmentLight", "]", ",", "async_add_entities", ",", ")", "->", "None", ":", "segment_ids", "=", "{", "light", ".", "segment_id", "for", "light", "in", "coordinator", ".", "data", ".", "state", ".", "segments", "}", "current_ids", "=", "set", "(", "current", ")", "# Discard master (if present)", "current_ids", ".", "discard", "(", "-", "1", ")", "# Process new segments, add them to Home Assistant", "new_entities", "=", "[", "]", "for", "segment_id", "in", "segment_ids", "-", "current_ids", ":", "current", "[", "segment_id", "]", "=", "WLEDSegmentLight", "(", "entry", ".", "entry_id", ",", "coordinator", ",", "segment_id", ")", "new_entities", ".", "append", "(", "current", "[", "segment_id", "]", ")", "# More than 1 segment now? Add master controls", "if", "len", "(", "current_ids", ")", "<", "2", "and", "len", "(", "segment_ids", ")", ">", "1", ":", "current", "[", "-", "1", "]", "=", "WLEDMasterLight", "(", "entry", ".", "entry_id", ",", "coordinator", ")", "new_entities", ".", "append", "(", "current", "[", "-", "1", "]", ")", "if", "new_entities", ":", "async_add_entities", "(", "new_entities", ")", "# Process deleted segments, remove them from Home Assistant", "for", "segment_id", "in", "current_ids", "-", "segment_ids", ":", "coordinator", ".", "hass", ".", "async_create_task", "(", "async_remove_entity", "(", "segment_id", ",", "coordinator", ",", "current", ")", ")", "# Remove master if there is only 1 segment left", "if", "len", "(", "current_ids", ")", ">", "1", "and", "len", "(", "segment_ids", ")", "<", "2", ":", "coordinator", ".", "hass", ".", "async_create_task", "(", "async_remove_entity", "(", "-", "1", ",", "coordinator", ",", "current", ")", ")" ]
[ 397, 0 ]
[ 434, 9 ]
python
co
['it', 'co', 'en']
False
async_remove_entity
( index: int, coordinator: WLEDDataUpdateCoordinator, current: Dict[int, WLEDSegmentLight], )
Remove WLED segment light from Home Assistant.
Remove WLED segment light from Home Assistant.
async def async_remove_entity( index: int, coordinator: WLEDDataUpdateCoordinator, current: Dict[int, WLEDSegmentLight], ) -> None: """Remove WLED segment light from Home Assistant.""" entity = current[index] await entity.async_remove() registry = await async_get_entity_registry(coordinator.hass) if entity.entity_id in registry.entities: registry.async_remove(entity.entity_id) del current[index]
[ "async", "def", "async_remove_entity", "(", "index", ":", "int", ",", "coordinator", ":", "WLEDDataUpdateCoordinator", ",", "current", ":", "Dict", "[", "int", ",", "WLEDSegmentLight", "]", ",", ")", "->", "None", ":", "entity", "=", "current", "[", "index", "]", "await", "entity", ".", "async_remove", "(", ")", "registry", "=", "await", "async_get_entity_registry", "(", "coordinator", ".", "hass", ")", "if", "entity", ".", "entity_id", "in", "registry", ".", "entities", ":", "registry", ".", "async_remove", "(", "entity", ".", "entity_id", ")", "del", "current", "[", "index", "]" ]
[ 437, 0 ]
[ 448, 22 ]
python
en
['en', 'en', 'en']
True
WLEDMasterLight.__init__
(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator)
Initialize WLED master light.
Initialize WLED master light.
def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator): """Initialize WLED master light.""" super().__init__( entry_id=entry_id, coordinator=coordinator, name=f"{coordinator.data.info.name} Master", icon="mdi:led-strip-variant", )
[ "def", "__init__", "(", "self", ",", "entry_id", ":", "str", ",", "coordinator", ":", "WLEDDataUpdateCoordinator", ")", ":", "super", "(", ")", ".", "__init__", "(", "entry_id", "=", "entry_id", ",", "coordinator", "=", "coordinator", ",", "name", "=", "f\"{coordinator.data.info.name} Master\"", ",", "icon", "=", "\"mdi:led-strip-variant\"", ",", ")" ]
[ 97, 4 ]
[ 104, 9 ]
python
en
['fr', 'zu', 'en']
False
WLEDMasterLight.unique_id
(self)
Return the unique ID for this sensor.
Return the unique ID for this sensor.
def unique_id(self) -> str: """Return the unique ID for this sensor.""" return f"{self.coordinator.data.info.mac_address}"
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "return", "f\"{self.coordinator.data.info.mac_address}\"" ]
[ 107, 4 ]
[ 109, 58 ]
python
en
['en', 'la', 'en']
True
WLEDMasterLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self) -> int: """Flag supported features.""" return SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_BRIGHTNESS", "|", "SUPPORT_TRANSITION" ]
[ 112, 4 ]
[ 114, 54 ]
python
en
['da', 'en', 'en']
True
WLEDMasterLight.brightness
(self)
Return the brightness of this light between 1..255.
Return the brightness of this light between 1..255.
def brightness(self) -> Optional[int]: """Return the brightness of this light between 1..255.""" return self.coordinator.data.state.brightness
[ "def", "brightness", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "return", "self", ".", "coordinator", ".", "data", ".", "state", ".", "brightness" ]
[ 117, 4 ]
[ 119, 53 ]
python
en
['en', 'en', 'en']
True
WLEDMasterLight.is_on
(self)
Return the state of the light.
Return the state of the light.
def is_on(self) -> bool: """Return the state of the light.""" return bool(self.coordinator.data.state.on)
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "coordinator", ".", "data", ".", "state", ".", "on", ")" ]
[ 122, 4 ]
[ 124, 51 ]
python
en
['en', 'en', 'en']
True
WLEDMasterLight.async_turn_off
(self, **kwargs: Any)
Turn off the light.
Turn off the light.
async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the light.""" data = {ATTR_ON: False} if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) await self.coordinator.wled.master(**data)
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "data", "=", "{", "ATTR_ON", ":", "False", "}", "if", "ATTR_TRANSITION", "in", "kwargs", ":", "# WLED uses 100ms per unit, so 10 = 1 second.", "data", "[", "ATTR_TRANSITION", "]", "=", "round", "(", "kwargs", "[", "ATTR_TRANSITION", "]", "*", "10", ")", "await", "self", ".", "coordinator", ".", "wled", ".", "master", "(", "*", "*", "data", ")" ]
[ 127, 4 ]
[ 135, 50 ]
python
en
['en', 'zh', 'en']
True
WLEDMasterLight.async_turn_on
(self, **kwargs: Any)
Turn on the light.
Turn on the light.
async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" data = {ATTR_ON: True} if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) if ATTR_BRIGHTNESS in kwargs: data[ATTR_BRIGHTNESS] = kwargs[ATTR_BRIGHTNESS] await self.coordinator.wled.master(**data)
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "data", "=", "{", "ATTR_ON", ":", "True", "}", "if", "ATTR_TRANSITION", "in", "kwargs", ":", "# WLED uses 100ms per unit, so 10 = 1 second.", "data", "[", "ATTR_TRANSITION", "]", "=", "round", "(", "kwargs", "[", "ATTR_TRANSITION", "]", "*", "10", ")", "if", "ATTR_BRIGHTNESS", "in", "kwargs", ":", "data", "[", "ATTR_BRIGHTNESS", "]", "=", "kwargs", "[", "ATTR_BRIGHTNESS", "]", "await", "self", ".", "coordinator", ".", "wled", ".", "master", "(", "*", "*", "data", ")" ]
[ 138, 4 ]
[ 149, 50 ]
python
en
['en', 'et', 'en']
True
WLEDSegmentLight.__init__
( self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, segment: int )
Initialize WLED segment light.
Initialize WLED segment light.
def __init__( self, entry_id: str, coordinator: WLEDDataUpdateCoordinator, segment: int ): """Initialize WLED segment light.""" self._rgbw = coordinator.data.info.leds.rgbw self._segment = segment # If this is the one and only segment, use a simpler name name = f"{coordinator.data.info.name} Segment {self._segment}" if len(coordinator.data.state.segments) == 1: name = coordinator.data.info.name super().__init__( entry_id=entry_id, coordinator=coordinator, name=name, icon="mdi:led-strip-variant", )
[ "def", "__init__", "(", "self", ",", "entry_id", ":", "str", ",", "coordinator", ":", "WLEDDataUpdateCoordinator", ",", "segment", ":", "int", ")", ":", "self", ".", "_rgbw", "=", "coordinator", ".", "data", ".", "info", ".", "leds", ".", "rgbw", "self", ".", "_segment", "=", "segment", "# If this is the one and only segment, use a simpler name", "name", "=", "f\"{coordinator.data.info.name} Segment {self._segment}\"", "if", "len", "(", "coordinator", ".", "data", ".", "state", ".", "segments", ")", "==", "1", ":", "name", "=", "coordinator", ".", "data", ".", "info", ".", "name", "super", "(", ")", ".", "__init__", "(", "entry_id", "=", "entry_id", ",", "coordinator", "=", "coordinator", ",", "name", "=", "name", ",", "icon", "=", "\"mdi:led-strip-variant\"", ",", ")" ]
[ 155, 4 ]
[ 172, 9 ]
python
en
['ca', 'en', 'en']
True
WLEDSegmentLight.unique_id
(self)
Return the unique ID for this sensor.
Return the unique ID for this sensor.
def unique_id(self) -> str: """Return the unique ID for this sensor.""" return f"{self.coordinator.data.info.mac_address}_{self._segment}"
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "return", "f\"{self.coordinator.data.info.mac_address}_{self._segment}\"" ]
[ 175, 4 ]
[ 177, 74 ]
python
en
['en', 'la', 'en']
True
WLEDSegmentLight.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self) -> bool: """Return True if entity is available.""" try: self.coordinator.data.state.segments[self._segment] except IndexError: return False return super().available
[ "def", "available", "(", "self", ")", "->", "bool", ":", "try", ":", "self", ".", "coordinator", ".", "data", ".", "state", ".", "segments", "[", "self", ".", "_segment", "]", "except", "IndexError", ":", "return", "False", "return", "super", "(", ")", ".", "available" ]
[ 180, 4 ]
[ 187, 32 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.device_state_attributes
(self)
Return the state attributes of the entity.
Return the state attributes of the entity.
def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes of the entity.""" playlist = self.coordinator.data.state.playlist if playlist == -1: playlist = None preset = self.coordinator.data.state.preset if preset == -1: preset = None segment = self.coordinator.data.state.segments[self._segment] return { ATTR_INTENSITY: segment.intensity, ATTR_PALETTE: segment.palette.name, ATTR_PLAYLIST: playlist, ATTR_PRESET: preset, ATTR_REVERSE: segment.reverse, ATTR_SPEED: segment.speed, }
[ "def", "device_state_attributes", "(", "self", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "playlist", "=", "self", ".", "coordinator", ".", "data", ".", "state", ".", "playlist", "if", "playlist", "==", "-", "1", ":", "playlist", "=", "None", "preset", "=", "self", ".", "coordinator", ".", "data", ".", "state", ".", "preset", "if", "preset", "==", "-", "1", ":", "preset", "=", "None", "segment", "=", "self", ".", "coordinator", ".", "data", ".", "state", ".", "segments", "[", "self", ".", "_segment", "]", "return", "{", "ATTR_INTENSITY", ":", "segment", ".", "intensity", ",", "ATTR_PALETTE", ":", "segment", ".", "palette", ".", "name", ",", "ATTR_PLAYLIST", ":", "playlist", ",", "ATTR_PRESET", ":", "preset", ",", "ATTR_REVERSE", ":", "segment", ".", "reverse", ",", "ATTR_SPEED", ":", "segment", ".", "speed", ",", "}" ]
[ 190, 4 ]
[ 208, 9 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.hs_color
(self)
Return the hue and saturation color value [float, float].
Return the hue and saturation color value [float, float].
def hs_color(self) -> Optional[Tuple[float, float]]: """Return the hue and saturation color value [float, float].""" color = self.coordinator.data.state.segments[self._segment].color_primary return color_util.color_RGB_to_hs(*color[:3])
[ "def", "hs_color", "(", "self", ")", "->", "Optional", "[", "Tuple", "[", "float", ",", "float", "]", "]", ":", "color", "=", "self", ".", "coordinator", ".", "data", ".", "state", ".", "segments", "[", "self", ".", "_segment", "]", ".", "color_primary", "return", "color_util", ".", "color_RGB_to_hs", "(", "*", "color", "[", ":", "3", "]", ")" ]
[ 211, 4 ]
[ 214, 53 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.effect
(self)
Return the current effect of the light.
Return the current effect of the light.
def effect(self) -> Optional[str]: """Return the current effect of the light.""" return self.coordinator.data.state.segments[self._segment].effect.name
[ "def", "effect", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "coordinator", ".", "data", ".", "state", ".", "segments", "[", "self", ".", "_segment", "]", ".", "effect", ".", "name" ]
[ 217, 4 ]
[ 219, 78 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.brightness
(self)
Return the brightness of this light between 1..255.
Return the brightness of this light between 1..255.
def brightness(self) -> Optional[int]: """Return the brightness of this light between 1..255.""" state = self.coordinator.data.state # If this is the one and only segment, calculate brightness based # on the master and segment brightness if len(state.segments) == 1: return int( (state.segments[self._segment].brightness * state.brightness) / 255 ) return state.segments[self._segment].brightness
[ "def", "brightness", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "state", "=", "self", ".", "coordinator", ".", "data", ".", "state", "# If this is the one and only segment, calculate brightness based", "# on the master and segment brightness", "if", "len", "(", "state", ".", "segments", ")", "==", "1", ":", "return", "int", "(", "(", "state", ".", "segments", "[", "self", ".", "_segment", "]", ".", "brightness", "*", "state", ".", "brightness", ")", "/", "255", ")", "return", "state", ".", "segments", "[", "self", ".", "_segment", "]", ".", "brightness" ]
[ 222, 4 ]
[ 233, 55 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.white_value
(self)
Return the white value of this light between 0..255.
Return the white value of this light between 0..255.
def white_value(self) -> Optional[int]: """Return the white value of this light between 0..255.""" color = self.coordinator.data.state.segments[self._segment].color_primary return color[-1] if self._rgbw else None
[ "def", "white_value", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "color", "=", "self", ".", "coordinator", ".", "data", ".", "state", ".", "segments", "[", "self", ".", "_segment", "]", ".", "color_primary", "return", "color", "[", "-", "1", "]", "if", "self", ".", "_rgbw", "else", "None" ]
[ 236, 4 ]
[ 239, 48 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self) -> int: """Flag supported features.""" flags = ( SUPPORT_BRIGHTNESS | SUPPORT_COLOR | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT | SUPPORT_TRANSITION ) if self._rgbw: flags |= SUPPORT_WHITE_VALUE return flags
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "flags", "=", "(", "SUPPORT_BRIGHTNESS", "|", "SUPPORT_COLOR", "|", "SUPPORT_COLOR_TEMP", "|", "SUPPORT_EFFECT", "|", "SUPPORT_TRANSITION", ")", "if", "self", ".", "_rgbw", ":", "flags", "|=", "SUPPORT_WHITE_VALUE", "return", "flags" ]
[ 242, 4 ]
[ 255, 20 ]
python
en
['da', 'en', 'en']
True
WLEDSegmentLight.effect_list
(self)
Return the list of supported effects.
Return the list of supported effects.
def effect_list(self) -> List[str]: """Return the list of supported effects.""" return [effect.name for effect in self.coordinator.data.effects]
[ "def", "effect_list", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "effect", ".", "name", "for", "effect", "in", "self", ".", "coordinator", ".", "data", ".", "effects", "]" ]
[ 258, 4 ]
[ 260, 72 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.is_on
(self)
Return the state of the light.
Return the state of the light.
def is_on(self) -> bool: """Return the state of the light.""" state = self.coordinator.data.state # If there is a single segment, take master into account if len(state.segments) == 1 and not state.on: return False return bool(state.segments[self._segment].on)
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "state", "=", "self", ".", "coordinator", ".", "data", ".", "state", "# If there is a single segment, take master into account", "if", "len", "(", "state", ".", "segments", ")", "==", "1", "and", "not", "state", ".", "on", ":", "return", "False", "return", "bool", "(", "state", ".", "segments", "[", "self", ".", "_segment", "]", ".", "on", ")" ]
[ 263, 4 ]
[ 271, 53 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.async_turn_off
(self, **kwargs: Any)
Turn off the light.
Turn off the light.
async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the light.""" data = {ATTR_ON: False} if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) # If there is a single segment, control via the master if len(self.coordinator.data.state.segments) == 1: await self.coordinator.wled.master(**data) return data[ATTR_SEGMENT_ID] = self._segment await self.coordinator.wled.segment(**data)
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "data", "=", "{", "ATTR_ON", ":", "False", "}", "if", "ATTR_TRANSITION", "in", "kwargs", ":", "# WLED uses 100ms per unit, so 10 = 1 second.", "data", "[", "ATTR_TRANSITION", "]", "=", "round", "(", "kwargs", "[", "ATTR_TRANSITION", "]", "*", "10", ")", "# If there is a single segment, control via the master", "if", "len", "(", "self", ".", "coordinator", ".", "data", ".", "state", ".", "segments", ")", "==", "1", ":", "await", "self", ".", "coordinator", ".", "wled", ".", "master", "(", "*", "*", "data", ")", "return", "data", "[", "ATTR_SEGMENT_ID", "]", "=", "self", ".", "_segment", "await", "self", ".", "coordinator", ".", "wled", ".", "segment", "(", "*", "*", "data", ")" ]
[ 274, 4 ]
[ 288, 51 ]
python
en
['en', 'zh', 'en']
True
WLEDSegmentLight.async_turn_on
(self, **kwargs: Any)
Turn on the light.
Turn on the light.
async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" data = {ATTR_ON: True, ATTR_SEGMENT_ID: self._segment} if ATTR_COLOR_TEMP in kwargs: mireds = color_util.color_temperature_kelvin_to_mired( kwargs[ATTR_COLOR_TEMP] ) data[ATTR_COLOR_PRIMARY] = tuple( map(int, color_util.color_temperature_to_rgb(mireds)) ) if ATTR_HS_COLOR in kwargs: hue, sat = kwargs[ATTR_HS_COLOR] data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100) if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) if ATTR_BRIGHTNESS in kwargs: data[ATTR_BRIGHTNESS] = kwargs[ATTR_BRIGHTNESS] if ATTR_EFFECT in kwargs: data[ATTR_EFFECT] = kwargs[ATTR_EFFECT] # Support for RGBW strips, adds white value if self._rgbw and any( x in (ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_WHITE_VALUE) for x in kwargs ): # WLED cannot just accept a white value, it needs the color. # We use the last know color in case just the white value changes. if all(x not in (ATTR_COLOR_TEMP, ATTR_HS_COLOR) for x in kwargs): hue, sat = self.hs_color data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100) # On a RGBW strip, when the color is pure white, disable the RGB LEDs in # WLED by setting RGB to 0,0,0 if data[ATTR_COLOR_PRIMARY] == (255, 255, 255): data[ATTR_COLOR_PRIMARY] = (0, 0, 0) # Add requested or last known white value if ATTR_WHITE_VALUE in kwargs: data[ATTR_COLOR_PRIMARY] += (kwargs[ATTR_WHITE_VALUE],) else: data[ATTR_COLOR_PRIMARY] += (self.white_value,) # When only 1 segment is present, switch along the master, and use # the master for power/brightness control. if len(self.coordinator.data.state.segments) == 1: master_data = {ATTR_ON: True} if ATTR_BRIGHTNESS in data: master_data[ATTR_BRIGHTNESS] = data[ATTR_BRIGHTNESS] data[ATTR_BRIGHTNESS] = 255 if ATTR_TRANSITION in data: master_data[ATTR_TRANSITION] = data[ATTR_TRANSITION] del data[ATTR_TRANSITION] await self.coordinator.wled.segment(**data) await self.coordinator.wled.master(**master_data) return await self.coordinator.wled.segment(**data)
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "data", "=", "{", "ATTR_ON", ":", "True", ",", "ATTR_SEGMENT_ID", ":", "self", ".", "_segment", "}", "if", "ATTR_COLOR_TEMP", "in", "kwargs", ":", "mireds", "=", "color_util", ".", "color_temperature_kelvin_to_mired", "(", "kwargs", "[", "ATTR_COLOR_TEMP", "]", ")", "data", "[", "ATTR_COLOR_PRIMARY", "]", "=", "tuple", "(", "map", "(", "int", ",", "color_util", ".", "color_temperature_to_rgb", "(", "mireds", ")", ")", ")", "if", "ATTR_HS_COLOR", "in", "kwargs", ":", "hue", ",", "sat", "=", "kwargs", "[", "ATTR_HS_COLOR", "]", "data", "[", "ATTR_COLOR_PRIMARY", "]", "=", "color_util", ".", "color_hsv_to_RGB", "(", "hue", ",", "sat", ",", "100", ")", "if", "ATTR_TRANSITION", "in", "kwargs", ":", "# WLED uses 100ms per unit, so 10 = 1 second.", "data", "[", "ATTR_TRANSITION", "]", "=", "round", "(", "kwargs", "[", "ATTR_TRANSITION", "]", "*", "10", ")", "if", "ATTR_BRIGHTNESS", "in", "kwargs", ":", "data", "[", "ATTR_BRIGHTNESS", "]", "=", "kwargs", "[", "ATTR_BRIGHTNESS", "]", "if", "ATTR_EFFECT", "in", "kwargs", ":", "data", "[", "ATTR_EFFECT", "]", "=", "kwargs", "[", "ATTR_EFFECT", "]", "# Support for RGBW strips, adds white value", "if", "self", ".", "_rgbw", "and", "any", "(", "x", "in", "(", "ATTR_COLOR_TEMP", ",", "ATTR_HS_COLOR", ",", "ATTR_WHITE_VALUE", ")", "for", "x", "in", "kwargs", ")", ":", "# WLED cannot just accept a white value, it needs the color.", "# We use the last know color in case just the white value changes.", "if", "all", "(", "x", "not", "in", "(", "ATTR_COLOR_TEMP", ",", "ATTR_HS_COLOR", ")", "for", "x", "in", "kwargs", ")", ":", "hue", ",", "sat", "=", "self", ".", "hs_color", "data", "[", "ATTR_COLOR_PRIMARY", "]", "=", "color_util", ".", "color_hsv_to_RGB", "(", "hue", ",", "sat", ",", "100", ")", "# On a RGBW strip, when the color is pure white, disable the RGB LEDs in", "# WLED by setting RGB to 0,0,0", "if", "data", "[", "ATTR_COLOR_PRIMARY", "]", "==", "(", "255", ",", "255", ",", "255", ")", ":", "data", "[", "ATTR_COLOR_PRIMARY", "]", "=", "(", "0", ",", "0", ",", "0", ")", "# Add requested or last known white value", "if", "ATTR_WHITE_VALUE", "in", "kwargs", ":", "data", "[", "ATTR_COLOR_PRIMARY", "]", "+=", "(", "kwargs", "[", "ATTR_WHITE_VALUE", "]", ",", ")", "else", ":", "data", "[", "ATTR_COLOR_PRIMARY", "]", "+=", "(", "self", ".", "white_value", ",", ")", "# When only 1 segment is present, switch along the master, and use", "# the master for power/brightness control.", "if", "len", "(", "self", ".", "coordinator", ".", "data", ".", "state", ".", "segments", ")", "==", "1", ":", "master_data", "=", "{", "ATTR_ON", ":", "True", "}", "if", "ATTR_BRIGHTNESS", "in", "data", ":", "master_data", "[", "ATTR_BRIGHTNESS", "]", "=", "data", "[", "ATTR_BRIGHTNESS", "]", "data", "[", "ATTR_BRIGHTNESS", "]", "=", "255", "if", "ATTR_TRANSITION", "in", "data", ":", "master_data", "[", "ATTR_TRANSITION", "]", "=", "data", "[", "ATTR_TRANSITION", "]", "del", "data", "[", "ATTR_TRANSITION", "]", "await", "self", ".", "coordinator", ".", "wled", ".", "segment", "(", "*", "*", "data", ")", "await", "self", ".", "coordinator", ".", "wled", ".", "master", "(", "*", "*", "master_data", ")", "return", "await", "self", ".", "coordinator", ".", "wled", ".", "segment", "(", "*", "*", "data", ")" ]
[ 291, 4 ]
[ 354, 51 ]
python
en
['en', 'et', 'en']
True
WLEDSegmentLight.async_effect
( self, effect: Optional[Union[int, str]] = None, intensity: Optional[int] = None, palette: Optional[Union[int, str]] = None, reverse: Optional[bool] = None, speed: Optional[int] = None, )
Set the effect of a WLED light.
Set the effect of a WLED light.
async def async_effect( self, effect: Optional[Union[int, str]] = None, intensity: Optional[int] = None, palette: Optional[Union[int, str]] = None, reverse: Optional[bool] = None, speed: Optional[int] = None, ) -> None: """Set the effect of a WLED light.""" data = {ATTR_SEGMENT_ID: self._segment} if effect is not None: data[ATTR_EFFECT] = effect if intensity is not None: data[ATTR_INTENSITY] = intensity if palette is not None: data[ATTR_PALETTE] = palette if reverse is not None: data[ATTR_REVERSE] = reverse if speed is not None: data[ATTR_SPEED] = speed await self.coordinator.wled.segment(**data)
[ "async", "def", "async_effect", "(", "self", ",", "effect", ":", "Optional", "[", "Union", "[", "int", ",", "str", "]", "]", "=", "None", ",", "intensity", ":", "Optional", "[", "int", "]", "=", "None", ",", "palette", ":", "Optional", "[", "Union", "[", "int", ",", "str", "]", "]", "=", "None", ",", "reverse", ":", "Optional", "[", "bool", "]", "=", "None", ",", "speed", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "None", ":", "data", "=", "{", "ATTR_SEGMENT_ID", ":", "self", ".", "_segment", "}", "if", "effect", "is", "not", "None", ":", "data", "[", "ATTR_EFFECT", "]", "=", "effect", "if", "intensity", "is", "not", "None", ":", "data", "[", "ATTR_INTENSITY", "]", "=", "intensity", "if", "palette", "is", "not", "None", ":", "data", "[", "ATTR_PALETTE", "]", "=", "palette", "if", "reverse", "is", "not", "None", ":", "data", "[", "ATTR_REVERSE", "]", "=", "reverse", "if", "speed", "is", "not", "None", ":", "data", "[", "ATTR_SPEED", "]", "=", "speed", "await", "self", ".", "coordinator", ".", "wled", ".", "segment", "(", "*", "*", "data", ")" ]
[ 357, 4 ]
[ 383, 51 ]
python
en
['en', 'en', 'en']
True
WLEDSegmentLight.async_preset
( self, preset: int, )
Set a WLED light to a saved preset.
Set a WLED light to a saved preset.
async def async_preset( self, preset: int, ) -> None: """Set a WLED light to a saved preset.""" data = {ATTR_PRESET: preset} await self.coordinator.wled.preset(**data)
[ "async", "def", "async_preset", "(", "self", ",", "preset", ":", "int", ",", ")", "->", "None", ":", "data", "=", "{", "ATTR_PRESET", ":", "preset", "}", "await", "self", ".", "coordinator", ".", "wled", ".", "preset", "(", "*", "*", "data", ")" ]
[ 386, 4 ]
[ 393, 50 ]
python
en
['en', 'su', 'en']
True
met_setup_fixture
()
Patch met setup entry.
Patch met setup entry.
def met_setup_fixture(): """Patch met setup entry.""" with patch("homeassistant.components.met.async_setup_entry", return_value=True): yield
[ "def", "met_setup_fixture", "(", ")", ":", "with", "patch", "(", "\"homeassistant.components.met.async_setup_entry\"", ",", "return_value", "=", "True", ")", ":", "yield" ]
[ 11, 0 ]
[ 14, 13 ]
python
en
['en', 'en', 'en']
True
test_show_config_form
(hass)
Test show configuration form.
Test show configuration form.
async def test_show_config_form(hass): """Test show configuration form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == "form" assert result["step_id"] == "user"
[ "async", "def", "test_show_config_form", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"user\"", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"" ]
[ 17, 0 ]
[ 24, 38 ]
python
en
['en', 'fr', 'en']
True
test_flow_with_home_location
(hass)
Test config flow. Test the flow when a default location is configured. Then it should return a form with default values.
Test config flow.
async def test_flow_with_home_location(hass): """Test config flow. Test the flow when a default location is configured. Then it should return a form with default values. """ hass.config.latitude = 1 hass.config.longitude = 2 hass.config.elevation = 3 result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == "form" assert result["step_id"] == "user" default_data = result["data_schema"]({}) assert default_data["name"] == HOME_LOCATION_NAME assert default_data["latitude"] == 1 assert default_data["longitude"] == 2 assert default_data["elevation"] == 3
[ "async", "def", "test_flow_with_home_location", "(", "hass", ")", ":", "hass", ".", "config", ".", "latitude", "=", "1", "hass", ".", "config", ".", "longitude", "=", "2", "hass", ".", "config", ".", "elevation", "=", "3", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"user\"", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "default_data", "=", "result", "[", "\"data_schema\"", "]", "(", "{", "}", ")", "assert", "default_data", "[", "\"name\"", "]", "==", "HOME_LOCATION_NAME", "assert", "default_data", "[", "\"latitude\"", "]", "==", "1", "assert", "default_data", "[", "\"longitude\"", "]", "==", "2", "assert", "default_data", "[", "\"elevation\"", "]", "==", "3" ]
[ 27, 0 ]
[ 48, 41 ]
python
da
['de', 'da', 'en']
False
test_create_entry
(hass)
Test create entry from user input.
Test create entry from user input.
async def test_create_entry(hass): """Test create entry from user input.""" test_data = { "name": "home", CONF_LONGITUDE: 0, CONF_LATITUDE: 0, CONF_ELEVATION: 0, } result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"}, data=test_data ) assert result["type"] == "create_entry" assert result["title"] == "home" assert result["data"] == test_data
[ "async", "def", "test_create_entry", "(", "hass", ")", ":", "test_data", "=", "{", "\"name\"", ":", "\"home\"", ",", "CONF_LONGITUDE", ":", "0", ",", "CONF_LATITUDE", ":", "0", ",", "CONF_ELEVATION", ":", "0", ",", "}", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"user\"", "}", ",", "data", "=", "test_data", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result", "[", "\"title\"", "]", "==", "\"home\"", "assert", "result", "[", "\"data\"", "]", "==", "test_data" ]
[ 51, 0 ]
[ 66, 38 ]
python
en
['en', 'en', 'en']
True
test_flow_entry_already_exists
(hass)
Test user input for config_entry that already exists. Test when the form should show when user puts existing location in the config gui. Then the form should show with error.
Test user input for config_entry that already exists.
async def test_flow_entry_already_exists(hass): """Test user input for config_entry that already exists. Test when the form should show when user puts existing location in the config gui. Then the form should show with error. """ first_entry = MockConfigEntry( domain="met", data={"name": "home", CONF_LATITUDE: 0, CONF_LONGITUDE: 0, CONF_ELEVATION: 0}, ) first_entry.add_to_hass(hass) test_data = { "name": "home", CONF_LONGITUDE: 0, CONF_LATITUDE: 0, CONF_ELEVATION: 0, } result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"}, data=test_data ) assert result["type"] == "form" assert result["errors"]["name"] == "already_configured"
[ "async", "def", "test_flow_entry_already_exists", "(", "hass", ")", ":", "first_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"met\"", ",", "data", "=", "{", "\"name\"", ":", "\"home\"", ",", "CONF_LATITUDE", ":", "0", ",", "CONF_LONGITUDE", ":", "0", ",", "CONF_ELEVATION", ":", "0", "}", ",", ")", "first_entry", ".", "add_to_hass", "(", "hass", ")", "test_data", "=", "{", "\"name\"", ":", "\"home\"", ",", "CONF_LONGITUDE", ":", "0", ",", "CONF_LATITUDE", ":", "0", ",", "CONF_ELEVATION", ":", "0", ",", "}", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"user\"", "}", ",", "data", "=", "test_data", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"errors\"", "]", "[", "\"name\"", "]", "==", "\"already_configured\"" ]
[ 69, 0 ]
[ 93, 59 ]
python
en
['en', 'en', 'en']
True
test_onboarding_step
(hass)
Test initializing via onboarding step.
Test initializing via onboarding step.
async def test_onboarding_step(hass): """Test initializing via onboarding step.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "onboarding"}, data={} ) assert result["type"] == "create_entry" assert result["title"] == HOME_LOCATION_NAME assert result["data"] == {"track_home": True}
[ "async", "def", "test_onboarding_step", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"onboarding\"", "}", ",", "data", "=", "{", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result", "[", "\"title\"", "]", "==", "HOME_LOCATION_NAME", "assert", "result", "[", "\"data\"", "]", "==", "{", "\"track_home\"", ":", "True", "}" ]
[ 96, 0 ]
[ 104, 49 ]
python
en
['nl', 'en', 'en']
True
test_import_step
(hass)
Test initializing via import step.
Test initializing via import step.
async def test_import_step(hass): """Test initializing via import step.""" test_data = { "name": "home", CONF_LONGITUDE: None, CONF_LATITUDE: None, CONF_ELEVATION: 0, "track_home": True, } result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "import"}, data=test_data ) assert result["type"] == "create_entry" assert result["title"] == "home" assert result["data"] == test_data
[ "async", "def", "test_import_step", "(", "hass", ")", ":", "test_data", "=", "{", "\"name\"", ":", "\"home\"", ",", "CONF_LONGITUDE", ":", "None", ",", "CONF_LATITUDE", ":", "None", ",", "CONF_ELEVATION", ":", "0", ",", "\"track_home\"", ":", "True", ",", "}", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"import\"", "}", ",", "data", "=", "test_data", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result", "[", "\"title\"", "]", "==", "\"home\"", "assert", "result", "[", "\"data\"", "]", "==", "test_data" ]
[ 107, 0 ]
[ 122, 38 ]
python
en
['nl', 'zu', 'en']
False
get_arguments
()
Get parsed passed in arguments.
Get parsed passed in arguments.
def get_arguments() -> argparse.Namespace: """Get parsed passed in arguments.""" return util.get_base_arg_parser().parse_known_args()[0]
[ "def", "get_arguments", "(", ")", "->", "argparse", ".", "Namespace", ":", "return", "util", ".", "get_base_arg_parser", "(", ")", ".", "parse_known_args", "(", ")", "[", "0", "]" ]
[ 9, 0 ]
[ 11, 59 ]
python
en
['en', 'la', 'en']
True
main
()
Run a translation script.
Run a translation script.
def main(): """Run a translation script.""" if not Path("requirements_all.txt").is_file(): print("Run from project root") return 1 args = get_arguments() module = importlib.import_module(f".{args.action}", "script.translations") return module.run()
[ "def", "main", "(", ")", ":", "if", "not", "Path", "(", "\"requirements_all.txt\"", ")", ".", "is_file", "(", ")", ":", "print", "(", "\"Run from project root\"", ")", "return", "1", "args", "=", "get_arguments", "(", ")", "module", "=", "importlib", ".", "import_module", "(", "f\".{args.action}\"", ",", "\"script.translations\"", ")", "return", "module", ".", "run", "(", ")" ]
[ 14, 0 ]
[ 23, 23 ]
python
co
['ro', 'co', 'en']
False
create_air_quality_sensor_service
(accessory)
Define temperature characteristics.
Define temperature characteristics.
def create_air_quality_sensor_service(accessory): """Define temperature characteristics.""" service = accessory.add_service(ServicesTypes.AIR_QUALITY_SENSOR) cur_state = service.add_char(CharacteristicsTypes.AIR_QUALITY) cur_state.value = 5 cur_state = service.add_char(CharacteristicsTypes.DENSITY_OZONE) cur_state.value = 1111 cur_state = service.add_char(CharacteristicsTypes.DENSITY_NO2) cur_state.value = 2222 cur_state = service.add_char(CharacteristicsTypes.DENSITY_SO2) cur_state.value = 3333 cur_state = service.add_char(CharacteristicsTypes.DENSITY_PM25) cur_state.value = 4444 cur_state = service.add_char(CharacteristicsTypes.DENSITY_PM10) cur_state.value = 5555 cur_state = service.add_char(CharacteristicsTypes.DENSITY_VOC) cur_state.value = 6666
[ "def", "create_air_quality_sensor_service", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "AIR_QUALITY_SENSOR", ")", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "AIR_QUALITY", ")", "cur_state", ".", "value", "=", "5", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DENSITY_OZONE", ")", "cur_state", ".", "value", "=", "1111", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DENSITY_NO2", ")", "cur_state", ".", "value", "=", "2222", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DENSITY_SO2", ")", "cur_state", ".", "value", "=", "3333", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DENSITY_PM25", ")", "cur_state", ".", "value", "=", "4444", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DENSITY_PM10", ")", "cur_state", ".", "value", "=", "5555", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DENSITY_VOC", ")", "cur_state", ".", "value", "=", "6666" ]
[ 7, 0 ]
[ 30, 26 ]
python
en
['en', 'ca', 'en']
True
test_air_quality_sensor_read_state
(hass, utcnow)
Test reading the state of a HomeKit temperature sensor accessory.
Test reading the state of a HomeKit temperature sensor accessory.
async def test_air_quality_sensor_read_state(hass, utcnow): """Test reading the state of a HomeKit temperature sensor accessory.""" helper = await setup_test_component(hass, create_air_quality_sensor_service) state = await helper.poll_and_get_state() assert state.state == "4444" assert state.attributes["air_quality_text"] == "poor" assert state.attributes["ozone"] == 1111 assert state.attributes["nitrogen_dioxide"] == 2222 assert state.attributes["sulphur_dioxide"] == 3333 assert state.attributes["particulate_matter_2_5"] == 4444 assert state.attributes["particulate_matter_10"] == 5555 assert state.attributes["volatile_organic_compounds"] == 6666
[ "async", "def", "test_air_quality_sensor_read_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_air_quality_sensor_service", ")", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"4444\"", "assert", "state", ".", "attributes", "[", "\"air_quality_text\"", "]", "==", "\"poor\"", "assert", "state", ".", "attributes", "[", "\"ozone\"", "]", "==", "1111", "assert", "state", ".", "attributes", "[", "\"nitrogen_dioxide\"", "]", "==", "2222", "assert", "state", ".", "attributes", "[", "\"sulphur_dioxide\"", "]", "==", "3333", "assert", "state", ".", "attributes", "[", "\"particulate_matter_2_5\"", "]", "==", "4444", "assert", "state", ".", "attributes", "[", "\"particulate_matter_10\"", "]", "==", "5555", "assert", "state", ".", "attributes", "[", "\"volatile_organic_compounds\"", "]", "==", "6666" ]
[ 33, 0 ]
[ 46, 65 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistant, entry: ConfigEntry, async_add_entities )
Set up Toon sensors based on a config entry.
Set up Toon sensors based on a config entry.
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None: """Set up Toon sensors based on a config entry.""" coordinator = hass.data[DOMAIN][entry.entry_id] sensors = [ ToonElectricityMeterDeviceSensor(coordinator, key=key) for key in ( "power_average_daily", "power_average", "power_daily_cost", "power_daily_value", "power_meter_reading_low", "power_meter_reading", "power_value", "solar_meter_reading_low_produced", "solar_meter_reading_produced", ) ] sensors.extend( [ToonDisplayDeviceSensor(coordinator, key="current_display_temperature")] ) sensors.extend( [ ToonGasMeterDeviceSensor(coordinator, key=key) for key in ( "gas_average_daily", "gas_average", "gas_daily_cost", "gas_daily_usage", "gas_meter_reading", "gas_value", ) ] ) sensors.extend( [ ToonWaterMeterDeviceSensor(coordinator, key=key) for key in ( "water_average_daily", "water_average", "water_daily_cost", "water_daily_usage", "water_meter_reading", "water_value", ) ] ) if coordinator.data.agreement.is_toon_solar: sensors.extend( [ ToonSolarDeviceSensor(coordinator, key=key) for key in [ "solar_value", "solar_maximum", "solar_produced", "solar_average_produced", "power_usage_day_produced_solar", "power_usage_day_from_grid_usage", "power_usage_day_to_grid_usage", "power_usage_current_covered_by_solar", ] ] ) if coordinator.data.thermostat.have_opentherm_boiler: sensors.extend( [ ToonBoilerDeviceSensor( coordinator, key="thermostat_info_current_modulation_level" ) ] ) async_add_entities(sensors, True)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "coordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "sensors", "=", "[", "ToonElectricityMeterDeviceSensor", "(", "coordinator", ",", "key", "=", "key", ")", "for", "key", "in", "(", "\"power_average_daily\"", ",", "\"power_average\"", ",", "\"power_daily_cost\"", ",", "\"power_daily_value\"", ",", "\"power_meter_reading_low\"", ",", "\"power_meter_reading\"", ",", "\"power_value\"", ",", "\"solar_meter_reading_low_produced\"", ",", "\"solar_meter_reading_produced\"", ",", ")", "]", "sensors", ".", "extend", "(", "[", "ToonDisplayDeviceSensor", "(", "coordinator", ",", "key", "=", "\"current_display_temperature\"", ")", "]", ")", "sensors", ".", "extend", "(", "[", "ToonGasMeterDeviceSensor", "(", "coordinator", ",", "key", "=", "key", ")", "for", "key", "in", "(", "\"gas_average_daily\"", ",", "\"gas_average\"", ",", "\"gas_daily_cost\"", ",", "\"gas_daily_usage\"", ",", "\"gas_meter_reading\"", ",", "\"gas_value\"", ",", ")", "]", ")", "sensors", ".", "extend", "(", "[", "ToonWaterMeterDeviceSensor", "(", "coordinator", ",", "key", "=", "key", ")", "for", "key", "in", "(", "\"water_average_daily\"", ",", "\"water_average\"", ",", "\"water_daily_cost\"", ",", "\"water_daily_usage\"", ",", "\"water_meter_reading\"", ",", "\"water_value\"", ",", ")", "]", ")", "if", "coordinator", ".", "data", ".", "agreement", ".", "is_toon_solar", ":", "sensors", ".", "extend", "(", "[", "ToonSolarDeviceSensor", "(", "coordinator", ",", "key", "=", "key", ")", "for", "key", "in", "[", "\"solar_value\"", ",", "\"solar_maximum\"", ",", "\"solar_produced\"", ",", "\"solar_average_produced\"", ",", "\"power_usage_day_produced_solar\"", ",", "\"power_usage_day_from_grid_usage\"", ",", "\"power_usage_day_to_grid_usage\"", ",", "\"power_usage_current_covered_by_solar\"", ",", "]", "]", ")", "if", "coordinator", ".", "data", ".", "thermostat", ".", "have_opentherm_boiler", ":", "sensors", ".", "extend", "(", "[", "ToonBoilerDeviceSensor", "(", "coordinator", ",", "key", "=", "\"thermostat_info_current_modulation_level\"", ")", "]", ")", "async_add_entities", "(", "sensors", ",", "True", ")" ]
[ 29, 0 ]
[ 108, 37 ]
python
en
['en', 'en', 'en']
True
ToonSensor.__init__
(self, coordinator: ToonDataUpdateCoordinator, *, key: str)
Initialize the Toon sensor.
Initialize the Toon sensor.
def __init__(self, coordinator: ToonDataUpdateCoordinator, *, key: str) -> None: """Initialize the Toon sensor.""" self.key = key super().__init__( coordinator, enabled_default=SENSOR_ENTITIES[key][ATTR_DEFAULT_ENABLED], icon=SENSOR_ENTITIES[key][ATTR_ICON], name=SENSOR_ENTITIES[key][ATTR_NAME], )
[ "def", "__init__", "(", "self", ",", "coordinator", ":", "ToonDataUpdateCoordinator", ",", "*", ",", "key", ":", "str", ")", "->", "None", ":", "self", ".", "key", "=", "key", "super", "(", ")", ".", "__init__", "(", "coordinator", ",", "enabled_default", "=", "SENSOR_ENTITIES", "[", "key", "]", "[", "ATTR_DEFAULT_ENABLED", "]", ",", "icon", "=", "SENSOR_ENTITIES", "[", "key", "]", "[", "ATTR_ICON", "]", ",", "name", "=", "SENSOR_ENTITIES", "[", "key", "]", "[", "ATTR_NAME", "]", ",", ")" ]
[ 114, 4 ]
[ 123, 9 ]
python
en
['en', 'en', 'en']
True
ToonSensor.unique_id
(self)
Return the unique ID for this sensor.
Return the unique ID for this sensor.
def unique_id(self) -> str: """Return the unique ID for this sensor.""" agreement_id = self.coordinator.data.agreement.agreement_id # This unique ID is a bit ugly and contains unneeded information. # It is here for legacy / backward compatible reasons. return f"{DOMAIN}_{agreement_id}_sensor_{self.key}"
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "agreement_id", "=", "self", ".", "coordinator", ".", "data", ".", "agreement", ".", "agreement_id", "# This unique ID is a bit ugly and contains unneeded information.", "# It is here for legacy / backward compatible reasons.", "return", "f\"{DOMAIN}_{agreement_id}_sensor_{self.key}\"" ]
[ 126, 4 ]
[ 131, 59 ]
python
en
['en', 'la', 'en']
True
ToonSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self) -> Optional[str]: """Return the state of the sensor.""" section = getattr( self.coordinator.data, SENSOR_ENTITIES[self.key][ATTR_SECTION] ) return getattr(section, SENSOR_ENTITIES[self.key][ATTR_MEASUREMENT])
[ "def", "state", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "section", "=", "getattr", "(", "self", ".", "coordinator", ".", "data", ",", "SENSOR_ENTITIES", "[", "self", ".", "key", "]", "[", "ATTR_SECTION", "]", ")", "return", "getattr", "(", "section", ",", "SENSOR_ENTITIES", "[", "self", ".", "key", "]", "[", "ATTR_MEASUREMENT", "]", ")" ]
[ 134, 4 ]
[ 139, 76 ]
python
en
['en', 'en', 'en']
True
ToonSensor.unit_of_measurement
(self)
Return the unit this state is expressed in.
Return the unit this state is expressed in.
def unit_of_measurement(self) -> Optional[str]: """Return the unit this state is expressed in.""" return SENSOR_ENTITIES[self.key][ATTR_UNIT_OF_MEASUREMENT]
[ "def", "unit_of_measurement", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "SENSOR_ENTITIES", "[", "self", ".", "key", "]", "[", "ATTR_UNIT_OF_MEASUREMENT", "]" ]
[ 142, 4 ]
[ 144, 66 ]
python
en
['en', 'en', 'en']
True
ToonSensor.device_class
(self)
Return the device class.
Return the device class.
def device_class(self) -> Optional[str]: """Return the device class.""" return SENSOR_ENTITIES[self.key][ATTR_DEVICE_CLASS]
[ "def", "device_class", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "SENSOR_ENTITIES", "[", "self", ".", "key", "]", "[", "ATTR_DEVICE_CLASS", "]" ]
[ 147, 4 ]
[ 149, 59 ]
python
en
['en', 'en', 'en']
True
init_integration
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, rgbw: bool = False, skip_setup: bool = False, )
Set up the Atag integration in Home Assistant.
Set up the Atag integration in Home Assistant.
async def init_integration( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, rgbw: bool = False, skip_setup: bool = False, ) -> MockConfigEntry: """Set up the Atag integration in Home Assistant.""" aioclient_mock.post( "http://127.0.0.1:10000/retrieve", json=RECEIVE_REPLY, headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.post( "http://127.0.0.1:10000/update", json=UPDATE_REPLY, headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.post( "http://127.0.0.1:10000/pair", json=PAIR_REPLY, headers={"Content-Type": CONTENT_TYPE_JSON}, ) entry = MockConfigEntry(domain=DOMAIN, data=USER_INPUT) entry.add_to_hass(hass) if not skip_setup: await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() return entry
[ "async", "def", "init_integration", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ",", "rgbw", ":", "bool", "=", "False", ",", "skip_setup", ":", "bool", "=", "False", ",", ")", "->", "MockConfigEntry", ":", "aioclient_mock", ".", "post", "(", "\"http://127.0.0.1:10000/retrieve\"", ",", "json", "=", "RECEIVE_REPLY", ",", "headers", "=", "{", "\"Content-Type\"", ":", "CONTENT_TYPE_JSON", "}", ",", ")", "aioclient_mock", ".", "post", "(", "\"http://127.0.0.1:10000/update\"", ",", "json", "=", "UPDATE_REPLY", ",", "headers", "=", "{", "\"Content-Type\"", ":", "CONTENT_TYPE_JSON", "}", ",", ")", "aioclient_mock", ".", "post", "(", "\"http://127.0.0.1:10000/pair\"", ",", "json", "=", "PAIR_REPLY", ",", "headers", "=", "{", "\"Content-Type\"", ":", "CONTENT_TYPE_JSON", "}", ",", ")", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "USER_INPUT", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "if", "not", "skip_setup", ":", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "return", "entry" ]
[ 53, 0 ]
[ 84, 16 ]
python
en
['en', 'en', 'en']
True
json_message_response
(message: str, message_code: int)
Produce common json output.
Produce common json output.
def json_message_response(message: str, message_code: int) -> Response: """Produce common json output.""" return HomeAssistantView.json({"message": message, "code": message_code}, 200)
[ "def", "json_message_response", "(", "message", ":", "str", ",", "message_code", ":", "int", ")", "->", "Response", ":", "return", "HomeAssistantView", ".", "json", "(", "{", "\"message\"", ":", "message", ",", "\"code\"", ":", "message_code", "}", ",", "200", ")" ]
[ 505, 0 ]
[ 507, 82 ]
python
en
['fi', 'fr', 'en']
False
get_attribute_unique_id
(attribute: WithingsAttribute, user_id: int)
Get a entity unique id for a user's attribute.
Get a entity unique id for a user's attribute.
def get_attribute_unique_id(attribute: WithingsAttribute, user_id: int) -> str: """Get a entity unique id for a user's attribute.""" return f"withings_{user_id}_{attribute.measurement.value}"
[ "def", "get_attribute_unique_id", "(", "attribute", ":", "WithingsAttribute", ",", "user_id", ":", "int", ")", "->", "str", ":", "return", "f\"withings_{user_id}_{attribute.measurement.value}\"" ]
[ 902, 0 ]
[ 904, 62 ]
python
en
['en', 'en', 'en']
True
async_get_entity_id
( hass: HomeAssistant, attribute: WithingsAttribute, user_id: int )
Get an entity id for a user's attribute.
Get an entity id for a user's attribute.
async def async_get_entity_id( hass: HomeAssistant, attribute: WithingsAttribute, user_id: int ) -> Optional[str]: """Get an entity id for a user's attribute.""" entity_registry: EntityRegistry = ( await hass.helpers.entity_registry.async_get_registry() ) unique_id = get_attribute_unique_id(attribute, user_id) entity_id = entity_registry.async_get_entity_id( attribute.platform, const.DOMAIN, unique_id ) if entity_id is None: _LOGGER.error("Cannot find entity id for unique_id: %s", unique_id) return None return entity_id
[ "async", "def", "async_get_entity_id", "(", "hass", ":", "HomeAssistant", ",", "attribute", ":", "WithingsAttribute", ",", "user_id", ":", "int", ")", "->", "Optional", "[", "str", "]", ":", "entity_registry", ":", "EntityRegistry", "=", "(", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", ")", "unique_id", "=", "get_attribute_unique_id", "(", "attribute", ",", "user_id", ")", "entity_id", "=", "entity_registry", ".", "async_get_entity_id", "(", "attribute", ".", "platform", ",", "const", ".", "DOMAIN", ",", "unique_id", ")", "if", "entity_id", "is", "None", ":", "_LOGGER", ".", "error", "(", "\"Cannot find entity id for unique_id: %s\"", ",", "unique_id", ")", "return", "None", "return", "entity_id" ]
[ 907, 0 ]
[ 924, 20 ]
python
en
['en', 'en', 'en']
True
async_get_data_manager
( hass: HomeAssistant, config_entry: ConfigEntry )
Get the data manager for a config entry.
Get the data manager for a config entry.
async def async_get_data_manager( hass: HomeAssistant, config_entry: ConfigEntry ) -> DataManager: """Get the data manager for a config entry.""" hass.data.setdefault(const.DOMAIN, {}) hass.data[const.DOMAIN].setdefault(config_entry.entry_id, {}) config_entry_data = hass.data[const.DOMAIN][config_entry.entry_id] if const.DATA_MANAGER not in config_entry_data: profile = config_entry.data.get(const.PROFILE) _LOGGER.debug("Creating withings data manager for profile: %s", profile) config_entry_data[const.DATA_MANAGER] = DataManager( hass, profile, ConfigEntryWithingsApi( hass=hass, config_entry=config_entry, implementation=await config_entry_oauth2_flow.async_get_config_entry_implementation( hass, config_entry ), ), config_entry.data["token"]["userid"], WebhookConfig( id=config_entry.data[CONF_WEBHOOK_ID], url=config_entry.data[const.CONF_WEBHOOK_URL], enabled=config_entry.data[const.CONF_USE_WEBHOOK], ), ) return config_entry_data[const.DATA_MANAGER]
[ "async", "def", "async_get_data_manager", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ")", "->", "DataManager", ":", "hass", ".", "data", ".", "setdefault", "(", "const", ".", "DOMAIN", ",", "{", "}", ")", "hass", ".", "data", "[", "const", ".", "DOMAIN", "]", ".", "setdefault", "(", "config_entry", ".", "entry_id", ",", "{", "}", ")", "config_entry_data", "=", "hass", ".", "data", "[", "const", ".", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "if", "const", ".", "DATA_MANAGER", "not", "in", "config_entry_data", ":", "profile", "=", "config_entry", ".", "data", ".", "get", "(", "const", ".", "PROFILE", ")", "_LOGGER", ".", "debug", "(", "\"Creating withings data manager for profile: %s\"", ",", "profile", ")", "config_entry_data", "[", "const", ".", "DATA_MANAGER", "]", "=", "DataManager", "(", "hass", ",", "profile", ",", "ConfigEntryWithingsApi", "(", "hass", "=", "hass", ",", "config_entry", "=", "config_entry", ",", "implementation", "=", "await", "config_entry_oauth2_flow", ".", "async_get_config_entry_implementation", "(", "hass", ",", "config_entry", ")", ",", ")", ",", "config_entry", ".", "data", "[", "\"token\"", "]", "[", "\"userid\"", "]", ",", "WebhookConfig", "(", "id", "=", "config_entry", ".", "data", "[", "CONF_WEBHOOK_ID", "]", ",", "url", "=", "config_entry", ".", "data", "[", "const", ".", "CONF_WEBHOOK_URL", "]", ",", "enabled", "=", "config_entry", ".", "data", "[", "const", ".", "CONF_USE_WEBHOOK", "]", ",", ")", ",", ")", "return", "config_entry_data", "[", "const", ".", "DATA_MANAGER", "]" ]
[ 1020, 0 ]
[ 1050, 48 ]
python
en
['en', 'en', 'en']
True
get_data_manager_by_webhook_id
( hass: HomeAssistant, webhook_id: str )
Get a data manager by it's webhook id.
Get a data manager by it's webhook id.
def get_data_manager_by_webhook_id( hass: HomeAssistant, webhook_id: str ) -> Optional[DataManager]: """Get a data manager by it's webhook id.""" return next( iter( [ data_manager for data_manager in get_all_data_managers(hass) if data_manager.webhook_config.id == webhook_id ] ), None, )
[ "def", "get_data_manager_by_webhook_id", "(", "hass", ":", "HomeAssistant", ",", "webhook_id", ":", "str", ")", "->", "Optional", "[", "DataManager", "]", ":", "return", "next", "(", "iter", "(", "[", "data_manager", "for", "data_manager", "in", "get_all_data_managers", "(", "hass", ")", "if", "data_manager", ".", "webhook_config", ".", "id", "==", "webhook_id", "]", ")", ",", "None", ",", ")" ]
[ 1053, 0 ]
[ 1066, 5 ]
python
en
['en', 'en', 'en']
True
get_all_data_managers
(hass: HomeAssistant)
Get all configured data managers.
Get all configured data managers.
def get_all_data_managers(hass: HomeAssistant) -> Tuple[DataManager, ...]: """Get all configured data managers.""" return tuple( [ config_entry_data[const.DATA_MANAGER] for config_entry_data in hass.data[const.DOMAIN].values() if const.DATA_MANAGER in config_entry_data ] )
[ "def", "get_all_data_managers", "(", "hass", ":", "HomeAssistant", ")", "->", "Tuple", "[", "DataManager", ",", "...", "]", ":", "return", "tuple", "(", "[", "config_entry_data", "[", "const", ".", "DATA_MANAGER", "]", "for", "config_entry_data", "in", "hass", ".", "data", "[", "const", ".", "DOMAIN", "]", ".", "values", "(", ")", "if", "const", ".", "DATA_MANAGER", "in", "config_entry_data", "]", ")" ]
[ 1069, 0 ]
[ 1077, 5 ]
python
en
['en', 'en', 'en']
True
async_remove_data_manager
(hass: HomeAssistant, config_entry: ConfigEntry)
Remove a data manager for a config entry.
Remove a data manager for a config entry.
def async_remove_data_manager(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Remove a data manager for a config entry.""" del hass.data[const.DOMAIN][config_entry.entry_id][const.DATA_MANAGER]
[ "def", "async_remove_data_manager", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ")", "->", "None", ":", "del", "hass", ".", "data", "[", "const", ".", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "const", ".", "DATA_MANAGER", "]" ]
[ 1080, 0 ]
[ 1082, 74 ]
python
en
['en', 'en', 'en']
True
async_create_entities
( hass: HomeAssistant, entry: ConfigEntry, create_func: Callable[[DataManager, WithingsAttribute], Entity], platform: str, )
Create withings entities from config entry.
Create withings entities from config entry.
async def async_create_entities( hass: HomeAssistant, entry: ConfigEntry, create_func: Callable[[DataManager, WithingsAttribute], Entity], platform: str, ) -> List[Entity]: """Create withings entities from config entry.""" data_manager = await async_get_data_manager(hass, entry) return [ create_func(data_manager, attribute) for attribute in get_platform_attributes(platform) ]
[ "async", "def", "async_create_entities", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ",", "create_func", ":", "Callable", "[", "[", "DataManager", ",", "WithingsAttribute", "]", ",", "Entity", "]", ",", "platform", ":", "str", ",", ")", "->", "List", "[", "Entity", "]", ":", "data_manager", "=", "await", "async_get_data_manager", "(", "hass", ",", "entry", ")", "return", "[", "create_func", "(", "data_manager", ",", "attribute", ")", "for", "attribute", "in", "get_platform_attributes", "(", "platform", ")", "]" ]
[ 1085, 0 ]
[ 1097, 5 ]
python
en
['en', 'en', 'en']
True
get_platform_attributes
(platform: str)
Get withings attributes used for a specific platform.
Get withings attributes used for a specific platform.
def get_platform_attributes(platform: str) -> Tuple[WithingsAttribute, ...]: """Get withings attributes used for a specific platform.""" return tuple( [ attribute for attribute in WITHINGS_ATTRIBUTES if attribute.platform == platform ] )
[ "def", "get_platform_attributes", "(", "platform", ":", "str", ")", "->", "Tuple", "[", "WithingsAttribute", ",", "...", "]", ":", "return", "tuple", "(", "[", "attribute", "for", "attribute", "in", "WITHINGS_ATTRIBUTES", "if", "attribute", ".", "platform", "==", "platform", "]", ")" ]
[ 1100, 0 ]
[ 1108, 5 ]
python
en
['en', 'en', 'en']
True
ConfigEntryWithingsApi.__init__
( self, hass: HomeAssistant, config_entry: ConfigEntry, implementation: AbstractOAuth2Implementation, )
Initialize object.
Initialize object.
def __init__( self, hass: HomeAssistant, config_entry: ConfigEntry, implementation: AbstractOAuth2Implementation, ): """Initialize object.""" self._hass = hass self._config_entry = config_entry self._implementation = implementation self.session = OAuth2Session(hass, config_entry, implementation)
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ",", "implementation", ":", "AbstractOAuth2Implementation", ",", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_config_entry", "=", "config_entry", "self", ".", "_implementation", "=", "implementation", "self", ".", "session", "=", "OAuth2Session", "(", "hass", ",", "config_entry", ",", "implementation", ")" ]
[ 475, 4 ]
[ 485, 72 ]
python
en
['en', 'en', 'it']
False
ConfigEntryWithingsApi._request
( self, path: str, params: Dict[str, Any], method: str = "GET" )
Perform an async request.
Perform an async request.
def _request( self, path: str, params: Dict[str, Any], method: str = "GET" ) -> Dict[str, Any]: """Perform an async request.""" asyncio.run_coroutine_threadsafe( self.session.async_ensure_token_valid(), self._hass.loop ) access_token = self._config_entry.data["token"]["access_token"] response = requests.request( method, f"{self.URL}/{path}", params=params, headers={"Authorization": f"Bearer {access_token}"}, ) return response.json()
[ "def", "_request", "(", "self", ",", "path", ":", "str", ",", "params", ":", "Dict", "[", "str", ",", "Any", "]", ",", "method", ":", "str", "=", "\"GET\"", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "session", ".", "async_ensure_token_valid", "(", ")", ",", "self", ".", "_hass", ".", "loop", ")", "access_token", "=", "self", ".", "_config_entry", ".", "data", "[", "\"token\"", "]", "[", "\"access_token\"", "]", "response", "=", "requests", ".", "request", "(", "method", ",", "f\"{self.URL}/{path}\"", ",", "params", "=", "params", ",", "headers", "=", "{", "\"Authorization\"", ":", "f\"Bearer {access_token}\"", "}", ",", ")", "return", "response", ".", "json", "(", ")" ]
[ 487, 4 ]
[ 502, 30 ]
python
en
['en', 'en', 'en']
True
WebhookUpdateCoordinator.__init__
(self, hass: HomeAssistant, user_id: int)
Initialize the object.
Initialize the object.
def __init__(self, hass: HomeAssistant, user_id: int) -> None: """Initialize the object.""" self._hass = hass self._user_id = user_id self._listeners: List[CALLBACK_TYPE] = [] self.data: MeasurementData = {}
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "user_id", ":", "int", ")", "->", "None", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_user_id", "=", "user_id", "self", ".", "_listeners", ":", "List", "[", "CALLBACK_TYPE", "]", "=", "[", "]", "self", ".", "data", ":", "MeasurementData", "=", "{", "}" ]
[ 522, 4 ]
[ 527, 39 ]
python
en
['en', 'en', 'en']
True
WebhookUpdateCoordinator.async_add_listener
(self, listener: CALLBACK_TYPE)
Add a listener.
Add a listener.
def async_add_listener(self, listener: CALLBACK_TYPE) -> Callable[[], None]: """Add a listener.""" self._listeners.append(listener) @callback def remove_listener() -> None: self.async_remove_listener(listener) return remove_listener
[ "def", "async_add_listener", "(", "self", ",", "listener", ":", "CALLBACK_TYPE", ")", "->", "Callable", "[", "[", "]", ",", "None", "]", ":", "self", ".", "_listeners", ".", "append", "(", "listener", ")", "@", "callback", "def", "remove_listener", "(", ")", "->", "None", ":", "self", ".", "async_remove_listener", "(", "listener", ")", "return", "remove_listener" ]
[ 529, 4 ]
[ 537, 30 ]
python
en
['en', 'cy', 'en']
True
WebhookUpdateCoordinator.async_remove_listener
(self, listener: CALLBACK_TYPE)
Remove a listener.
Remove a listener.
def async_remove_listener(self, listener: CALLBACK_TYPE) -> None: """Remove a listener.""" self._listeners.remove(listener)
[ "def", "async_remove_listener", "(", "self", ",", "listener", ":", "CALLBACK_TYPE", ")", "->", "None", ":", "self", ".", "_listeners", ".", "remove", "(", "listener", ")" ]
[ 539, 4 ]
[ 541, 40 ]
python
en
['es', 'it', 'en']
False
WebhookUpdateCoordinator.update_data
(self, measurement: Measurement, value: Any)
Update the data object and notify listeners the data has changed.
Update the data object and notify listeners the data has changed.
def update_data(self, measurement: Measurement, value: Any) -> None: """Update the data object and notify listeners the data has changed.""" self.data[measurement] = value self.notify_data_changed()
[ "def", "update_data", "(", "self", ",", "measurement", ":", "Measurement", ",", "value", ":", "Any", ")", "->", "None", ":", "self", ".", "data", "[", "measurement", "]", "=", "value", "self", ".", "notify_data_changed", "(", ")" ]
[ 543, 4 ]
[ 546, 34 ]
python
en
['en', 'en', 'en']
True
WebhookUpdateCoordinator.notify_data_changed
(self)
Notify all listeners the data has changed.
Notify all listeners the data has changed.
def notify_data_changed(self) -> None: """Notify all listeners the data has changed.""" for listener in self._listeners: listener()
[ "def", "notify_data_changed", "(", "self", ")", "->", "None", ":", "for", "listener", "in", "self", ".", "_listeners", ":", "listener", "(", ")" ]
[ 548, 4 ]
[ 551, 22 ]
python
en
['en', 'en', 'en']
True
DataManager.__init__
( self, hass: HomeAssistant, profile: str, api: ConfigEntryWithingsApi, user_id: int, webhook_config: WebhookConfig, )
Initialize the data manager.
Initialize the data manager.
def __init__( self, hass: HomeAssistant, profile: str, api: ConfigEntryWithingsApi, user_id: int, webhook_config: WebhookConfig, ): """Initialize the data manager.""" self._hass = hass self._api = api self._user_id = user_id self._profile = profile self._webhook_config = webhook_config self._notify_subscribe_delay = datetime.timedelta(seconds=5) self._notify_unsubscribe_delay = datetime.timedelta(seconds=1) self._is_available = True self._cancel_interval_update_interval: Optional[CALLBACK_TYPE] = None self._cancel_configure_webhook_subscribe_interval: Optional[ CALLBACK_TYPE ] = None self._api_notification_id = f"withings_{self._user_id}" self.subscription_update_coordinator = DataUpdateCoordinator( hass, _LOGGER, name="subscription_update_coordinator", update_interval=timedelta(minutes=120), update_method=self.async_subscribe_webhook, ) self.poll_data_update_coordinator = DataUpdateCoordinator[ Dict[MeasureType, Any] ]( hass, _LOGGER, name="poll_data_update_coordinator", update_interval=timedelta(minutes=120) if self._webhook_config.enabled else timedelta(minutes=10), update_method=self.async_get_all_data, ) self.webhook_update_coordinator = WebhookUpdateCoordinator( self._hass, self._user_id ) self._cancel_subscription_update: Optional[Callable[[], None]] = None self._subscribe_webhook_run_count = 0
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "profile", ":", "str", ",", "api", ":", "ConfigEntryWithingsApi", ",", "user_id", ":", "int", ",", "webhook_config", ":", "WebhookConfig", ",", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_api", "=", "api", "self", ".", "_user_id", "=", "user_id", "self", ".", "_profile", "=", "profile", "self", ".", "_webhook_config", "=", "webhook_config", "self", ".", "_notify_subscribe_delay", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "5", ")", "self", ".", "_notify_unsubscribe_delay", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "1", ")", "self", ".", "_is_available", "=", "True", "self", ".", "_cancel_interval_update_interval", ":", "Optional", "[", "CALLBACK_TYPE", "]", "=", "None", "self", ".", "_cancel_configure_webhook_subscribe_interval", ":", "Optional", "[", "CALLBACK_TYPE", "]", "=", "None", "self", ".", "_api_notification_id", "=", "f\"withings_{self._user_id}\"", "self", ".", "subscription_update_coordinator", "=", "DataUpdateCoordinator", "(", "hass", ",", "_LOGGER", ",", "name", "=", "\"subscription_update_coordinator\"", ",", "update_interval", "=", "timedelta", "(", "minutes", "=", "120", ")", ",", "update_method", "=", "self", ".", "async_subscribe_webhook", ",", ")", "self", ".", "poll_data_update_coordinator", "=", "DataUpdateCoordinator", "[", "Dict", "[", "MeasureType", ",", "Any", "]", "]", "(", "hass", ",", "_LOGGER", ",", "name", "=", "\"poll_data_update_coordinator\"", ",", "update_interval", "=", "timedelta", "(", "minutes", "=", "120", ")", "if", "self", ".", "_webhook_config", ".", "enabled", "else", "timedelta", "(", "minutes", "=", "10", ")", ",", "update_method", "=", "self", ".", "async_get_all_data", ",", ")", "self", ".", "webhook_update_coordinator", "=", "WebhookUpdateCoordinator", "(", "self", ".", "_hass", ",", "self", ".", "_user_id", ")", "self", ".", "_cancel_subscription_update", ":", "Optional", "[", "Callable", "[", "[", "]", ",", "None", "]", "]", "=", "None", "self", ".", "_subscribe_webhook_run_count", "=", "0" ]
[ 557, 4 ]
[ 603, 45 ]
python
en
['en', 'en', 'en']
True
DataManager.webhook_config
(self)
Get the webhook config.
Get the webhook config.
def webhook_config(self) -> WebhookConfig: """Get the webhook config.""" return self._webhook_config
[ "def", "webhook_config", "(", "self", ")", "->", "WebhookConfig", ":", "return", "self", ".", "_webhook_config" ]
[ 606, 4 ]
[ 608, 35 ]
python
en
['en', 'en', 'en']
True
DataManager.user_id
(self)
Get the user_id of the authenticated user.
Get the user_id of the authenticated user.
def user_id(self) -> int: """Get the user_id of the authenticated user.""" return self._user_id
[ "def", "user_id", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_user_id" ]
[ 611, 4 ]
[ 613, 28 ]
python
en
['en', 'en', 'en']
True
DataManager.profile
(self)
Get the profile.
Get the profile.
def profile(self) -> str: """Get the profile.""" return self._profile
[ "def", "profile", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_profile" ]
[ 616, 4 ]
[ 618, 28 ]
python
en
['en', 'en', 'en']
True
DataManager.async_start_polling_webhook_subscriptions
(self)
Start polling webhook subscriptions (if enabled) to reconcile their setup.
Start polling webhook subscriptions (if enabled) to reconcile their setup.
def async_start_polling_webhook_subscriptions(self) -> None: """Start polling webhook subscriptions (if enabled) to reconcile their setup.""" self.async_stop_polling_webhook_subscriptions() def empty_listener() -> None: pass self._cancel_subscription_update = ( self.subscription_update_coordinator.async_add_listener(empty_listener) )
[ "def", "async_start_polling_webhook_subscriptions", "(", "self", ")", "->", "None", ":", "self", ".", "async_stop_polling_webhook_subscriptions", "(", ")", "def", "empty_listener", "(", ")", "->", "None", ":", "pass", "self", ".", "_cancel_subscription_update", "=", "(", "self", ".", "subscription_update_coordinator", ".", "async_add_listener", "(", "empty_listener", ")", ")" ]
[ 620, 4 ]
[ 629, 9 ]
python
en
['en', 'en', 'en']
True
DataManager.async_stop_polling_webhook_subscriptions
(self)
Stop polling webhook subscriptions.
Stop polling webhook subscriptions.
def async_stop_polling_webhook_subscriptions(self) -> None: """Stop polling webhook subscriptions.""" if self._cancel_subscription_update: self._cancel_subscription_update() self._cancel_subscription_update = None
[ "def", "async_stop_polling_webhook_subscriptions", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_cancel_subscription_update", ":", "self", ".", "_cancel_subscription_update", "(", ")", "self", ".", "_cancel_subscription_update", "=", "None" ]
[ 631, 4 ]
[ 635, 51 ]
python
en
['en', 'en', 'en']
True
DataManager._do_retry
(self, func, attempts=3)
Retry a function call. Withings' API occasionally and incorrectly throws errors. Retrying the call tends to work.
Retry a function call.
async def _do_retry(self, func, attempts=3) -> Any: """Retry a function call. Withings' API occasionally and incorrectly throws errors. Retrying the call tends to work. """ exception = None for attempt in range(1, attempts + 1): _LOGGER.debug("Attempt %s of %s", attempt, attempts) try: return await func() except Exception as exception1: # pylint: disable=broad-except await asyncio.sleep(0.1) exception = exception1 continue if exception: raise exception
[ "async", "def", "_do_retry", "(", "self", ",", "func", ",", "attempts", "=", "3", ")", "->", "Any", ":", "exception", "=", "None", "for", "attempt", "in", "range", "(", "1", ",", "attempts", "+", "1", ")", ":", "_LOGGER", ".", "debug", "(", "\"Attempt %s of %s\"", ",", "attempt", ",", "attempts", ")", "try", ":", "return", "await", "func", "(", ")", "except", "Exception", "as", "exception1", ":", "# pylint: disable=broad-except", "await", "asyncio", ".", "sleep", "(", "0.1", ")", "exception", "=", "exception1", "continue", "if", "exception", ":", "raise", "exception" ]
[ 637, 4 ]
[ 653, 27 ]
python
en
['en', 'en', 'en']
True
DataManager.async_subscribe_webhook
(self)
Subscribe the webhook to withings data updates.
Subscribe the webhook to withings data updates.
async def async_subscribe_webhook(self) -> None: """Subscribe the webhook to withings data updates.""" return await self._do_retry(self._async_subscribe_webhook)
[ "async", "def", "async_subscribe_webhook", "(", "self", ")", "->", "None", ":", "return", "await", "self", ".", "_do_retry", "(", "self", ".", "_async_subscribe_webhook", ")" ]
[ 655, 4 ]
[ 657, 66 ]
python
en
['en', 'en', 'en']
True
DataManager.async_unsubscribe_webhook
(self)
Unsubscribe webhook from withings data updates.
Unsubscribe webhook from withings data updates.
async def async_unsubscribe_webhook(self) -> None: """Unsubscribe webhook from withings data updates.""" return await self._do_retry(self._async_unsubscribe_webhook)
[ "async", "def", "async_unsubscribe_webhook", "(", "self", ")", "->", "None", ":", "return", "await", "self", ".", "_do_retry", "(", "self", ".", "_async_unsubscribe_webhook", ")" ]
[ 707, 4 ]
[ 709, 68 ]
python
en
['en', 'en', 'en']
True
DataManager.async_get_all_data
(self)
Update all withings data.
Update all withings data.
async def async_get_all_data(self) -> Optional[Dict[MeasureType, Any]]: """Update all withings data.""" try: return await self._do_retry(self._async_get_all_data) except Exception as exception: # User is not authenticated. if isinstance( exception, (UnauthorizedException, AuthFailedException) ) or NOT_AUTHENTICATED_ERROR.match(str(exception)): context = { const.PROFILE: self._profile, "userid": self._user_id, "source": "reauth", } # Check if reauth flow already exists. flow = next( iter( flow for flow in self._hass.config_entries.flow.async_progress() if flow.context == context ), None, ) if flow: return # Start a reauth flow. await self._hass.config_entries.flow.async_init( const.DOMAIN, context=context, ) return raise exception
[ "async", "def", "async_get_all_data", "(", "self", ")", "->", "Optional", "[", "Dict", "[", "MeasureType", ",", "Any", "]", "]", ":", "try", ":", "return", "await", "self", ".", "_do_retry", "(", "self", ".", "_async_get_all_data", ")", "except", "Exception", "as", "exception", ":", "# User is not authenticated.", "if", "isinstance", "(", "exception", ",", "(", "UnauthorizedException", ",", "AuthFailedException", ")", ")", "or", "NOT_AUTHENTICATED_ERROR", ".", "match", "(", "str", "(", "exception", ")", ")", ":", "context", "=", "{", "const", ".", "PROFILE", ":", "self", ".", "_profile", ",", "\"userid\"", ":", "self", ".", "_user_id", ",", "\"source\"", ":", "\"reauth\"", ",", "}", "# Check if reauth flow already exists.", "flow", "=", "next", "(", "iter", "(", "flow", "for", "flow", "in", "self", ".", "_hass", ".", "config_entries", ".", "flow", ".", "async_progress", "(", ")", "if", "flow", ".", "context", "==", "context", ")", ",", "None", ",", ")", "if", "flow", ":", "return", "# Start a reauth flow.", "await", "self", ".", "_hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "const", ".", "DOMAIN", ",", "context", "=", "context", ",", ")", "return", "raise", "exception" ]
[ 730, 4 ]
[ 764, 27 ]
python
en
['en', 'en', 'en']
True
DataManager.async_get_measures
(self)
Get the measures data.
Get the measures data.
async def async_get_measures(self) -> Dict[MeasureType, Any]: """Get the measures data.""" _LOGGER.debug("Updating withings measures") response = await self._hass.async_add_executor_job(self._api.measure_get_meas) # Sort from oldest to newest. groups = sorted( query_measure_groups( response, MeasureTypes.ANY, MeasureGroupAttribs.UNAMBIGUOUS ), key=lambda group: group.created.datetime, reverse=False, ) return { WITHINGS_MEASURE_TYPE_MAP[measure.type].measurement: round( float(measure.value * pow(10, measure.unit)), 2 ) for group in groups for measure in group.measures }
[ "async", "def", "async_get_measures", "(", "self", ")", "->", "Dict", "[", "MeasureType", ",", "Any", "]", ":", "_LOGGER", ".", "debug", "(", "\"Updating withings measures\"", ")", "response", "=", "await", "self", ".", "_hass", ".", "async_add_executor_job", "(", "self", ".", "_api", ".", "measure_get_meas", ")", "# Sort from oldest to newest.", "groups", "=", "sorted", "(", "query_measure_groups", "(", "response", ",", "MeasureTypes", ".", "ANY", ",", "MeasureGroupAttribs", ".", "UNAMBIGUOUS", ")", ",", "key", "=", "lambda", "group", ":", "group", ".", "created", ".", "datetime", ",", "reverse", "=", "False", ",", ")", "return", "{", "WITHINGS_MEASURE_TYPE_MAP", "[", "measure", ".", "type", "]", ".", "measurement", ":", "round", "(", "float", "(", "measure", ".", "value", "*", "pow", "(", "10", ",", "measure", ".", "unit", ")", ")", ",", "2", ")", "for", "group", "in", "groups", "for", "measure", "in", "group", ".", "measures", "}" ]
[ 773, 4 ]
[ 794, 9 ]
python
en
['en', 'en', 'en']
True
DataManager.async_get_sleep_summary
(self)
Get the sleep summary data.
Get the sleep summary data.
async def async_get_sleep_summary(self) -> Dict[MeasureType, Any]: """Get the sleep summary data.""" _LOGGER.debug("Updating withing sleep summary") now = dt.utcnow() yesterday = now - datetime.timedelta(days=1) yesterday_noon = datetime.datetime( yesterday.year, yesterday.month, yesterday.day, 12, 0, 0, 0, datetime.timezone.utc, ) def get_sleep_summary() -> SleepGetSummaryResponse: return self._api.sleep_get_summary( lastupdate=yesterday_noon, data_fields=[ GetSleepSummaryField.BREATHING_DISTURBANCES_INTENSITY, GetSleepSummaryField.DEEP_SLEEP_DURATION, GetSleepSummaryField.DURATION_TO_SLEEP, GetSleepSummaryField.DURATION_TO_WAKEUP, GetSleepSummaryField.HR_AVERAGE, GetSleepSummaryField.HR_MAX, GetSleepSummaryField.HR_MIN, GetSleepSummaryField.LIGHT_SLEEP_DURATION, GetSleepSummaryField.REM_SLEEP_DURATION, GetSleepSummaryField.RR_AVERAGE, GetSleepSummaryField.RR_MAX, GetSleepSummaryField.RR_MIN, GetSleepSummaryField.SLEEP_SCORE, GetSleepSummaryField.SNORING, GetSleepSummaryField.SNORING_EPISODE_COUNT, GetSleepSummaryField.WAKEUP_COUNT, GetSleepSummaryField.WAKEUP_DURATION, ], ) response = await self._hass.async_add_executor_job(get_sleep_summary) # Set the default to empty lists. raw_values: Dict[GetSleepSummaryField, List[int]] = { field: [] for field in GetSleepSummaryField } # Collect the raw data. for serie in response.series: data = serie.data for field in GetSleepSummaryField: raw_values[field].append(data._asdict()[field.value]) values: Dict[GetSleepSummaryField, float] = {} def average(data: List[int]) -> float: return sum(data) / len(data) def set_value(field: GetSleepSummaryField, func: Callable) -> None: non_nones = [ value for value in raw_values.get(field, []) if value is not None ] values[field] = func(non_nones) if non_nones else None set_value(GetSleepSummaryField.BREATHING_DISTURBANCES_INTENSITY, average) set_value(GetSleepSummaryField.DEEP_SLEEP_DURATION, sum) set_value(GetSleepSummaryField.DURATION_TO_SLEEP, average) set_value(GetSleepSummaryField.DURATION_TO_WAKEUP, average) set_value(GetSleepSummaryField.HR_AVERAGE, average) set_value(GetSleepSummaryField.HR_MAX, average) set_value(GetSleepSummaryField.HR_MIN, average) set_value(GetSleepSummaryField.LIGHT_SLEEP_DURATION, sum) set_value(GetSleepSummaryField.REM_SLEEP_DURATION, sum) set_value(GetSleepSummaryField.RR_AVERAGE, average) set_value(GetSleepSummaryField.RR_MAX, average) set_value(GetSleepSummaryField.RR_MIN, average) set_value(GetSleepSummaryField.SLEEP_SCORE, max) set_value(GetSleepSummaryField.SNORING, average) set_value(GetSleepSummaryField.SNORING_EPISODE_COUNT, sum) set_value(GetSleepSummaryField.WAKEUP_COUNT, sum) set_value(GetSleepSummaryField.WAKEUP_DURATION, average) return { WITHINGS_MEASURE_TYPE_MAP[field].measurement: round(value, 4) if value is not None else None for field, value in values.items() }
[ "async", "def", "async_get_sleep_summary", "(", "self", ")", "->", "Dict", "[", "MeasureType", ",", "Any", "]", ":", "_LOGGER", ".", "debug", "(", "\"Updating withing sleep summary\"", ")", "now", "=", "dt", ".", "utcnow", "(", ")", "yesterday", "=", "now", "-", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "yesterday_noon", "=", "datetime", ".", "datetime", "(", "yesterday", ".", "year", ",", "yesterday", ".", "month", ",", "yesterday", ".", "day", ",", "12", ",", "0", ",", "0", ",", "0", ",", "datetime", ".", "timezone", ".", "utc", ",", ")", "def", "get_sleep_summary", "(", ")", "->", "SleepGetSummaryResponse", ":", "return", "self", ".", "_api", ".", "sleep_get_summary", "(", "lastupdate", "=", "yesterday_noon", ",", "data_fields", "=", "[", "GetSleepSummaryField", ".", "BREATHING_DISTURBANCES_INTENSITY", ",", "GetSleepSummaryField", ".", "DEEP_SLEEP_DURATION", ",", "GetSleepSummaryField", ".", "DURATION_TO_SLEEP", ",", "GetSleepSummaryField", ".", "DURATION_TO_WAKEUP", ",", "GetSleepSummaryField", ".", "HR_AVERAGE", ",", "GetSleepSummaryField", ".", "HR_MAX", ",", "GetSleepSummaryField", ".", "HR_MIN", ",", "GetSleepSummaryField", ".", "LIGHT_SLEEP_DURATION", ",", "GetSleepSummaryField", ".", "REM_SLEEP_DURATION", ",", "GetSleepSummaryField", ".", "RR_AVERAGE", ",", "GetSleepSummaryField", ".", "RR_MAX", ",", "GetSleepSummaryField", ".", "RR_MIN", ",", "GetSleepSummaryField", ".", "SLEEP_SCORE", ",", "GetSleepSummaryField", ".", "SNORING", ",", "GetSleepSummaryField", ".", "SNORING_EPISODE_COUNT", ",", "GetSleepSummaryField", ".", "WAKEUP_COUNT", ",", "GetSleepSummaryField", ".", "WAKEUP_DURATION", ",", "]", ",", ")", "response", "=", "await", "self", ".", "_hass", ".", "async_add_executor_job", "(", "get_sleep_summary", ")", "# Set the default to empty lists.", "raw_values", ":", "Dict", "[", "GetSleepSummaryField", ",", "List", "[", "int", "]", "]", "=", "{", "field", ":", "[", "]", "for", "field", "in", "GetSleepSummaryField", "}", "# Collect the raw data.", "for", "serie", "in", "response", ".", "series", ":", "data", "=", "serie", ".", "data", "for", "field", "in", "GetSleepSummaryField", ":", "raw_values", "[", "field", "]", ".", "append", "(", "data", ".", "_asdict", "(", ")", "[", "field", ".", "value", "]", ")", "values", ":", "Dict", "[", "GetSleepSummaryField", ",", "float", "]", "=", "{", "}", "def", "average", "(", "data", ":", "List", "[", "int", "]", ")", "->", "float", ":", "return", "sum", "(", "data", ")", "/", "len", "(", "data", ")", "def", "set_value", "(", "field", ":", "GetSleepSummaryField", ",", "func", ":", "Callable", ")", "->", "None", ":", "non_nones", "=", "[", "value", "for", "value", "in", "raw_values", ".", "get", "(", "field", ",", "[", "]", ")", "if", "value", "is", "not", "None", "]", "values", "[", "field", "]", "=", "func", "(", "non_nones", ")", "if", "non_nones", "else", "None", "set_value", "(", "GetSleepSummaryField", ".", "BREATHING_DISTURBANCES_INTENSITY", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "DEEP_SLEEP_DURATION", ",", "sum", ")", "set_value", "(", "GetSleepSummaryField", ".", "DURATION_TO_SLEEP", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "DURATION_TO_WAKEUP", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "HR_AVERAGE", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "HR_MAX", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "HR_MIN", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "LIGHT_SLEEP_DURATION", ",", "sum", ")", "set_value", "(", "GetSleepSummaryField", ".", "REM_SLEEP_DURATION", ",", "sum", ")", "set_value", "(", "GetSleepSummaryField", ".", "RR_AVERAGE", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "RR_MAX", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "RR_MIN", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "SLEEP_SCORE", ",", "max", ")", "set_value", "(", "GetSleepSummaryField", ".", "SNORING", ",", "average", ")", "set_value", "(", "GetSleepSummaryField", ".", "SNORING_EPISODE_COUNT", ",", "sum", ")", "set_value", "(", "GetSleepSummaryField", ".", "WAKEUP_COUNT", ",", "sum", ")", "set_value", "(", "GetSleepSummaryField", ".", "WAKEUP_DURATION", ",", "average", ")", "return", "{", "WITHINGS_MEASURE_TYPE_MAP", "[", "field", "]", ".", "measurement", ":", "round", "(", "value", ",", "4", ")", "if", "value", "is", "not", "None", "else", "None", "for", "field", ",", "value", "in", "values", ".", "items", "(", ")", "}" ]
[ 796, 4 ]
[ 884, 9 ]
python
en
['en', 'ga', 'en']
True
DataManager.async_webhook_data_updated
(self, data_category: NotifyAppli)
Handle scenario when data is updated from a webook.
Handle scenario when data is updated from a webook.
async def async_webhook_data_updated(self, data_category: NotifyAppli) -> None: """Handle scenario when data is updated from a webook.""" _LOGGER.debug("Withings webhook triggered") if data_category in { NotifyAppli.WEIGHT, NotifyAppli.CIRCULATORY, NotifyAppli.SLEEP, }: await self.poll_data_update_coordinator.async_request_refresh() elif data_category in {NotifyAppli.BED_IN, NotifyAppli.BED_OUT}: self.webhook_update_coordinator.update_data( Measurement.IN_BED, data_category == NotifyAppli.BED_IN )
[ "async", "def", "async_webhook_data_updated", "(", "self", ",", "data_category", ":", "NotifyAppli", ")", "->", "None", ":", "_LOGGER", ".", "debug", "(", "\"Withings webhook triggered\"", ")", "if", "data_category", "in", "{", "NotifyAppli", ".", "WEIGHT", ",", "NotifyAppli", ".", "CIRCULATORY", ",", "NotifyAppli", ".", "SLEEP", ",", "}", ":", "await", "self", ".", "poll_data_update_coordinator", ".", "async_request_refresh", "(", ")", "elif", "data_category", "in", "{", "NotifyAppli", ".", "BED_IN", ",", "NotifyAppli", ".", "BED_OUT", "}", ":", "self", ".", "webhook_update_coordinator", ".", "update_data", "(", "Measurement", ".", "IN_BED", ",", "data_category", "==", "NotifyAppli", ".", "BED_IN", ")" ]
[ 886, 4 ]
[ 899, 13 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.__init__
(self, data_manager: DataManager, attribute: WithingsAttribute)
Initialize the Withings sensor.
Initialize the Withings sensor.
def __init__(self, data_manager: DataManager, attribute: WithingsAttribute) -> None: """Initialize the Withings sensor.""" self._data_manager = data_manager self._attribute = attribute self._profile = self._data_manager.profile self._user_id = self._data_manager.user_id self._name = f"Withings {self._attribute.measurement.value} {self._profile}" self._unique_id = get_attribute_unique_id(self._attribute, self._user_id) self._state_data: Optional[Any] = None
[ "def", "__init__", "(", "self", ",", "data_manager", ":", "DataManager", ",", "attribute", ":", "WithingsAttribute", ")", "->", "None", ":", "self", ".", "_data_manager", "=", "data_manager", "self", ".", "_attribute", "=", "attribute", "self", ".", "_profile", "=", "self", ".", "_data_manager", ".", "profile", "self", ".", "_user_id", "=", "self", ".", "_data_manager", ".", "user_id", "self", ".", "_name", "=", "f\"Withings {self._attribute.measurement.value} {self._profile}\"", "self", ".", "_unique_id", "=", "get_attribute_unique_id", "(", "self", ".", "_attribute", ",", "self", ".", "_user_id", ")", "self", ".", "_state_data", ":", "Optional", "[", "Any", "]", "=", "None" ]
[ 930, 4 ]
[ 938, 46 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.should_poll
(self)
Return False to indicate HA should not poll for changes.
Return False to indicate HA should not poll for changes.
def should_poll(self) -> bool: """Return False to indicate HA should not poll for changes.""" return False
[ "def", "should_poll", "(", "self", ")", "->", "bool", ":", "return", "False" ]
[ 941, 4 ]
[ 943, 20 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self) -> str: """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_name" ]
[ 946, 4 ]
[ 948, 25 ]
python
en
['en', 'mi', 'en']
True
BaseWithingsSensor.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self) -> bool: """Return True if entity is available.""" if self._attribute.update_type == UpdateType.POLL: return self._data_manager.poll_data_update_coordinator.last_update_success if self._attribute.update_type == UpdateType.WEBHOOK: return self._data_manager.webhook_config.enabled and ( self._attribute.measurement in self._data_manager.webhook_update_coordinator.data ) return True
[ "def", "available", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_attribute", ".", "update_type", "==", "UpdateType", ".", "POLL", ":", "return", "self", ".", "_data_manager", ".", "poll_data_update_coordinator", ".", "last_update_success", "if", "self", ".", "_attribute", ".", "update_type", "==", "UpdateType", ".", "WEBHOOK", ":", "return", "self", ".", "_data_manager", ".", "webhook_config", ".", "enabled", "and", "(", "self", ".", "_attribute", ".", "measurement", "in", "self", ".", "_data_manager", ".", "webhook_update_coordinator", ".", "data", ")", "return", "True" ]
[ 951, 4 ]
[ 962, 19 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.unique_id
(self)
Return a unique, Home Assistant friendly identifier for this entity.
Return a unique, Home Assistant friendly identifier for this entity.
def unique_id(self) -> str: """Return a unique, Home Assistant friendly identifier for this entity.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_unique_id" ]
[ 965, 4 ]
[ 967, 30 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.unit_of_measurement
(self)
Return the unit of measurement of this entity, if any.
Return the unit of measurement of this entity, if any.
def unit_of_measurement(self) -> str: """Return the unit of measurement of this entity, if any.""" return self._attribute.unit_of_measurement
[ "def", "unit_of_measurement", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_attribute", ".", "unit_of_measurement" ]
[ 970, 4 ]
[ 972, 50 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.icon
(self)
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
def icon(self) -> str: """Icon to use in the frontend, if any.""" return self._attribute.icon
[ "def", "icon", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_attribute", ".", "icon" ]
[ 975, 4 ]
[ 977, 35 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.entity_registry_enabled_default
(self)
Return if the entity should be enabled when first added to the entity registry.
Return if the entity should be enabled when first added to the entity registry.
def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return self._attribute.enabled_by_default
[ "def", "entity_registry_enabled_default", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_attribute", ".", "enabled_by_default" ]
[ 980, 4 ]
[ 982, 49 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor._update_state_data
(self, data: MeasurementData)
Update the state data.
Update the state data.
def _update_state_data(self, data: MeasurementData) -> None: """Update the state data.""" self._state_data = data.get(self._attribute.measurement) self.async_write_ha_state()
[ "def", "_update_state_data", "(", "self", ",", "data", ":", "MeasurementData", ")", "->", "None", ":", "self", ".", "_state_data", "=", "data", ".", "get", "(", "self", ".", "_attribute", ".", "measurement", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 996, 4 ]
[ 999, 35 ]
python
en
['en', 'en', 'en']
True
BaseWithingsSensor.async_added_to_hass
(self)
Register update dispatcher.
Register update dispatcher.
async def async_added_to_hass(self) -> None: """Register update dispatcher.""" if self._attribute.update_type == UpdateType.POLL: self.async_on_remove( self._data_manager.poll_data_update_coordinator.async_add_listener( self._on_poll_data_updated ) ) self._on_poll_data_updated() elif self._attribute.update_type == UpdateType.WEBHOOK: self.async_on_remove( self._data_manager.webhook_update_coordinator.async_add_listener( self._on_webhook_data_updated ) ) self._on_webhook_data_updated()
[ "async", "def", "async_added_to_hass", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_attribute", ".", "update_type", "==", "UpdateType", ".", "POLL", ":", "self", ".", "async_on_remove", "(", "self", ".", "_data_manager", ".", "poll_data_update_coordinator", ".", "async_add_listener", "(", "self", ".", "_on_poll_data_updated", ")", ")", "self", ".", "_on_poll_data_updated", "(", ")", "elif", "self", ".", "_attribute", ".", "update_type", "==", "UpdateType", ".", "WEBHOOK", ":", "self", ".", "async_on_remove", "(", "self", ".", "_data_manager", ".", "webhook_update_coordinator", ".", "async_add_listener", "(", "self", ".", "_on_webhook_data_updated", ")", ")", "self", ".", "_on_webhook_data_updated", "(", ")" ]
[ 1001, 4 ]
[ 1017, 43 ]
python
de
['it', 'de', 'en']
False
WithingsLocalOAuth2Implementation.redirect_uri
(self)
Return the redirect uri.
Return the redirect uri.
def redirect_uri(self) -> str: """Return the redirect uri.""" url = get_url(self.hass, allow_internal=False, prefer_cloud=True) return f"{url}{AUTH_CALLBACK_PATH}"
[ "def", "redirect_uri", "(", "self", ")", "->", "str", ":", "url", "=", "get_url", "(", "self", ".", "hass", ",", "allow_internal", "=", "False", ",", "prefer_cloud", "=", "True", ")", "return", "f\"{url}{AUTH_CALLBACK_PATH}\"" ]
[ 1115, 4 ]
[ 1118, 43 ]
python
en
['en', 'hr', 'en']
True
async_setup_entry
( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], )
Set up from config entry.
Set up from config entry.
async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up from config entry.""" # Grab hosts list once to examine whether the initial fetch has got some data for # us, i.e. if wlan host list is supported. Only set up a subscription and proceed # with adding and tracking entities if it is. router = hass.data[DOMAIN].routers[config_entry.data[CONF_URL]] try: _ = router.data[KEY_WLAN_HOST_LIST]["Hosts"]["Host"] except KeyError: _LOGGER.debug("%s[%s][%s] not in data", KEY_WLAN_HOST_LIST, "Hosts", "Host") return # Initialize already tracked entities tracked: Set[str] = set() registry = await entity_registry.async_get_registry(hass) known_entities: List[Entity] = [] for entity in registry.entities.values(): if ( entity.domain == DEVICE_TRACKER_DOMAIN and entity.config_entry_id == config_entry.entry_id ): tracked.add(entity.unique_id) known_entities.append( HuaweiLteScannerEntity(router, entity.unique_id.partition("-")[2]) ) async_add_entities(known_entities, True) # Tell parent router to poll hosts list to gather new devices router.subscriptions[KEY_WLAN_HOST_LIST].add(_DEVICE_SCAN) async def _async_maybe_add_new_entities(url: str) -> None: """Add new entities if the update signal comes from our router.""" if url == router.url: async_add_new_entities(hass, url, async_add_entities, tracked) # Register to handle router data updates disconnect_dispatcher = async_dispatcher_connect( hass, UPDATE_SIGNAL, _async_maybe_add_new_entities ) router.unload_handlers.append(disconnect_dispatcher) # Add new entities from initial scan async_add_new_entities(hass, router.url, async_add_entities, tracked)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "config_entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "Callable", "[", "[", "List", "[", "Entity", "]", ",", "bool", "]", ",", "None", "]", ",", ")", "->", "None", ":", "# Grab hosts list once to examine whether the initial fetch has got some data for", "# us, i.e. if wlan host list is supported. Only set up a subscription and proceed", "# with adding and tracking entities if it is.", "router", "=", "hass", ".", "data", "[", "DOMAIN", "]", ".", "routers", "[", "config_entry", ".", "data", "[", "CONF_URL", "]", "]", "try", ":", "_", "=", "router", ".", "data", "[", "KEY_WLAN_HOST_LIST", "]", "[", "\"Hosts\"", "]", "[", "\"Host\"", "]", "except", "KeyError", ":", "_LOGGER", ".", "debug", "(", "\"%s[%s][%s] not in data\"", ",", "KEY_WLAN_HOST_LIST", ",", "\"Hosts\"", ",", "\"Host\"", ")", "return", "# Initialize already tracked entities", "tracked", ":", "Set", "[", "str", "]", "=", "set", "(", ")", "registry", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "known_entities", ":", "List", "[", "Entity", "]", "=", "[", "]", "for", "entity", "in", "registry", ".", "entities", ".", "values", "(", ")", ":", "if", "(", "entity", ".", "domain", "==", "DEVICE_TRACKER_DOMAIN", "and", "entity", ".", "config_entry_id", "==", "config_entry", ".", "entry_id", ")", ":", "tracked", ".", "add", "(", "entity", ".", "unique_id", ")", "known_entities", ".", "append", "(", "HuaweiLteScannerEntity", "(", "router", ",", "entity", ".", "unique_id", ".", "partition", "(", "\"-\"", ")", "[", "2", "]", ")", ")", "async_add_entities", "(", "known_entities", ",", "True", ")", "# Tell parent router to poll hosts list to gather new devices", "router", ".", "subscriptions", "[", "KEY_WLAN_HOST_LIST", "]", ".", "add", "(", "_DEVICE_SCAN", ")", "async", "def", "_async_maybe_add_new_entities", "(", "url", ":", "str", ")", "->", "None", ":", "\"\"\"Add new entities if the update signal comes from our router.\"\"\"", "if", "url", "==", "router", ".", "url", ":", "async_add_new_entities", "(", "hass", ",", "url", ",", "async_add_entities", ",", "tracked", ")", "# Register to handle router data updates", "disconnect_dispatcher", "=", "async_dispatcher_connect", "(", "hass", ",", "UPDATE_SIGNAL", ",", "_async_maybe_add_new_entities", ")", "router", ".", "unload_handlers", ".", "append", "(", "disconnect_dispatcher", ")", "# Add new entities from initial scan", "async_add_new_entities", "(", "hass", ",", "router", ".", "url", ",", "async_add_entities", ",", "tracked", ")" ]
[ 30, 0 ]
[ 77, 73 ]
python
en
['en', 'en', 'en']
True
async_add_new_entities
( hass: HomeAssistantType, router_url: str, async_add_entities: Callable[[List[Entity], bool], None], tracked: Set[str], )
Add new entities that are not already being tracked.
Add new entities that are not already being tracked.
def async_add_new_entities( hass: HomeAssistantType, router_url: str, async_add_entities: Callable[[List[Entity], bool], None], tracked: Set[str], ) -> None: """Add new entities that are not already being tracked.""" router = hass.data[DOMAIN].routers[router_url] try: hosts = router.data[KEY_WLAN_HOST_LIST]["Hosts"]["Host"] except KeyError: _LOGGER.debug("%s[%s][%s] not in data", KEY_WLAN_HOST_LIST, "Hosts", "Host") return new_entities: List[Entity] = [] for host in (x for x in hosts if x.get("MacAddress")): entity = HuaweiLteScannerEntity(router, host["MacAddress"]) if entity.unique_id in tracked: continue tracked.add(entity.unique_id) new_entities.append(entity) async_add_entities(new_entities, True)
[ "def", "async_add_new_entities", "(", "hass", ":", "HomeAssistantType", ",", "router_url", ":", "str", ",", "async_add_entities", ":", "Callable", "[", "[", "List", "[", "Entity", "]", ",", "bool", "]", ",", "None", "]", ",", "tracked", ":", "Set", "[", "str", "]", ",", ")", "->", "None", ":", "router", "=", "hass", ".", "data", "[", "DOMAIN", "]", ".", "routers", "[", "router_url", "]", "try", ":", "hosts", "=", "router", ".", "data", "[", "KEY_WLAN_HOST_LIST", "]", "[", "\"Hosts\"", "]", "[", "\"Host\"", "]", "except", "KeyError", ":", "_LOGGER", ".", "debug", "(", "\"%s[%s][%s] not in data\"", ",", "KEY_WLAN_HOST_LIST", ",", "\"Hosts\"", ",", "\"Host\"", ")", "return", "new_entities", ":", "List", "[", "Entity", "]", "=", "[", "]", "for", "host", "in", "(", "x", "for", "x", "in", "hosts", "if", "x", ".", "get", "(", "\"MacAddress\"", ")", ")", ":", "entity", "=", "HuaweiLteScannerEntity", "(", "router", ",", "host", "[", "\"MacAddress\"", "]", ")", "if", "entity", ".", "unique_id", "in", "tracked", ":", "continue", "tracked", ".", "add", "(", "entity", ".", "unique_id", ")", "new_entities", ".", "append", "(", "entity", ")", "async_add_entities", "(", "new_entities", ",", "True", ")" ]
[ 81, 0 ]
[ 102, 42 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_get_options_flow
(config_entry)
Return the options flow.
Return the options flow.
def async_get_options_flow(config_entry): """Return the options flow.""" return OptionsFlowHandler(config_entry)
[ "def", "async_get_options_flow", "(", "config_entry", ")", ":", "return", "OptionsFlowHandler", "(", "config_entry", ")" ]
[ 35, 4 ]
[ 37, 47 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.__init__
(self)
Initialize the config flow.
Initialize the config flow.
def __init__(self): """Initialize the config flow.""" self._discovered_devices = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_discovered_devices", "=", "{", "}" ]
[ 39, 4 ]
[ 41, 37 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_user
(self, user_input=None)
Handle the initial step.
Handle the initial step.
async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: if user_input.get(CONF_HOST): try: await self._async_try_connect(user_input[CONF_HOST]) return self.async_create_entry( title=user_input[CONF_HOST], data=user_input, ) except CannotConnect: errors["base"] = "cannot_connect" except AlreadyConfigured: return self.async_abort(reason="already_configured") else: return await self.async_step_pick_device() user_input = user_input or {} return self.async_show_form( step_id="user", data_schema=vol.Schema( {vol.Optional(CONF_HOST, default=user_input.get(CONF_HOST, "")): str} ), errors=errors, )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "if", "user_input", ".", "get", "(", "CONF_HOST", ")", ":", "try", ":", "await", "self", ".", "_async_try_connect", "(", "user_input", "[", "CONF_HOST", "]", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "user_input", "[", "CONF_HOST", "]", ",", "data", "=", "user_input", ",", ")", "except", "CannotConnect", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "except", "AlreadyConfigured", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"already_configured\"", ")", "else", ":", "return", "await", "self", ".", "async_step_pick_device", "(", ")", "user_input", "=", "user_input", "or", "{", "}", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_HOST", ",", "default", "=", "user_input", ".", "get", "(", "CONF_HOST", ",", "\"\"", ")", ")", ":", "str", "}", ")", ",", "errors", "=", "errors", ",", ")" ]
[ 43, 4 ]
[ 68, 9 ]
python
en
['en', 'en', 'en']
True