Merge of nested IF-IF cases - S-W (#48372)

This commit is contained in:
Franck Nijhof 2021-03-27 10:54:59 +01:00 committed by GitHub
parent 3aed84560f
commit 8d5ce53098
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 128 additions and 126 deletions

View file

@ -103,18 +103,18 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
for sensor in hass_sensors: for sensor in hass_sensors:
state_unknown = False state_unknown = False
if not values: # SAJ inverters are powered by DC via solar panels and thus are
# SAJ inverters are powered by DC via solar panels and thus are # offline after the sun has set. If a sensor resets on a daily
# offline after the sun has set. If a sensor resets on a daily # basis like "today_yield", this reset won't happen automatically.
# basis like "today_yield", this reset won't happen automatically. # Code below checks if today > day when sensor was last updated
# Code below checks if today > day when sensor was last updated # and if so: set state to None.
# and if so: set state to None. # Sensors with live values like "temperature" or "current_power"
# Sensors with live values like "temperature" or "current_power" # will also be reset to None.
# will also be reset to None. if not values and (
if (sensor.per_day_basis and date.today() > sensor.date_updated) or ( (sensor.per_day_basis and date.today() > sensor.date_updated)
not sensor.per_day_basis and not sensor.per_total_basis or (not sensor.per_day_basis and not sensor.per_total_basis)
): ):
state_unknown = True state_unknown = True
sensor.async_update_values(unknown_state=state_unknown) sensor.async_update_values(unknown_state=state_unknown)
return values return values

View file

@ -53,31 +53,32 @@ class SmhiFlowHandler(config_entries.ConfigFlow):
# If hass config has the location set and is a valid coordinate the # If hass config has the location set and is a valid coordinate the
# default location is set as default values in the form # default location is set as default values in the form
if not smhi_locations(self.hass): if (
if await self._homeassistant_location_exists(): not smhi_locations(self.hass)
return await self._show_config_form( and await self._homeassistant_location_exists()
name=HOME_LOCATION_NAME, ):
latitude=self.hass.config.latitude, return await self._show_config_form(
longitude=self.hass.config.longitude, name=HOME_LOCATION_NAME,
) latitude=self.hass.config.latitude,
longitude=self.hass.config.longitude,
)
return await self._show_config_form() return await self._show_config_form()
async def _homeassistant_location_exists(self) -> bool: async def _homeassistant_location_exists(self) -> bool:
"""Return true if default location is set and is valid.""" """Return true if default location is set and is valid."""
if self.hass.config.latitude != 0.0 and self.hass.config.longitude != 0.0: # Return true if valid location
# Return true if valid location return (
if await self._check_location( self.hass.config.latitude != 0.0
and self.hass.config.longitude != 0.0
and await self._check_location(
self.hass.config.longitude, self.hass.config.latitude self.hass.config.longitude, self.hass.config.latitude
): )
return True )
return False
def _name_in_configuration_exists(self, name: str) -> bool: def _name_in_configuration_exists(self, name: str) -> bool:
"""Return True if name exists in configuration.""" """Return True if name exists in configuration."""
if name in smhi_locations(self.hass): return name in smhi_locations(self.hass)
return True
return False
async def _show_config_form( async def _show_config_form(
self, name: str = None, latitude: str = None, longitude: str = None self, name: str = None, latitude: str = None, longitude: str = None
@ -97,7 +98,6 @@ class SmhiFlowHandler(config_entries.ConfigFlow):
async def _check_location(self, longitude: str, latitude: str) -> bool: async def _check_location(self, longitude: str, latitude: str) -> bool:
"""Return true if location is ok.""" """Return true if location is ok."""
try: try:
session = aiohttp_client.async_get_clientsession(self.hass) session = aiohttp_client.async_get_clientsession(self.hass)
smhi_api = Smhi(longitude, latitude, session=session) smhi_api = Smhi(longitude, latitude, session=session)

View file

@ -50,9 +50,8 @@ class HlsMasterPlaylistView(StreamView):
track = stream.add_provider("hls") track = stream.add_provider("hls")
stream.start() stream.start()
# Wait for a segment to be ready # Wait for a segment to be ready
if not track.segments: if not track.segments and not await track.recv():
if not await track.recv(): return web.HTTPNotFound()
return web.HTTPNotFound()
headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]} headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]}
return web.Response(body=self.render(track).encode("utf-8"), headers=headers) return web.Response(body=self.render(track).encode("utf-8"), headers=headers)
@ -110,9 +109,8 @@ class HlsPlaylistView(StreamView):
track = stream.add_provider("hls") track = stream.add_provider("hls")
stream.start() stream.start()
# Wait for a segment to be ready # Wait for a segment to be ready
if not track.segments: if not track.segments and not await track.recv():
if not await track.recv(): return web.HTTPNotFound()
return web.HTTPNotFound()
headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]} headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]}
return web.Response(body=self.render(track).encode("utf-8"), headers=headers) return web.Response(body=self.render(track).encode("utf-8"), headers=headers)

View file

@ -118,21 +118,20 @@ class SubaruConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_pin(self, user_input=None): async def async_step_pin(self, user_input=None):
"""Handle second part of config flow, if required.""" """Handle second part of config flow, if required."""
error = None error = None
if user_input: if user_input and self.controller.update_saved_pin(user_input[CONF_PIN]):
if self.controller.update_saved_pin(user_input[CONF_PIN]): try:
try: vol.Match(r"[0-9]{4}")(user_input[CONF_PIN])
vol.Match(r"[0-9]{4}")(user_input[CONF_PIN]) await self.controller.test_pin()
await self.controller.test_pin() except vol.Invalid:
except vol.Invalid: error = {"base": "bad_pin_format"}
error = {"base": "bad_pin_format"} except InvalidPIN:
except InvalidPIN: error = {"base": "incorrect_pin"}
error = {"base": "incorrect_pin"} else:
else: _LOGGER.debug("PIN successfully tested")
_LOGGER.debug("PIN successfully tested") self.config_data.update(user_input)
self.config_data.update(user_input) return self.async_create_entry(
return self.async_create_entry( title=self.config_data[CONF_USERNAME], data=self.config_data
title=self.config_data[CONF_USERNAME], data=self.config_data )
)
return self.async_show_form(step_id="pin", data_schema=PIN_SCHEMA, errors=error) return self.async_show_form(step_id="pin", data_schema=PIN_SCHEMA, errors=error)

View file

@ -220,16 +220,20 @@ class SubaruSensor(SubaruEntity, SensorEntity):
self.hass.config.units.length(self.current_value, self.api_unit), 1 self.hass.config.units.length(self.current_value, self.api_unit), 1
) )
if self.api_unit in PRESSURE_UNITS: if (
if self.hass.config.units == IMPERIAL_SYSTEM: self.api_unit in PRESSURE_UNITS
return round( and self.hass.config.units == IMPERIAL_SYSTEM
self.hass.config.units.pressure(self.current_value, self.api_unit), ):
1, return round(
) self.hass.config.units.pressure(self.current_value, self.api_unit),
1,
)
if self.api_unit in FUEL_CONSUMPTION_UNITS: if (
if self.hass.config.units == IMPERIAL_SYSTEM: self.api_unit in FUEL_CONSUMPTION_UNITS
return round((100.0 * L_PER_GAL) / (KM_PER_MI * self.current_value), 1) and self.hass.config.units == IMPERIAL_SYSTEM
):
return round((100.0 * L_PER_GAL) / (KM_PER_MI * self.current_value), 1)
return self.current_value return self.current_value

View file

@ -164,17 +164,18 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
# Initialize the sensor argument if none was provided. # Initialize the sensor argument if none was provided.
# For disk monitoring default to "/" (root) to prevent runtime errors, if argument was not specified. # For disk monitoring default to "/" (root) to prevent runtime errors, if argument was not specified.
if CONF_ARG not in resource: if CONF_ARG not in resource:
resource[CONF_ARG] = ""
if resource[CONF_TYPE].startswith("disk_"): if resource[CONF_TYPE].startswith("disk_"):
resource[CONF_ARG] = "/" resource[CONF_ARG] = "/"
else:
resource[CONF_ARG] = ""
# Verify if we can retrieve CPU / processor temperatures. # Verify if we can retrieve CPU / processor temperatures.
# If not, do not create the entity and add a warning to the log # If not, do not create the entity and add a warning to the log
if resource[CONF_TYPE] == "processor_temperature": if (
if SystemMonitorSensor.read_cpu_temperature() is None: resource[CONF_TYPE] == "processor_temperature"
_LOGGER.warning("Cannot read CPU / processor temperature information") and SystemMonitorSensor.read_cpu_temperature() is None
continue ):
_LOGGER.warning("Cannot read CPU / processor temperature information")
continue
dev.append(SystemMonitorSensor(resource[CONF_TYPE], resource[CONF_ARG])) dev.append(SystemMonitorSensor(resource[CONF_TYPE], resource[CONF_ARG]))
@ -272,23 +273,20 @@ class SystemMonitorSensor(SensorEntity):
err.name, err.name,
) )
self._state = STATE_OFF self._state = STATE_OFF
elif self.type == "network_out" or self.type == "network_in": elif self.type in ["network_out", "network_in"]:
counters = psutil.net_io_counters(pernic=True) counters = psutil.net_io_counters(pernic=True)
if self.argument in counters: if self.argument in counters:
counter = counters[self.argument][IO_COUNTER[self.type]] counter = counters[self.argument][IO_COUNTER[self.type]]
self._state = round(counter / 1024 ** 2, 1) self._state = round(counter / 1024 ** 2, 1)
else: else:
self._state = None self._state = None
elif self.type == "packets_out" or self.type == "packets_in": elif self.type in ["packets_out", "packets_in"]:
counters = psutil.net_io_counters(pernic=True) counters = psutil.net_io_counters(pernic=True)
if self.argument in counters: if self.argument in counters:
self._state = counters[self.argument][IO_COUNTER[self.type]] self._state = counters[self.argument][IO_COUNTER[self.type]]
else: else:
self._state = None self._state = None
elif ( elif self.type in ["throughput_network_out", "throughput_network_in"]:
self.type == "throughput_network_out"
or self.type == "throughput_network_in"
):
counters = psutil.net_io_counters(pernic=True) counters = psutil.net_io_counters(pernic=True)
if self.argument in counters: if self.argument in counters:
counter = counters[self.argument][IO_COUNTER[self.type]] counter = counters[self.argument][IO_COUNTER[self.type]]
@ -306,7 +304,7 @@ class SystemMonitorSensor(SensorEntity):
self._last_value = counter self._last_value = counter
else: else:
self._state = None self._state = None
elif self.type == "ipv4_address" or self.type == "ipv6_address": elif self.type in ["ipv4_address", "ipv6_address"]:
addresses = psutil.net_if_addrs() addresses = psutil.net_if_addrs()
if self.argument in addresses: if self.argument in addresses:
for addr in addresses[self.argument]: for addr in addresses[self.argument]:
@ -333,16 +331,9 @@ class SystemMonitorSensor(SensorEntity):
temps = psutil.sensors_temperatures() temps = psutil.sensors_temperatures()
for name, entries in temps.items(): for name, entries in temps.items():
i = 1 for i, entry in enumerate(entries, start=1):
for entry in entries:
# In case the label is empty (e.g. on Raspberry PI 4), # In case the label is empty (e.g. on Raspberry PI 4),
# construct it ourself here based on the sensor key name. # construct it ourself here based on the sensor key name.
if not entry.label: _label = f"{name} {i}" if not entry.label else entry.label
_label = f"{name} {i}"
else:
_label = entry.label
if _label in CPU_SENSOR_PREFIXES: if _label in CPU_SENSOR_PREFIXES:
return round(entry.current, 1) return round(entry.current, 1)
i += 1

View file

@ -131,11 +131,10 @@ class TadoDeviceScanner(DeviceScanner):
# Find devices that have geofencing enabled, and are currently at home. # Find devices that have geofencing enabled, and are currently at home.
for mobile_device in tado_json: for mobile_device in tado_json:
if mobile_device.get("location"): if mobile_device.get("location") and mobile_device["location"]["atHome"]:
if mobile_device["location"]["atHome"]: device_id = mobile_device["id"]
device_id = mobile_device["id"] device_name = mobile_device["name"]
device_name = mobile_device["name"] last_results.append(Device(device_id, device_name))
last_results.append(Device(device_id, device_name))
self.last_results = last_results self.last_results = last_results

View file

@ -320,12 +320,12 @@ class TPLinkSmartBulb(LightEntity):
light_state_params[LIGHT_STATE_BRIGHTNESS] light_state_params[LIGHT_STATE_BRIGHTNESS]
) )
if light_features.supported_features & SUPPORT_COLOR_TEMP: if (
if ( light_features.supported_features & SUPPORT_COLOR_TEMP
light_state_params.get(LIGHT_STATE_COLOR_TEMP) is not None and light_state_params.get(LIGHT_STATE_COLOR_TEMP) is not None
and light_state_params[LIGHT_STATE_COLOR_TEMP] != 0 and light_state_params[LIGHT_STATE_COLOR_TEMP] != 0
): ):
color_temp = kelvin_to_mired(light_state_params[LIGHT_STATE_COLOR_TEMP]) color_temp = kelvin_to_mired(light_state_params[LIGHT_STATE_COLOR_TEMP])
if light_features.supported_features & SUPPORT_COLOR: if light_features.supported_features & SUPPORT_COLOR:
hue_saturation = ( hue_saturation = (

View file

@ -205,10 +205,13 @@ class UniFiClientTracker(UniFiClient, ScannerEntity):
elif not self.heartbeat_check: elif not self.heartbeat_check:
self.schedule_update = True self.schedule_update = True
elif not self.client.event and self.client.last_updated == SOURCE_DATA: elif (
if self.is_wired == self.client.is_wired: not self.client.event
self._is_connected = True and self.client.last_updated == SOURCE_DATA
self.schedule_update = True and self.is_wired == self.client.is_wired
):
self._is_connected = True
self.schedule_update = True
if self.schedule_update: if self.schedule_update:
self.schedule_update = False self.schedule_update = False

View file

@ -279,10 +279,11 @@ class UniFiBlockClientSwitch(UniFiClient, SwitchEntity):
@callback @callback
def async_update_callback(self) -> None: def async_update_callback(self) -> None:
"""Update the clients state.""" """Update the clients state."""
if self.client.last_updated == SOURCE_EVENT: if (
self.client.last_updated == SOURCE_EVENT
if self.client.event.event in CLIENT_BLOCKED + CLIENT_UNBLOCKED: and self.client.event.event in CLIENT_BLOCKED + CLIENT_UNBLOCKED
self._is_blocked = self.client.event.event in CLIENT_BLOCKED ):
self._is_blocked = self.client.event.event in CLIENT_BLOCKED
super().async_update_callback() super().async_update_callback()

View file

@ -129,11 +129,9 @@ class UnifiVideoCamera(Camera):
if "recordingIndicator" in self._caminfo: if "recordingIndicator" in self._caminfo:
recording_state = self._caminfo["recordingIndicator"] recording_state = self._caminfo["recordingIndicator"]
return ( return self._caminfo["recordingSettings"][
self._caminfo["recordingSettings"]["fullTimeRecordEnabled"] "fullTimeRecordEnabled"
or recording_state == "MOTION_INPROGRESS" ] or recording_state in ["MOTION_INPROGRESS", "MOTION_FINISHED"]
or recording_state == "MOTION_FINISHED"
)
@property @property
def motion_detection_enabled(self): def motion_detection_enabled(self):
@ -198,9 +196,8 @@ class UnifiVideoCamera(Camera):
def camera_image(self): def camera_image(self):
"""Return the image of this camera.""" """Return the image of this camera."""
if not self._camera: if not self._camera and not self._login():
if not self._login(): return
return
def _get_image(retry=True): def _get_image(retry=True):
try: try:

View file

@ -80,9 +80,12 @@ class WiLightFan(WiLightDevice, FanEntity):
@property @property
def percentage(self) -> int | None: def percentage(self) -> int | None:
"""Return the current speed percentage.""" """Return the current speed percentage."""
if "direction" in self._status: if (
if self._status["direction"] == WL_DIRECTION_OFF: "direction" in self._status
return 0 and self._status["direction"] == WL_DIRECTION_OFF
):
return 0
wl_speed = self._status.get("speed") wl_speed = self._status.get("speed")
if wl_speed is None: if wl_speed is None:
return None return None
@ -96,9 +99,11 @@ class WiLightFan(WiLightDevice, FanEntity):
@property @property
def current_direction(self) -> str: def current_direction(self) -> str:
"""Return the current direction of the fan.""" """Return the current direction of the fan."""
if "direction" in self._status: if (
if self._status["direction"] != WL_DIRECTION_OFF: "direction" in self._status
self._direction = self._status["direction"] and self._status["direction"] != WL_DIRECTION_OFF
):
self._direction = self._status["direction"]
return self._direction return self._direction
async def async_turn_on( async def async_turn_on(
@ -119,9 +124,11 @@ class WiLightFan(WiLightDevice, FanEntity):
if percentage == 0: if percentage == 0:
await self._client.set_fan_direction(self._index, WL_DIRECTION_OFF) await self._client.set_fan_direction(self._index, WL_DIRECTION_OFF)
return return
if "direction" in self._status: if (
if self._status["direction"] == WL_DIRECTION_OFF: "direction" in self._status
await self._client.set_fan_direction(self._index, self._direction) and self._status["direction"] == WL_DIRECTION_OFF
):
await self._client.set_fan_direction(self._index, self._direction)
wl_speed = percentage_to_ordered_list_item(ORDERED_NAMED_FAN_SPEEDS, percentage) wl_speed = percentage_to_ordered_list_item(ORDERED_NAMED_FAN_SPEEDS, percentage)
await self._client.set_fan_speed(self._index, wl_speed) await self._client.set_fan_speed(self._index, wl_speed)

View file

@ -40,9 +40,11 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
for sensor in pywink.get_sensors(): for sensor in pywink.get_sensors():
_id = sensor.object_id() + sensor.name() _id = sensor.object_id() + sensor.name()
if _id not in hass.data[DOMAIN]["unique_ids"]: if (
if sensor.capability() in SENSOR_TYPES: _id not in hass.data[DOMAIN]["unique_ids"]
add_entities([WinkBinarySensorEntity(sensor, hass)]) and sensor.capability() in SENSOR_TYPES
):
add_entities([WinkBinarySensorEntity(sensor, hass)])
for key in pywink.get_keys(): for key in pywink.get_keys():
_id = key.object_id() + key.name() _id = key.object_id() + key.name()

View file

@ -19,9 +19,11 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
for sensor in pywink.get_sensors(): for sensor in pywink.get_sensors():
_id = sensor.object_id() + sensor.name() _id = sensor.object_id() + sensor.name()
if _id not in hass.data[DOMAIN]["unique_ids"]: if (
if sensor.capability() in SENSOR_TYPES: _id not in hass.data[DOMAIN]["unique_ids"]
add_entities([WinkSensorEntity(sensor, hass)]) and sensor.capability() in SENSOR_TYPES
):
add_entities([WinkSensorEntity(sensor, hass)])
for eggtray in pywink.get_eggtrays(): for eggtray in pywink.get_eggtrays():
_id = eggtray.object_id() + eggtray.name() _id = eggtray.object_id() + eggtray.name()

View file

@ -127,9 +127,8 @@ class WorxLandroidSensor(SensorEntity):
def get_error(obj): def get_error(obj):
"""Get the mower error.""" """Get the mower error."""
for i, err in enumerate(obj["allarmi"]): for i, err in enumerate(obj["allarmi"]):
if i != 2: # ignore wire bounce errors if i != 2 and err == 1: # ignore wire bounce errors
if err == 1: return ERROR_STATE[i]
return ERROR_STATE[i]
return None return None