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,7 +103,6 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
for sensor in hass_sensors:
state_unknown = False
if not values:
# 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
# basis like "today_yield", this reset won't happen automatically.
@ -111,8 +110,9 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
# and if so: set state to None.
# Sensors with live values like "temperature" or "current_power"
# will also be reset to None.
if (sensor.per_day_basis and date.today() > sensor.date_updated) or (
not sensor.per_day_basis and not sensor.per_total_basis
if not values and (
(sensor.per_day_basis and date.today() > sensor.date_updated)
or (not sensor.per_day_basis and not sensor.per_total_basis)
):
state_unknown = True
sensor.async_update_values(unknown_state=state_unknown)

View file

@ -53,8 +53,10 @@ class SmhiFlowHandler(config_entries.ConfigFlow):
# If hass config has the location set and is a valid coordinate the
# default location is set as default values in the form
if not smhi_locations(self.hass):
if await self._homeassistant_location_exists():
if (
not smhi_locations(self.hass)
and await self._homeassistant_location_exists()
):
return await self._show_config_form(
name=HOME_LOCATION_NAME,
latitude=self.hass.config.latitude,
@ -65,19 +67,18 @@ class SmhiFlowHandler(config_entries.ConfigFlow):
async def _homeassistant_location_exists(self) -> bool:
"""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
if await self._check_location(
return (
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
):
return True
return False
)
)
def _name_in_configuration_exists(self, name: str) -> bool:
"""Return True if name exists in configuration."""
if name in smhi_locations(self.hass):
return True
return False
return name in smhi_locations(self.hass)
async def _show_config_form(
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:
"""Return true if location is ok."""
try:
session = aiohttp_client.async_get_clientsession(self.hass)
smhi_api = Smhi(longitude, latitude, session=session)

View file

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

View file

@ -118,8 +118,7 @@ class SubaruConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_pin(self, user_input=None):
"""Handle second part of config flow, if required."""
error = None
if user_input:
if self.controller.update_saved_pin(user_input[CONF_PIN]):
if user_input and self.controller.update_saved_pin(user_input[CONF_PIN]):
try:
vol.Match(r"[0-9]{4}")(user_input[CONF_PIN])
await self.controller.test_pin()

View file

@ -220,15 +220,19 @@ class SubaruSensor(SubaruEntity, SensorEntity):
self.hass.config.units.length(self.current_value, self.api_unit), 1
)
if self.api_unit in PRESSURE_UNITS:
if self.hass.config.units == IMPERIAL_SYSTEM:
if (
self.api_unit in PRESSURE_UNITS
and self.hass.config.units == IMPERIAL_SYSTEM
):
return round(
self.hass.config.units.pressure(self.current_value, self.api_unit),
1,
)
if self.api_unit in FUEL_CONSUMPTION_UNITS:
if self.hass.config.units == IMPERIAL_SYSTEM:
if (
self.api_unit in FUEL_CONSUMPTION_UNITS
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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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