String formatting and max line length - Part 2 (#84393)

This commit is contained in:
Franck Nijhof 2022-12-22 11:38:59 +01:00 committed by GitHub
parent 7e682af472
commit cb13418bab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
69 changed files with 431 additions and 174 deletions

View File

@ -86,7 +86,10 @@ def request_app_setup(
if os.path.isfile(config_path): if os.path.isfile(config_path):
config_file = load_json(config_path) config_file = load_json(config_path)
if config_file == DEFAULT_CONFIG: if config_file == DEFAULT_CONFIG:
error_msg = f"You didn't correctly modify {FITBIT_CONFIG_FILE}, please try again." error_msg = (
f"You didn't correctly modify {FITBIT_CONFIG_FILE}, please try"
" again."
)
configurator.notify_errors(hass, _CONFIGURING["fitbit"], error_msg) configurator.notify_errors(hass, _CONFIGURING["fitbit"], error_msg)
else: else:

View File

@ -316,8 +316,10 @@ class FluxSwitch(SwitchEntity, RestoreEntity):
self.hass, self._lights, x_val, y_val, brightness, self._transition self.hass, self._lights, x_val, y_val, brightness, self._transition
) )
_LOGGER.debug( _LOGGER.debug(
(
"Lights updated to x:%s y:%s brightness:%s, %s%% " "Lights updated to x:%s y:%s brightness:%s, %s%% "
"of %s cycle complete at %s", "of %s cycle complete at %s"
),
x_val, x_val,
y_val, y_val,
brightness, brightness,
@ -341,8 +343,10 @@ class FluxSwitch(SwitchEntity, RestoreEntity):
self.hass, self._lights, mired, brightness, self._transition self.hass, self._lights, mired, brightness, self._transition
) )
_LOGGER.debug( _LOGGER.debug(
(
"Lights updated to mired:%s brightness:%s, %s%% " "Lights updated to mired:%s brightness:%s, %s%% "
"of %s cycle complete at %s", "of %s cycle complete at %s"
),
mired, mired,
brightness, brightness,
round(percentage_complete * 100), round(percentage_complete * 100),

View File

@ -177,7 +177,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if not mac_matches_by_one(mac, entry.unique_id): if not mac_matches_by_one(mac, entry.unique_id):
# The device is offline and another flux_led device is now using the ip address # The device is offline and another flux_led device is now using the ip address
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Unexpected device found at {host}; Expected {entry.unique_id}, found {mac}" f"Unexpected device found at {host}; Expected {entry.unique_id}, found"
f" {mac}"
) )
if not discovery_cached: if not discovery_cached:

View File

@ -117,7 +117,10 @@ class HassFoscamCamera(Camera):
if ret == -3: if ret == -3:
LOGGER.info( LOGGER.info(
"Can't get motion detection status, camera %s configured with non-admin user", (
"Can't get motion detection status, camera %s configured with"
" non-admin user"
),
self.name, self.name,
) )
@ -156,7 +159,10 @@ class HassFoscamCamera(Camera):
if ret != 0: if ret != 0:
if ret == -3: if ret == -3:
LOGGER.info( LOGGER.info(
"Can't set motion detection status, camera %s configured with non-admin user", (
"Can't set motion detection status, camera %s configured"
" with non-admin user"
),
self.name, self.name,
) )
return return
@ -164,7 +170,10 @@ class HassFoscamCamera(Camera):
self._attr_motion_detection_enabled = True self._attr_motion_detection_enabled = True
except TypeError: except TypeError:
LOGGER.debug( LOGGER.debug(
"Failed enabling motion detection on '%s'. Is it supported by the device?", (
"Failed enabling motion detection on '%s'. Is it supported by the"
" device?"
),
self.name, self.name,
) )
@ -176,7 +185,10 @@ class HassFoscamCamera(Camera):
if ret != 0: if ret != 0:
if ret == -3: if ret == -3:
LOGGER.info( LOGGER.info(
"Can't set motion detection status, camera %s configured with non-admin user", (
"Can't set motion detection status, camera %s configured"
" with non-admin user"
),
self.name, self.name,
) )
return return
@ -184,7 +196,10 @@ class HassFoscamCamera(Camera):
self._attr_motion_detection_enabled = False self._attr_motion_detection_enabled = False
except TypeError: except TypeError:
LOGGER.debug( LOGGER.debug(
"Failed disabling motion detection on '%s'. Is it supported by the device?", (
"Failed disabling motion detection on '%s'. Is it supported by the"
" device?"
),
self.name, self.name,
) )

View File

@ -57,7 +57,8 @@ class FreeboxSwitch(SwitchEntity):
await self._router.wifi.set_global_config({"enabled": enabled}) await self._router.wifi.set_global_config({"enabled": enabled})
except InsufficientPermissionsError: except InsufficientPermissionsError:
_LOGGER.warning( _LOGGER.warning(
"Home Assistant does not have permissions to modify the Freebox settings. Please refer to documentation" "Home Assistant does not have permissions to modify the Freebox"
" settings. Please refer to documentation"
) )
async def async_turn_on(self, **kwargs: Any) -> None: async def async_turn_on(self, **kwargs: Any) -> None:

View File

@ -328,7 +328,10 @@ class FritzBoxTools(update_coordinator.DataUpdateCoordinator):
).get("NewDisallow") ).get("NewDisallow")
except FRITZ_EXCEPTIONS as ex: except FRITZ_EXCEPTIONS as ex:
_LOGGER.debug( _LOGGER.debug(
"could not get WAN access rule for client device with IP '%s', error: %s", (
"could not get WAN access rule for client device with IP '%s',"
" error: %s"
),
ip_address, ip_address,
ex, ex,
) )
@ -574,21 +577,24 @@ class FritzBoxTools(update_coordinator.DataUpdateCoordinator):
try: try:
if service_call.service == SERVICE_REBOOT: if service_call.service == SERVICE_REBOOT:
_LOGGER.warning( _LOGGER.warning(
'Service "fritz.reboot" is deprecated, please use the corresponding button entity instead' 'Service "fritz.reboot" is deprecated, please use the corresponding'
" button entity instead"
) )
await self.async_trigger_reboot() await self.async_trigger_reboot()
return return
if service_call.service == SERVICE_RECONNECT: if service_call.service == SERVICE_RECONNECT:
_LOGGER.warning( _LOGGER.warning(
'Service "fritz.reconnect" is deprecated, please use the corresponding button entity instead' 'Service "fritz.reconnect" is deprecated, please use the'
" corresponding button entity instead"
) )
await self.async_trigger_reconnect() await self.async_trigger_reconnect()
return return
if service_call.service == SERVICE_CLEANUP: if service_call.service == SERVICE_CLEANUP:
_LOGGER.warning( _LOGGER.warning(
'Service "fritz.cleanup" is deprecated, please use the corresponding button entity instead' 'Service "fritz.cleanup" is deprecated, please use the'
" corresponding button entity instead"
) )
await self.async_trigger_cleanup(config_entry) await self.async_trigger_cleanup(config_entry)
return return
@ -634,7 +640,10 @@ class AvmWrapper(FritzBoxTools):
return result return result
except FritzSecurityError: except FritzSecurityError:
_LOGGER.error( _LOGGER.error(
"Authorization Error: Please check the provided credentials and verify that you can log into the web interface", (
"Authorization Error: Please check the provided credentials and"
" verify that you can log into the web interface"
),
exc_info=True, exc_info=True,
) )
except FRITZ_EXCEPTIONS: except FRITZ_EXCEPTIONS:
@ -646,7 +655,10 @@ class AvmWrapper(FritzBoxTools):
) )
except FritzConnectionException: except FritzConnectionException:
_LOGGER.error( _LOGGER.error(
"Connection Error: Please check the device is properly configured for remote login", (
"Connection Error: Please check the device is properly configured"
" for remote login"
),
exc_info=True, exc_info=True,
) )
return {} return {}

View File

@ -54,7 +54,8 @@ async def async_setup_services(hass: HomeAssistant) -> None:
) )
): ):
raise HomeAssistantError( raise HomeAssistantError(
f"Failed to call service '{service_call.service}'. Config entry for target not found" f"Failed to call service '{service_call.service}'. Config entry for"
" target not found"
) )
for entry_id in fritzbox_entry_ids: for entry_id in fritzbox_entry_ids:

View File

@ -149,7 +149,8 @@ class FritzboxLight(FritzBoxDeviceEntity, LightEntity):
if err.response.status_code != 400: if err.response.status_code != 400:
raise raise
LOGGER.debug( LOGGER.debug(
"fritzbox does not support method 'setunmappedcolor', fallback to 'setcolor'" "fritzbox does not support method 'setunmappedcolor', fallback to"
" 'setcolor'"
) )
# find supported hs values closest to what user selected # find supported hs values closest to what user selected
hue = min( hue = min(

View File

@ -36,7 +36,10 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
await hass.async_add_executor_job(fritzbox_phonebook.init_phonebook) await hass.async_add_executor_job(fritzbox_phonebook.init_phonebook)
except FritzSecurityError as ex: except FritzSecurityError as ex:
_LOGGER.error( _LOGGER.error(
"User has insufficient permissions to access AVM FRITZ!Box settings and its phonebooks: %s", (
"User has insufficient permissions to access AVM FRITZ!Box settings and"
" its phonebooks: %s"
),
ex, ex,
) )
return False return False

View File

@ -146,7 +146,9 @@ class Manifest:
MANIFEST_JSON = Manifest( MANIFEST_JSON = Manifest(
{ {
"background_color": "#FFFFFF", "background_color": "#FFFFFF",
"description": "Home automation platform that puts local control and privacy first.", "description": (
"Home automation platform that puts local control and privacy first."
),
"dir": "ltr", "dir": "ltr",
"display": "standalone", "display": "standalone",
"icons": [ "icons": [

View File

@ -87,7 +87,9 @@ async def browse_top_level(current_mode, afsapi: AFSAPI):
title=name, title=name,
media_class=MediaClass.DIRECTORY, media_class=MediaClass.DIRECTORY,
media_content_type=MediaType.CHANNELS, media_content_type=MediaType.CHANNELS,
media_content_id=f"{current_mode or 'unknown'}/{top_level_media_content_id}", media_content_id=(
f"{current_mode or 'unknown'}/{top_level_media_content_id}"
),
can_play=False, can_play=False,
can_expand=True, can_expand=True,
) )

View File

@ -358,8 +358,10 @@ class GenericHygrostat(HumidifierEntity, RestoreEntity):
self._active = True self._active = True
force = True force = True
_LOGGER.info( _LOGGER.info(
(
"Obtained current and target humidity. " "Obtained current and target humidity. "
"Generic hygrostat active. %s, %s", "Generic hygrostat active. %s, %s"
),
self._cur_humidity, self._cur_humidity,
self._target_humidity, self._target_humidity,
) )

View File

@ -409,7 +409,10 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
"""Prevent the device from keep running if HVACMode.OFF.""" """Prevent the device from keep running if HVACMode.OFF."""
if self._hvac_mode == HVACMode.OFF and self._is_device_active: if self._hvac_mode == HVACMode.OFF and self._is_device_active:
_LOGGER.warning( _LOGGER.warning(
"The climate mode is OFF, but the switch device is ON. Turning off device %s", (
"The climate mode is OFF, but the switch device is ON. Turning off"
" device %s"
),
self.heater_entity_id, self.heater_entity_id,
) )
await self._async_heater_turn_off() await self._async_heater_turn_off()
@ -445,8 +448,10 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
): ):
self._active = True self._active = True
_LOGGER.info( _LOGGER.info(
(
"Obtained current and target temperature. " "Obtained current and target temperature. "
"Generic thermostat active. %s, %s", "Generic thermostat active. %s, %s"
),
self._cur_temp, self._cur_temp,
self._target_temp, self._target_temp,
) )
@ -526,7 +531,8 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
"""Set new preset mode.""" """Set new preset mode."""
if preset_mode not in (self.preset_modes or []): if preset_mode not in (self.preset_modes or []):
raise ValueError( raise ValueError(
f"Got unsupported preset_mode {preset_mode}. Must be one of {self.preset_modes}" f"Got unsupported preset_mode {preset_mode}. Must be one of"
f" {self.preset_modes}"
) )
if preset_mode == self._attr_preset_mode: if preset_mode == self._attr_preset_mode:
# I don't think we need to call async_write_ha_state if we didn't change the state # I don't think we need to call async_write_ha_state if we didn't change the state

View File

@ -66,7 +66,10 @@ def async_cleanup_device_registry(
for item in device.identifiers: for item in device.identifiers:
if DOMAIN == item[0] and item[1] not in entry.options[CONF_REPOSITORIES]: if DOMAIN == item[0] and item[1] not in entry.options[CONF_REPOSITORIES]:
LOGGER.debug( LOGGER.debug(
"Unlinking device %s for untracked repository %s from config entry %s", (
"Unlinking device %s for untracked repository %s from config"
" entry %s"
),
device.id, device.id,
item[1], item[1],
entry.entry_id, entry.entry_id,

View File

@ -26,7 +26,9 @@ async def async_get_auth_implementation(
async def async_get_description_placeholders(hass: HomeAssistant) -> dict[str, str]: async def async_get_description_placeholders(hass: HomeAssistant) -> dict[str, str]:
"""Return description placeholders for the credentials dialog.""" """Return description placeholders for the credentials dialog."""
return { return {
"oauth_consent_url": "https://console.cloud.google.com/apis/credentials/consent", "oauth_consent_url": (
"https://console.cloud.google.com/apis/credentials/consent"
),
"more_info_url": "https://www.home-assistant.io/integrations/google/", "more_info_url": "https://www.home-assistant.io/integrations/google/",
"oauth_creds_url": "https://console.cloud.google.com/apis/credentials", "oauth_creds_url": "https://console.cloud.google.com/apis/credentials",
} }

View File

@ -173,8 +173,9 @@ async def async_setup_entry(
entity_enabled = data.get(CONF_TRACK, True) entity_enabled = data.get(CONF_TRACK, True)
if not entity_enabled: if not entity_enabled:
_LOGGER.warning( _LOGGER.warning(
"The 'track' option in google_calendars.yaml has been deprecated. The setting " "The 'track' option in google_calendars.yaml has been deprecated."
"has been imported to the UI, and should now be removed from google_calendars.yaml" " The setting has been imported to the UI, and should now be"
" removed from google_calendars.yaml"
) )
entity_name = data[CONF_DEVICE_ID] entity_name = data[CONF_DEVICE_ID]
# The unique id is based on the config entry and calendar id since multiple accounts # The unique id is based on the config entry and calendar id since multiple accounts

View File

@ -153,7 +153,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if agent_user_id is None: if agent_user_id is None:
_LOGGER.warning( _LOGGER.warning(
"No agent_user_id supplied for request_sync. Call as a user or pass in user id as agent_user_id" "No agent_user_id supplied for request_sync. Call as a user or pass in"
" user id as agent_user_id"
) )
return return

View File

@ -49,5 +49,6 @@ class SyncButton(ButtonEntity):
result = await self._google_config.async_sync_entities(agent_user_id) result = await self._google_config.async_sync_entities(agent_user_id)
if result != 200: if result != 200:
raise HomeAssistantError( raise HomeAssistantError(
f"Unable to sync devices with result code: {result}, check log for more info." f"Unable to sync devices with result code: {result}, check log for more"
" info."
) )

View File

@ -349,7 +349,10 @@ class AbstractConfig(ABC):
not version or AwesomeVersion(version) < LOCAL_SDK_MIN_VERSION not version or AwesomeVersion(version) < LOCAL_SDK_MIN_VERSION
): ):
_LOGGER.warning( _LOGGER.warning(
"Local SDK version is too old (%s), check documentation on how to update to the latest version", (
"Local SDK version is too old (%s), check documentation on how to"
" update to the latest version"
),
version, version,
) )
self._local_sdk_version_warn = True self._local_sdk_version_warn = True
@ -368,7 +371,10 @@ class AbstractConfig(ABC):
# No agent user linked to this webhook, means that the user has somehow unregistered # No agent user linked to this webhook, means that the user has somehow unregistered
# removing webhook and stopping processing of this request. # removing webhook and stopping processing of this request.
_LOGGER.error( _LOGGER.error(
"Cannot process request for webhook %s as no linked agent user is found:\n%s\n", (
"Cannot process request for webhook %s as no linked agent user is"
" found:\n%s\n"
),
webhook_id, webhook_id,
pprint.pformat(payload), pprint.pformat(payload),
) )

View File

@ -1043,7 +1043,7 @@ class TemperatureSettingTrait(_Trait):
raise SmartHomeError( raise SmartHomeError(
ERR_VALUE_OUT_OF_RANGE, ERR_VALUE_OUT_OF_RANGE,
( (
f"Upper bound for temperature range should be between " "Upper bound for temperature range should be between "
f"{min_temp} and {max_temp}" f"{min_temp} and {max_temp}"
), ),
) )
@ -1060,7 +1060,7 @@ class TemperatureSettingTrait(_Trait):
raise SmartHomeError( raise SmartHomeError(
ERR_VALUE_OUT_OF_RANGE, ERR_VALUE_OUT_OF_RANGE,
( (
f"Lower bound for temperature range should be between " "Lower bound for temperature range should be between "
f"{min_temp} and {max_temp}" f"{min_temp} and {max_temp}"
), ),
) )

View File

@ -16,7 +16,11 @@ async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationSe
async def async_get_description_placeholders(hass: HomeAssistant) -> dict[str, str]: async def async_get_description_placeholders(hass: HomeAssistant) -> dict[str, str]:
"""Return description placeholders for the credentials dialog.""" """Return description placeholders for the credentials dialog."""
return { return {
"oauth_consent_url": "https://console.cloud.google.com/apis/credentials/consent", "oauth_consent_url": (
"more_info_url": "https://www.home-assistant.io/integrations/google_assistant_sdk/", "https://console.cloud.google.com/apis/credentials/consent"
),
"more_info_url": (
"https://www.home-assistant.io/integrations/google_assistant_sdk/"
),
"oauth_creds_url": "https://console.cloud.google.com/apis/credentials", "oauth_creds_url": "https://console.cloud.google.com/apis/credentials",
} }

View File

@ -80,7 +80,8 @@ class GoogleMapsScanner:
except InvalidCookies: except InvalidCookies:
_LOGGER.error( _LOGGER.error(
"The cookie file provided does not provide a valid session. Please create another one and try again" "The cookie file provided does not provide a valid session. Please"
" create another one and try again"
) )
self.success_init = False self.success_init = False
@ -97,8 +98,10 @@ class GoogleMapsScanner:
and person.accuracy > self.max_gps_accuracy and person.accuracy > self.max_gps_accuracy
): ):
_LOGGER.info( _LOGGER.info(
(
"Ignoring %s update because expected GPS " "Ignoring %s update because expected GPS "
"accuracy %s is not met: %s", "accuracy %s is not met: %s"
),
person.nickname, person.nickname,
self.max_gps_accuracy, self.max_gps_accuracy,
person.accuracy, person.accuracy,
@ -108,8 +111,7 @@ class GoogleMapsScanner:
last_seen = dt_util.as_utc(person.datetime) last_seen = dt_util.as_utc(person.datetime)
if last_seen < self._prev_seen.get(dev_id, last_seen): if last_seen < self._prev_seen.get(dev_id, last_seen):
_LOGGER.warning( _LOGGER.warning(
"Ignoring %s update because timestamp " "Ignoring %s update because timestamp is older than last timestamp",
"is older than last timestamp",
person.nickname, person.nickname,
) )
_LOGGER.debug("%s < %s", last_seen, self._prev_seen[dev_id]) _LOGGER.debug("%s < %s", last_seen, self._prev_seen[dev_id])

View File

@ -16,7 +16,9 @@ async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationSe
async def async_get_description_placeholders(hass: HomeAssistant) -> dict[str, str]: async def async_get_description_placeholders(hass: HomeAssistant) -> dict[str, str]:
"""Return description placeholders for the credentials dialog.""" """Return description placeholders for the credentials dialog."""
return { return {
"oauth_consent_url": "https://console.cloud.google.com/apis/credentials/consent", "oauth_consent_url": (
"https://console.cloud.google.com/apis/credentials/consent"
),
"more_info_url": "https://www.home-assistant.io/integrations/google_sheets/", "more_info_url": "https://www.home-assistant.io/integrations/google_sheets/",
"oauth_creds_url": "https://console.cloud.google.com/apis/credentials", "oauth_creds_url": "https://console.cloud.google.com/apis/credentials",
} }

View File

@ -228,8 +228,10 @@ class GoogleWifiAPI:
self.data[attr_key] = sensor_value self.data[attr_key] = sensor_value
except KeyError: except KeyError:
_LOGGER.error( _LOGGER.error(
(
"Router does not support %s field. " "Router does not support %s field. "
"Please remove %s from monitored_conditions", "Please remove %s from monitored_conditions"
),
description.sensor_key, description.sensor_key,
attr_key, attr_key,
) )

View File

@ -89,8 +89,10 @@ MONITOR_SCHEMA = vol.Schema(
vol.Length( vol.Length(
min=8, min=8,
max=8, max=8,
msg="GEM serial number must be specified as an 8-character " msg=(
"string (including leading zeroes).", "GEM serial number must be specified as an 8-character "
"string (including leading zeroes)."
),
), ),
vol.Coerce(int), vol.Coerce(int),
), ),

View File

@ -240,7 +240,8 @@ class PulseCounter(GEMSensor):
# Config schema should have ensured it is one of the above values # Config schema should have ensured it is one of the above values
raise Exception( raise Exception(
f"Invalid value for time unit: {self._time_unit}. Expected one of {UnitOfTime.SECONDS}, {UnitOfTime.MINUTES}, or {UnitOfTime.HOURS}" f"Invalid value for time unit: {self._time_unit}. Expected one of"
f" {UnitOfTime.SECONDS}, {UnitOfTime.MINUTES}, or {UnitOfTime.HOURS}"
) )
@property @property

View File

@ -84,7 +84,9 @@ async def async_setup_entry(
# also extend the library's default identifier to include 'home-assistant' # also extend the library's default identifier to include 'home-assistant'
api = growattServer.GrowattApi( api = growattServer.GrowattApi(
add_random_user_id=True, add_random_user_id=True,
agent_identifier=f"{growattServer.GrowattApi.agent_identifier} - home-assistant", agent_identifier=(
f"{growattServer.GrowattApi.agent_identifier} - home-assistant"
),
) )
api.server_url = url api.server_url = url
@ -290,7 +292,10 @@ class GrowattData:
and api_value is not None and api_value is not None
): ):
_LOGGER.debug( _LOGGER.debug(
"%s - Drop threshold specified (%s), checking for drop... API Value: %s, Previous Value: %s", (
"%s - Drop threshold specified (%s), checking for drop... API"
" Value: %s, Previous Value: %s"
),
entity_description.name, entity_description.name,
entity_description.previous_value_drop_threshold, entity_description.previous_value_drop_threshold,
api_value, api_value,
@ -304,8 +309,11 @@ class GrowattData:
# however if the value is low e.g. 0.2 and drops by 0.1 it classes as a reset. # however if the value is low e.g. 0.2 and drops by 0.1 it classes as a reset.
if -(entity_description.previous_value_drop_threshold) <= diff < 0: if -(entity_description.previous_value_drop_threshold) <= diff < 0:
_LOGGER.debug( _LOGGER.debug(
"Diff is negative, but only by a small amount therefore not a nightly reset, " (
"using previous value (%s) instead of api value (%s)", "Diff is negative, but only by a small amount therefore not a"
" nightly reset, using previous value (%s) instead of api value"
" (%s)"
),
previous_value, previous_value,
api_value, api_value,
) )
@ -329,7 +337,10 @@ class GrowattData:
# value of the entity from the recorder # value of the entity from the recorder
if entity_description.never_resets and api_value == 0 and previous_value: if entity_description.never_resets and api_value == 0 and previous_value:
_LOGGER.debug( _LOGGER.debug(
"API value is 0, but this value should never reset, returning previous value (%s) instead", (
"API value is 0, but this value should never reset, returning"
" previous value (%s) instead"
),
previous_value, previous_value,
) )
return_value = previous_value return_value = previous_value

View File

@ -427,16 +427,14 @@ def get_next_departure(
if item["dest_arrival_time"] < item["origin_depart_time"]: if item["dest_arrival_time"] < item["origin_depart_time"]:
dest_arrival += datetime.timedelta(days=1) dest_arrival += datetime.timedelta(days=1)
dest_arrival_time = ( dest_arrival_time = (
f"{dest_arrival.strftime(dt_util.DATE_STR_FORMAT)} " f"{dest_arrival.strftime(dt_util.DATE_STR_FORMAT)} {item['dest_arrival_time']}"
f"{item['dest_arrival_time']}"
) )
dest_depart = dest_arrival dest_depart = dest_arrival
if item["dest_depart_time"] < item["dest_arrival_time"]: if item["dest_depart_time"] < item["dest_arrival_time"]:
dest_depart += datetime.timedelta(days=1) dest_depart += datetime.timedelta(days=1)
dest_depart_time = ( dest_depart_time = (
f"{dest_depart.strftime(dt_util.DATE_STR_FORMAT)} " f"{dest_depart.strftime(dt_util.DATE_STR_FORMAT)} {item['dest_depart_time']}"
f"{item['dest_depart_time']}"
) )
depart_time = dt_util.parse_datetime(origin_depart_time) depart_time = dt_util.parse_datetime(origin_depart_time)
@ -638,9 +636,11 @@ class GTFSDepartureSensor(SensorEntity):
self._agency = self._pygtfs.agencies_by_id(self._route.agency_id)[0] self._agency = self._pygtfs.agencies_by_id(self._route.agency_id)[0]
except IndexError: except IndexError:
_LOGGER.warning( _LOGGER.warning(
(
"Agency ID '%s' was not found in agency table, " "Agency ID '%s' was not found in agency table, "
"you may want to update the routes database table " "you may want to update the routes database table "
"to fix this missing reference", "to fix this missing reference"
),
self._route.agency_id, self._route.agency_id,
) )
self._agency = False self._agency = False

View File

@ -114,8 +114,10 @@ class HabitipyData:
except ClientResponseError as error: except ClientResponseError as error:
if error.status == HTTPStatus.TOO_MANY_REQUESTS: if error.status == HTTPStatus.TOO_MANY_REQUESTS:
_LOGGER.warning( _LOGGER.warning(
(
"Sensor data update for %s has too many API requests;" "Sensor data update for %s has too many API requests;"
" Skipping the update", " Skipping the update"
),
DOMAIN, DOMAIN,
) )
else: else:
@ -131,8 +133,10 @@ class HabitipyData:
except ClientResponseError as error: except ClientResponseError as error:
if error.status == HTTPStatus.TOO_MANY_REQUESTS: if error.status == HTTPStatus.TOO_MANY_REQUESTS:
_LOGGER.warning( _LOGGER.warning(
(
"Sensor data update for %s has too many API requests;" "Sensor data update for %s has too many API requests;"
" Skipping the update", " Skipping the update"
),
DOMAIN, DOMAIN,
) )
else: else:

View File

@ -126,7 +126,8 @@ class HarmonyData(HarmonySubscriberMixin):
except (ValueError, AttributeError) as err: except (ValueError, AttributeError) as err:
await self._client.close() await self._client.close()
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"{self._name}: Error {err} while connected HUB at: {self._address}:8088" f"{self._name}: Error {err} while connected HUB at:"
f" {self._address}:8088"
) from err ) from err
if not connected: if not connected:
await self._client.close() await self._client.close()
@ -219,8 +220,10 @@ class HarmonyData(HarmonySubscriberMixin):
return return
_LOGGER.debug( _LOGGER.debug(
(
"Sending commands to device %s holding for %s seconds " "Sending commands to device %s holding for %s seconds "
"with a delay of %s seconds", "with a delay of %s seconds"
),
device, device,
hold_secs, hold_secs,
delay_secs, delay_secs,

View File

@ -414,7 +414,8 @@ class HassIO:
if http_config.get(CONF_SERVER_HOST) is not None: if http_config.get(CONF_SERVER_HOST) is not None:
options["watchdog"] = False options["watchdog"] = False
_LOGGER.warning( _LOGGER.warning(
"Found incompatible HTTP option 'server_host'. Watchdog feature disabled" "Found incompatible HTTP option 'server_host'. Watchdog feature"
" disabled"
) )
return await self.send_command("/homeassistant/options", payload=options) return await self.send_command("/homeassistant/options", payload=options)
@ -455,7 +456,9 @@ class HassIO:
f"http://{self._ip}{command}", f"http://{self._ip}{command}",
json=payload, json=payload,
headers={ headers={
aiohttp.hdrs.AUTHORIZATION: f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}" aiohttp.hdrs.AUTHORIZATION: (
f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}"
)
}, },
timeout=aiohttp.ClientTimeout(total=timeout), timeout=aiohttp.ClientTimeout(total=timeout),
) )

View File

@ -108,8 +108,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
favorites = await controller.get_favorites() favorites = await controller.get_favorites()
else: else:
_LOGGER.warning( _LOGGER.warning(
"%s is not logged in to a HEOS account and will be unable to retrieve " (
"HEOS favorites: Use the 'heos.sign_in' service to sign-in to a HEOS account", "%s is not logged in to a HEOS account and will be unable to"
" retrieve HEOS favorites: Use the 'heos.sign_in' service to"
" sign-in to a HEOS account"
),
host, host,
) )
inputs = await controller.get_input_sources() inputs = await controller.get_input_sources()
@ -289,7 +292,8 @@ class GroupManager:
leader_id = entity_id_to_player_id_map.get(leader_entity_id) leader_id = entity_id_to_player_id_map.get(leader_entity_id)
if not leader_id: if not leader_id:
raise HomeAssistantError( raise HomeAssistantError(
f"The group leader {leader_entity_id} could not be resolved to a HEOS player." f"The group leader {leader_entity_id} could not be resolved to a HEOS"
" player."
) )
member_ids = [ member_ids = [
entity_id_to_player_id_map[member] entity_id_to_player_id_map[member]

View File

@ -72,7 +72,10 @@ class HERERoutingDataUpdateCoordinator(DataUpdateCoordinator):
) )
_LOGGER.debug( _LOGGER.debug(
"Requesting route for origin: %s, destination: %s, route_mode: %s, mode: %s, arrival: %s, departure: %s", (
"Requesting route for origin: %s, destination: %s, route_mode: %s,"
" mode: %s, arrival: %s, departure: %s"
),
origin, origin,
destination, destination,
route_mode, route_mode,
@ -167,7 +170,10 @@ class HERETransitDataUpdateCoordinator(DataUpdateCoordinator):
) )
_LOGGER.debug( _LOGGER.debug(
"Requesting transit route for origin: %s, destination: %s, arrival: %s, departure: %s", (
"Requesting transit route for origin: %s, destination: %s, arrival: %s,"
" departure: %s"
),
origin, origin,
destination, destination,
arrival, arrival,

View File

@ -140,7 +140,8 @@ class HiveClimateEntity(HiveEntity, ClimateEntity):
async def async_heating_boost(self, time_period, temperature): async def async_heating_boost(self, time_period, temperature):
"""Handle boost heating service call.""" """Handle boost heating service call."""
_LOGGER.warning( _LOGGER.warning(
"Hive Service heating_boost will be removed in 2021.7.0, please update to heating_boost_on" "Hive Service heating_boost will be removed in 2021.7.0, please update to"
" heating_boost_on"
) )
await self.async_heating_boost_on(time_period, temperature) await self.async_heating_boost_on(time_period, temperature)

View File

@ -41,7 +41,10 @@ def validate_above_below(value):
if above > below: if above > below:
raise vol.Invalid( raise vol.Invalid(
f"A value can never be above {above} and below {below} at the same time. You probably want two different triggers.", (
f"A value can never be above {above} and below {below} at the same"
" time. You probably want two different triggers."
),
) )
return value return value

View File

@ -26,7 +26,9 @@ import homeassistant.util.dt as dt_util
_TIME_TRIGGER_SCHEMA = vol.Any( _TIME_TRIGGER_SCHEMA = vol.Any(
cv.time, cv.time,
vol.All(str, cv.entity_domain(["input_datetime", "sensor"])), vol.All(str, cv.entity_domain(["input_datetime", "sensor"])),
msg="Expected HH:MM, HH:MM:SS or Entity ID with domain 'input_datetime' or 'sensor'", msg=(
"Expected HH:MM, HH:MM:SS or Entity ID with domain 'input_datetime' or 'sensor'"
),
) )
TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend(

View File

@ -653,10 +653,12 @@ class HomeKit:
if self._exclude_accessory_mode: if self._exclude_accessory_mode:
return None return None
_LOGGER.warning( _LOGGER.warning(
(
"The bridge %s has entity %s. For best performance, " "The bridge %s has entity %s. For best performance, "
"and to prevent unexpected unavailability, create and " "and to prevent unexpected unavailability, create and "
"pair a separate HomeKit instance in accessory mode for " "pair a separate HomeKit instance in accessory mode for "
"this entity", "this entity"
),
self._name, self._name,
state.entity_id, state.entity_id,
) )
@ -685,7 +687,10 @@ class HomeKit:
assert self.bridge is not None assert self.bridge is not None
if len(self.bridge.accessories) + 1 >= MAX_DEVICES: if len(self.bridge.accessories) + 1 >= MAX_DEVICES:
_LOGGER.warning( _LOGGER.warning(
"Cannot add %s as this would exceed the %d device limit. Consider using the filter option", (
"Cannot add %s as this would exceed the %d device limit. Consider"
" using the filter option"
),
name, name,
MAX_DEVICES, MAX_DEVICES,
) )
@ -920,7 +925,10 @@ class HomeKit:
for device_id in self._devices: for device_id in self._devices:
if not dev_reg.async_get(device_id): if not dev_reg.async_get(device_id):
_LOGGER.warning( _LOGGER.warning(
"HomeKit %s cannot add device %s because it is missing from the device registry", (
"HomeKit %s cannot add device %s because it is missing from the"
" device registry"
),
self._name, self._name,
device_id, device_id,
) )
@ -941,7 +949,10 @@ class HomeKit:
await async_validate_trigger_config(self.hass, trigger) await async_validate_trigger_config(self.hass, trigger)
except vol.Invalid as ex: except vol.Invalid as ex:
_LOGGER.debug( _LOGGER.debug(
"%s: cannot add unsupported trigger %s because it requires additional inputs which are not supported by HomeKit: %s", (
"%s: cannot add unsupported trigger %s because it requires"
" additional inputs which are not supported by HomeKit: %s"
),
self._name, self._name,
trigger, trigger,
ex, ex,

View File

@ -114,8 +114,10 @@ def get_accessory( # noqa: C901
"""Take state and return an accessory object if supported.""" """Take state and return an accessory object if supported."""
if not aid: if not aid:
_LOGGER.warning( _LOGGER.warning(
(
'The entity "%s" is not supported, since it ' 'The entity "%s" is not supported, since it '
"generates an invalid aid, please change it", "generates an invalid aid, please change it"
),
state.entity_id, state.entity_id,
) )
return None return None
@ -666,6 +668,7 @@ class HomeIIDManager(IIDManager): # type: ignore[misc]
) )
if iid in self.objs: if iid in self.objs:
raise RuntimeError( raise RuntimeError(
f"Cannot assign IID {iid} to {obj} as it is already in use by: {self.objs[iid]}" f"Cannot assign IID {iid} to {obj} as it is already in use by:"
f" {self.objs[iid]}"
) )
return iid return iid

View File

@ -667,7 +667,9 @@ def _async_get_matching_entities(
"""Fetch all entities or entities in the given domains.""" """Fetch all entities or entities in the given domains."""
ent_reg = entity_registry.async_get(hass) ent_reg = entity_registry.async_get(hass)
return { return {
state.entity_id: f"{state.attributes.get(ATTR_FRIENDLY_NAME, state.entity_id)} ({state.entity_id})" state.entity_id: (
f"{state.attributes.get(ATTR_FRIENDLY_NAME, state.entity_id)} ({state.entity_id})"
)
for state in sorted( for state in sorted(
hass.states.async_all(domains and set(domains)), hass.states.async_all(domains and set(domains)),
key=lambda item: item.entity_id, key=lambda item: item.entity_id,

View File

@ -28,7 +28,10 @@ def async_describe_events(
value = data.get(ATTR_VALUE) value = data.get(ATTR_VALUE)
value_msg = f" to {value}" if value else "" value_msg = f" to {value}" if value else ""
message = f"send command {data[ATTR_SERVICE]}{value_msg} for {data[ATTR_DISPLAY_NAME]}" message = (
f"send command {data[ATTR_SERVICE]}{value_msg} for"
f" {data[ATTR_DISPLAY_NAME]}"
)
return { return {
LOGBOOK_ENTRY_NAME: "HomeKit", LOGBOOK_ENTRY_NAME: "HomeKit",

View File

@ -325,7 +325,8 @@ class Camera(HomeAccessory, PyhapCamera):
) )
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception( _LOGGER.exception(
"Failed to get stream source - this could be a transient error or your camera might not be compatible with HomeKit yet" "Failed to get stream source - this could be a transient error or your"
" camera might not be compatible with HomeKit yet"
) )
return stream_source return stream_source

View File

@ -283,7 +283,10 @@ class OpeningDevice(OpeningDeviceBase, HomeAccessory):
# since CHAR_CURRENT_POSITION/CHAR_TARGET_POSITION are required # since CHAR_CURRENT_POSITION/CHAR_TARGET_POSITION are required
# by homekit, but really don't exist. # by homekit, but really don't exist.
_LOGGER.debug( _LOGGER.debug(
"%s does not support setting position, current position will be locked to closed", (
"%s does not support setting position, current position will be"
" locked to closed"
),
self.entity_id, self.entity_id,
) )
target_args["properties"] = {PROP_MIN_VALUE: 0, PROP_MAX_VALUE: 0} target_args["properties"] = {PROP_MIN_VALUE: 0, PROP_MAX_VALUE: 0}

View File

@ -174,7 +174,10 @@ class HumidifierDehumidifier(HomeAccessory):
"""Handle linked humidity sensor state change to update HomeKit value.""" """Handle linked humidity sensor state change to update HomeKit value."""
if new_state is None: if new_state is None:
_LOGGER.error( _LOGGER.error(
"%s: Unable to update from linked humidity sensor %s: the entity state is None", (
"%s: Unable to update from linked humidity sensor %s: the entity"
" state is None"
),
self.entity_id, self.entity_id,
self.linked_humidity_sensor, self.linked_humidity_sensor,
) )
@ -221,8 +224,10 @@ class HumidifierDehumidifier(HomeAccessory):
DOMAIN, DOMAIN,
SERVICE_SET_HUMIDITY, SERVICE_SET_HUMIDITY,
{ATTR_ENTITY_ID: self.entity_id, ATTR_HUMIDITY: humidity}, {ATTR_ENTITY_ID: self.entity_id, ATTR_HUMIDITY: humidity},
(
f"{self._target_humidity_char_name} to " f"{self._target_humidity_char_name} to "
f"{char_values[self._target_humidity_char_name]}{PERCENTAGE}", f"{char_values[self._target_humidity_char_name]}{PERCENTAGE}"
),
) )
@callback @callback

View File

@ -419,7 +419,10 @@ class Thermostat(HomeAccessory):
for hc_fallback in hc_fallback_order: for hc_fallback in hc_fallback_order:
if hc_fallback in self.hc_homekit_to_hass: if hc_fallback in self.hc_homekit_to_hass:
_LOGGER.debug( _LOGGER.debug(
"Siri requested target mode: %s and the device does not support, falling back to %s", (
"Siri requested target mode: %s and the device does not"
" support, falling back to %s"
),
target_hc, target_hc,
hc_fallback, hc_fallback,
) )
@ -428,7 +431,8 @@ class Thermostat(HomeAccessory):
params[ATTR_HVAC_MODE] = self.hc_homekit_to_hass[target_hc] params[ATTR_HVAC_MODE] = self.hc_homekit_to_hass[target_hc]
events.append( events.append(
f"{CHAR_TARGET_HEATING_COOLING} to {char_values[CHAR_TARGET_HEATING_COOLING]}" f"{CHAR_TARGET_HEATING_COOLING} to"
f" {char_values[CHAR_TARGET_HEATING_COOLING]}"
) )
# Many integrations do not actually implement `hvac_mode` for the # Many integrations do not actually implement `hvac_mode` for the
# `SERVICE_SET_TEMPERATURE_THERMOSTAT` service so we made a call to # `SERVICE_SET_TEMPERATURE_THERMOSTAT` service so we made a call to
@ -447,7 +451,8 @@ class Thermostat(HomeAccessory):
service = SERVICE_SET_TEMPERATURE_THERMOSTAT service = SERVICE_SET_TEMPERATURE_THERMOSTAT
temperature = self._temperature_to_states(hc_target_temp) temperature = self._temperature_to_states(hc_target_temp)
events.append( events.append(
f"{CHAR_TARGET_TEMPERATURE} to {char_values[CHAR_TARGET_TEMPERATURE]}°C" f"{CHAR_TARGET_TEMPERATURE} to"
f" {char_values[CHAR_TARGET_TEMPERATURE]}°C"
) )
params[ATTR_TEMPERATURE] = temperature params[ATTR_TEMPERATURE] = temperature
elif features & ClimateEntityFeature.TARGET_TEMPERATURE_RANGE: elif features & ClimateEntityFeature.TARGET_TEMPERATURE_RANGE:
@ -478,7 +483,8 @@ class Thermostat(HomeAccessory):
min_temp, max_temp = self.get_temperature_range() min_temp, max_temp = self.get_temperature_range()
if CHAR_COOLING_THRESHOLD_TEMPERATURE in char_values: if CHAR_COOLING_THRESHOLD_TEMPERATURE in char_values:
events.append( events.append(
f"{CHAR_COOLING_THRESHOLD_TEMPERATURE} to {char_values[CHAR_COOLING_THRESHOLD_TEMPERATURE]}°C" f"{CHAR_COOLING_THRESHOLD_TEMPERATURE} to"
f" {char_values[CHAR_COOLING_THRESHOLD_TEMPERATURE]}°C"
) )
high = char_values[CHAR_COOLING_THRESHOLD_TEMPERATURE] high = char_values[CHAR_COOLING_THRESHOLD_TEMPERATURE]
# If the device doesn't support TARGET_TEMPATURE # If the device doesn't support TARGET_TEMPATURE
@ -487,7 +493,8 @@ class Thermostat(HomeAccessory):
low = high - HEAT_COOL_DEADBAND low = high - HEAT_COOL_DEADBAND
if CHAR_HEATING_THRESHOLD_TEMPERATURE in char_values: if CHAR_HEATING_THRESHOLD_TEMPERATURE in char_values:
events.append( events.append(
f"{CHAR_HEATING_THRESHOLD_TEMPERATURE} to {char_values[CHAR_HEATING_THRESHOLD_TEMPERATURE]}°C" f"{CHAR_HEATING_THRESHOLD_TEMPERATURE} to"
f" {char_values[CHAR_HEATING_THRESHOLD_TEMPERATURE]}°C"
) )
low = char_values[CHAR_HEATING_THRESHOLD_TEMPERATURE] low = char_values[CHAR_HEATING_THRESHOLD_TEMPERATURE]
# If the device doesn't support TARGET_TEMPATURE # If the device doesn't support TARGET_TEMPATURE
@ -598,7 +605,10 @@ class Thermostat(HomeAccessory):
self.char_target_heat_cool.set_value(homekit_hvac_mode) self.char_target_heat_cool.set_value(homekit_hvac_mode)
else: else:
_LOGGER.error( _LOGGER.error(
"Cannot map hvac target mode: %s to homekit as only %s modes are supported", (
"Cannot map hvac target mode: %s to homekit as only %s modes"
" are supported"
),
hvac_mode, hvac_mode,
self.hc_homekit_to_hass, self.hc_homekit_to_hass,
) )

View File

@ -349,7 +349,7 @@ def async_show_setup_message(
message = ( message = (
f"To set up {bridge_name} in the Home App, " f"To set up {bridge_name} in the Home App, "
f"scan the QR code or enter the following code:\n" "scan the QR code or enter the following code:\n"
f"### {pin}\n" f"### {pin}\n"
f"![image](/api/homekit/pairingqr?{entry_id}-{pairing_secret})" f"![image](/api/homekit/pairingqr?{entry_id}-{pairing_secret})"
) )

View File

@ -97,9 +97,11 @@ async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
await controller.remove_pairing(hkid) await controller.remove_pairing(hkid)
except aiohomekit.AccessoryDisconnectedError: except aiohomekit.AccessoryDisconnectedError:
_LOGGER.warning( _LOGGER.warning(
(
"Accessory %s was removed from HomeAssistant but was not reachable " "Accessory %s was removed from HomeAssistant but was not reachable "
"to properly unpair. It may need resetting before you can use it with " "to properly unpair. It may need resetting before you can use it with "
"HomeKit again", "HomeKit again"
),
entry.title, entry.title,
) )

View File

@ -187,8 +187,11 @@ class HomeKitHeaterCoolerEntity(HomeKitBaseClimateEntity):
else: else:
hvac_mode = TARGET_HEATER_COOLER_STATE_HOMEKIT_TO_HASS.get(state) hvac_mode = TARGET_HEATER_COOLER_STATE_HOMEKIT_TO_HASS.get(state)
_LOGGER.warning( _LOGGER.warning(
"HomeKit device %s: Setting temperature in %s mode is not supported yet;" (
" Consider raising a ticket if you have this device and want to help us implement this feature", "HomeKit device %s: Setting temperature in %s mode is not supported"
" yet; Consider raising a ticket if you have this device and want"
" to help us implement this feature"
),
self.entity_id, self.entity_id,
hvac_mode, hvac_mode,
) )
@ -202,8 +205,11 @@ class HomeKitHeaterCoolerEntity(HomeKitBaseClimateEntity):
return return
if hvac_mode not in {HVACMode.HEAT, HVACMode.COOL}: if hvac_mode not in {HVACMode.HEAT, HVACMode.COOL}:
_LOGGER.warning( _LOGGER.warning(
"HomeKit device %s: Setting temperature in %s mode is not supported yet;" (
" Consider raising a ticket if you have this device and want to help us implement this feature", "HomeKit device %s: Setting temperature in %s mode is not supported"
" yet; Consider raising a ticket if you have this device and want"
" to help us implement this feature"
),
self.entity_id, self.entity_id,
hvac_mode, hvac_mode,
) )

View File

@ -167,7 +167,9 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
{ {
vol.Required("device"): vol.In( vol.Required("device"): vol.In(
{ {
key: f"{key} ({formatted_category(discovery.description.category)})" key: (
f"{key} ({formatted_category(discovery.description.category)})"
)
for key, discovery in self.devices.items() for key, discovery in self.devices.items()
} }
) )
@ -232,7 +234,10 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
# This can happen if the TXT record is received after the PTR record # This can happen if the TXT record is received after the PTR record
# we will wait for the next update in this case # we will wait for the next update in this case
_LOGGER.debug( _LOGGER.debug(
"HomeKit device %s: id not exposed; TXT record may have not yet been received", (
"HomeKit device %s: id not exposed; TXT record may have not yet"
" been received"
),
properties, properties,
) )
return self.async_abort(reason="invalid_properties") return self.async_abort(reason="invalid_properties")
@ -291,7 +296,10 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
await pairing.list_accessories_and_characteristics() await pairing.list_accessories_and_characteristics()
except AuthenticationError: except AuthenticationError:
_LOGGER.debug( _LOGGER.debug(
"%s (%s - %s) is unpaired. Removing invalid pairing for this device", (
"%s (%s - %s) is unpaired. Removing invalid pairing for this"
" device"
),
name, name,
model, model,
hkid, hkid,
@ -299,9 +307,11 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
await self.hass.config_entries.async_remove(existing.entry_id) await self.hass.config_entries.async_remove(existing.entry_id)
else: else:
_LOGGER.debug( _LOGGER.debug(
(
"%s (%s - %s) claims to be unpaired but isn't. " "%s (%s - %s) claims to be unpaired but isn't. "
"It's implementation of HomeKit is defective " "It's implementation of HomeKit is defective "
"or a zeroconf relay is broadcasting stale data", "or a zeroconf relay is broadcasting stale data"
),
name, name,
model, model,
hkid, hkid,

View File

@ -194,8 +194,10 @@ class HKDevice:
await self.pairing.async_populate_accessories_state(force_update=True) await self.pairing.async_populate_accessories_state(force_update=True)
except STARTUP_EXCEPTIONS as ex: except STARTUP_EXCEPTIONS as ex:
_LOGGER.debug( _LOGGER.debug(
"Failed to populate BLE accessory state for %s, accessory may be sleeping" (
" and will be retried the next time it advertises: %s", "Failed to populate BLE accessory state for %s, accessory may be"
" sleeping and will be retried the next time it advertises: %s"
),
self.config_entry.title, self.config_entry.title,
ex, ex,
) )
@ -360,7 +362,10 @@ class HKDevice:
if self.config_entry.entry_id not in device.config_entries: if self.config_entry.entry_id not in device.config_entries:
_LOGGER.info( _LOGGER.info(
"Found candidate device for %s:aid:%s, but owned by a different config entry, skipping", (
"Found candidate device for %s:aid:%s, but owned by a different"
" config entry, skipping"
),
self.unique_id, self.unique_id,
accessory.aid, accessory.aid,
) )
@ -407,7 +412,10 @@ class HKDevice:
platform, DOMAIN, new_unique_id platform, DOMAIN, new_unique_id
): ):
_LOGGER.debug( _LOGGER.debug(
"Unique ID %s is already in use by %s (system may have been downgraded)", (
"Unique ID %s is already in use by %s (system may have been"
" downgraded)"
),
new_unique_id, new_unique_id,
new_entity_id, new_entity_id,
) )
@ -429,7 +437,10 @@ class HKDevice:
does not require them to be stable. does not require them to be stable.
""" """
_LOGGER.debug( _LOGGER.debug(
"Removing legacy serial numbers from device registry entries for pairing %s", (
"Removing legacy serial numbers from device registry entries for"
" pairing %s"
),
self.unique_id, self.unique_id,
) )
@ -491,14 +502,20 @@ class HKDevice:
for accessory in self.entity_map.accessories: for accessory in self.entity_map.accessories:
if not valid_serial_number(accessory.serial_number): if not valid_serial_number(accessory.serial_number):
_LOGGER.debug( _LOGGER.debug(
"Serial number %r is not valid, it cannot be used as a unique identifier", (
"Serial number %r is not valid, it cannot be used as a unique"
" identifier"
),
accessory.serial_number, accessory.serial_number,
) )
unreliable_serial_numbers = True unreliable_serial_numbers = True
elif accessory.serial_number in devices: elif accessory.serial_number in devices:
_LOGGER.debug( _LOGGER.debug(
"Serial number %r is duplicated within this pairing, it cannot be used as a unique identifier", (
"Serial number %r is duplicated within this pairing, it cannot"
" be used as a unique identifier"
),
accessory.serial_number, accessory.serial_number,
) )
unreliable_serial_numbers = True unreliable_serial_numbers = True
@ -506,7 +523,10 @@ class HKDevice:
elif accessory.serial_number == accessory.hardware_revision: elif accessory.serial_number == accessory.hardware_revision:
# This is a known bug with some devices (e.g. RYSE SmartShades) # This is a known bug with some devices (e.g. RYSE SmartShades)
_LOGGER.debug( _LOGGER.debug(
"Serial number %r is actually the hardware revision, it cannot be used as a unique identifier", (
"Serial number %r is actually the hardware revision, it cannot"
" be used as a unique identifier"
),
accessory.serial_number, accessory.serial_number,
) )
unreliable_serial_numbers = True unreliable_serial_numbers = True
@ -670,7 +690,10 @@ class HKDevice:
if self._polling_lock.locked(): if self._polling_lock.locked():
if not self._polling_lock_warned: if not self._polling_lock_warned:
_LOGGER.warning( _LOGGER.warning(
"HomeKit controller update skipped as previous poll still in flight: %s", (
"HomeKit controller update skipped as previous poll still in"
" flight: %s"
),
self.unique_id, self.unique_id,
) )
self._polling_lock_warned = True self._polling_lock_warned = True
@ -678,7 +701,10 @@ class HKDevice:
if self._polling_lock_warned: if self._polling_lock_warned:
_LOGGER.info( _LOGGER.info(
"HomeKit controller no longer detecting back pressure - not skipping poll: %s", (
"HomeKit controller no longer detecting back pressure - not"
" skipping poll: %s"
),
self.unique_id, self.unique_id,
) )
self._polling_lock_warned = False self._polling_lock_warned = False

View File

@ -308,7 +308,10 @@ def setup_platform(
if (entity_desc := SENSOR_DESCRIPTIONS.get(state)) is None: if (entity_desc := SENSOR_DESCRIPTIONS.get(state)) is None:
name = conf.get(ATTR_NAME) name = conf.get(ATTR_NAME)
_LOGGER.warning( _LOGGER.warning(
"Sensor (%s) entity description is missing. Sensor state (%s) needs to be maintained", (
"Sensor (%s) entity description is missing. Sensor state (%s) needs"
" to be maintained"
),
name, name,
state, state,
) )

View File

@ -109,7 +109,10 @@ class HomematicipAlarmControlPanelEntity(AlarmControlPanelEntity):
self.async_write_ha_state() self.async_write_ha_state()
else: else:
_LOGGER.debug( _LOGGER.debug(
"Device Changed Event for %s (Alarm Control Panel) not fired. Entity is disabled", (
"Device Changed Event for %s (Alarm Control Panel) not fired."
" Entity is disabled"
),
self.name, self.name,
) )

View File

@ -190,8 +190,10 @@ class HomematicipHAP:
await hmip_events await hmip_events
except HmipConnectionError: except HmipConnectionError:
_LOGGER.error( _LOGGER.error(
(
"Error connecting to HomematicIP with HAP %s. " "Error connecting to HomematicIP with HAP %s. "
"Retrying in %d seconds", "Retrying in %d seconds"
),
self.config_entry.unique_id, self.config_entry.unique_id,
retry_delay, retry_delay,
) )

View File

@ -44,8 +44,9 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self.hass, self.hass,
title="HomeWizard Energy", title="HomeWizard Energy",
message=( message=(
"The custom integration of HomeWizard Energy has been migrated to core. " "The custom integration of HomeWizard Energy has been migrated to core."
"You can safely remove the custom integration from the custom_integrations folder." " You can safely remove the custom integration from the"
" custom_integrations folder."
), ),
notification_id=f"homewizard_energy_to_{DOMAIN}", notification_id=f"homewizard_energy_to_{DOMAIN}",
) )

View File

@ -162,7 +162,8 @@ class HoneywellData:
self.devices[updated_device.deviceid] = updated_device self.devices[updated_device.deviceid] = updated_device
else: else:
_LOGGER.info( _LOGGER.info(
"New device with ID %s detected, reload the honeywell integration if you want to access it in Home Assistant" "New device with ID %s detected, reload the honeywell integration"
" if you want to access it in Home Assistant"
) )
await self._hass.config_entries.async_reload(self._config.entry_id) await self._hass.config_entries.async_reload(self._config.entry_id)

View File

@ -361,7 +361,8 @@ class HomeAssistantHTTP:
except OSError as error: except OSError as error:
if not self.hass.config.safe_mode: if not self.hass.config.safe_mode:
raise HomeAssistantError( raise HomeAssistantError(
f"Could not use SSL certificate from {self.ssl_certificate}: {error}" f"Could not use SSL certificate from {self.ssl_certificate}:"
f" {error}"
) from error ) from error
_LOGGER.error( _LOGGER.error(
"Could not read SSL certificate from %s: %s", "Could not read SSL certificate from %s: %s",
@ -378,14 +379,17 @@ class HomeAssistantHTTP:
context = None context = None
else: else:
_LOGGER.critical( _LOGGER.critical(
"Home Assistant is running in safe mode with an emergency self signed ssl certificate because the configured SSL certificate was not usable" "Home Assistant is running in safe mode with an emergency self"
" signed ssl certificate because the configured SSL certificate was"
" not usable"
) )
return context return context
if self.ssl_peer_certificate: if self.ssl_peer_certificate:
if context is None: if context is None:
raise HomeAssistantError( raise HomeAssistantError(
"Failed to create ssl context, no fallback available because a peer certificate is required." "Failed to create ssl context, no fallback available because a peer"
" certificate is required."
) )
context.verify_mode = ssl.CERT_REQUIRED context.verify_mode = ssl.CERT_REQUIRED

View File

@ -116,7 +116,10 @@ async def process_wrong_login(request: Request) -> None:
gethostbyaddr, request.remote gethostbyaddr, request.remote
) )
base_msg = f"Login attempt or request with invalid authentication from {remote_host} ({remote_addr})." base_msg = (
"Login attempt or request with invalid authentication from"
f" {remote_host} ({remote_addr})."
)
# The user-agent is unsanitized input so we only include it in the log # The user-agent is unsanitized input so we only include it in the log
user_agent = request.headers.get("user-agent") user_agent = request.headers.get("user-agent")

View File

@ -112,8 +112,10 @@ def async_setup_forwarded(
# We have X-Forwarded-For, but config does not agree # We have X-Forwarded-For, but config does not agree
if not use_x_forwarded_for: if not use_x_forwarded_for:
_LOGGER.error( _LOGGER.error(
(
"A request from a reverse proxy was received from %s, but your " "A request from a reverse proxy was received from %s, but your "
"HTTP integration is not set-up for reverse proxies", "HTTP integration is not set-up for reverse proxies"
),
connected_ip, connected_ip,
) )
raise HTTPBadRequest raise HTTPBadRequest
@ -186,7 +188,10 @@ def async_setup_forwarded(
# of elements as X-Forwarded-For # of elements as X-Forwarded-For
if len(forwarded_proto) not in (1, len(forwarded_for)): if len(forwarded_proto) not in (1, len(forwarded_for)):
_LOGGER.error( _LOGGER.error(
"Incorrect number of elements in X-Forward-Proto. Expected 1 or %d, got %d: %s", (
"Incorrect number of elements in X-Forward-Proto. Expected 1 or"
" %d, got %d: %s"
),
len(forwarded_for), len(forwarded_for),
len(forwarded_proto), len(forwarded_proto),
forwarded_proto_headers[0], forwarded_proto_headers[0],

View File

@ -78,9 +78,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
): ):
persistent_notification.async_create( persistent_notification.async_create(
hass, hass,
(
"Your Hue hub has a known security vulnerability ([CVE-2020-6007] " "Your Hue hub has a known security vulnerability ([CVE-2020-6007] "
"(https://cve.circl.lu/cve/CVE-2020-6007)). " "(https://cve.circl.lu/cve/CVE-2020-6007)). "
"Go to the Hue app and check for software updates.", "Go to the Hue app and check for software updates."
),
"Signify Hue", "Signify Hue",
"hue_hub_firmware", "hue_hub_firmware",
) )

View File

@ -115,7 +115,10 @@ async def handle_v2_migration(hass: core.HomeAssistant, entry: ConfigEntry) -> N
if hass_dev_id is None: if hass_dev_id is None:
# can be safely ignored, this device does not exist in current config # can be safely ignored, this device does not exist in current config
LOGGER.debug( LOGGER.debug(
"Ignoring device %s (%s) as it does not (yet) exist in the device registry", (
"Ignoring device %s (%s) as it does not (yet) exist in the"
" device registry"
),
hue_dev.metadata.name, hue_dev.metadata.name,
hue_dev.id, hue_dev.id,
) )
@ -149,7 +152,10 @@ async def handle_v2_migration(hass: core.HomeAssistant, entry: ConfigEntry) -> N
if new_unique_id is None: if new_unique_id is None:
# this may happen if we're looking at orphaned or unsupported entity # this may happen if we're looking at orphaned or unsupported entity
LOGGER.warning( LOGGER.warning(
"Skip migration of %s because it no longer exists on the bridge", (
"Skip migration of %s because it no longer exists on the"
" bridge"
),
ent.entity_id, ent.entity_id,
) )
continue continue

View File

@ -133,8 +133,10 @@ async def hue_activate_scene_v2(
) -> bool: ) -> bool:
"""Service for V2 bridge to call scene by name.""" """Service for V2 bridge to call scene by name."""
LOGGER.warning( LOGGER.warning(
(
"Use of service_call '%s' is deprecated and will be removed " "Use of service_call '%s' is deprecated and will be removed "
"in a future release. Please use scene entities instead", "in a future release. Please use scene entities instead"
),
SERVICE_HUE_ACTIVATE_SCENE, SERVICE_HUE_ACTIVATE_SCENE,
) )
api: HueBridgeV2 = bridge.api api: HueBridgeV2 = bridge.api

View File

@ -196,11 +196,13 @@ class HueBaseEntity(Entity):
# the device state changed from on->off or off->on # the device state changed from on->off or off->on
# while it was reported as not connected! # while it was reported as not connected!
self.logger.warning( self.logger.warning(
"Device %s changed state while reported as disconnected. " (
"This might be an indicator that routing is not working for this device " "Device %s changed state while reported as disconnected. This"
"or the device is having connectivity issues. " " might be an indicator that routing is not working for this"
"You can disable availability reporting for this device in the Hue options. " " device or the device is having connectivity issues. You can"
"Device details: %s - %s (%s) fw: %s", " disable availability reporting for this device in the Hue"
" options. Device details: %s - %s (%s) fw: %s"
),
self.name, self.name,
self.device.product_data.manufacturer_name, self.device.product_data.manufacturer_name,
self.device.product_data.product_name, self.device.product_data.product_name,

View File

@ -87,7 +87,9 @@ async def async_attach_trigger(
numeric_state_config = { numeric_state_config = {
numeric_state_trigger.CONF_PLATFORM: "numeric_state", numeric_state_trigger.CONF_PLATFORM: "numeric_state",
numeric_state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID], numeric_state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID],
numeric_state_trigger.CONF_VALUE_TEMPLATE: "{{ state.attributes.humidity }}", numeric_state_trigger.CONF_VALUE_TEMPLATE: (
"{{ state.attributes.humidity }}"
),
} }
if CONF_ABOVE in config: if CONF_ABOVE in config:

View File

@ -95,7 +95,9 @@ class ShadeEntity(HDEntity):
manufacturer=MANUFACTURER, manufacturer=MANUFACTURER,
model=str(self._shade.raw_data[ATTR_TYPE]), model=str(self._shade.raw_data[ATTR_TYPE]),
via_device=(DOMAIN, self._device_info.serial_number), via_device=(DOMAIN, self._device_info.serial_number),
configuration_url=f"http://{self._device_info.hub_address}/api/shades/{self._shade.id}", configuration_url=(
f"http://{self._device_info.hub_address}/api/shades/{self._shade.id}"
),
) )
for shade in self._shade.shade_types: for shade in self._shade.shade_types:

View File

@ -198,7 +198,10 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
{ {
vol.Optional(CONF_FILTER, default=old_filter): cv.multi_select( vol.Optional(CONF_FILTER, default=old_filter): cv.multi_select(
{ {
key: f"{departure_filter['serviceName']}, {departure_filter['label']}" key: (
f"{departure_filter['serviceName']},"
f" {departure_filter['label']}"
)
for key, departure_filter in self.departure_filters.items() for key, departure_filter in self.departure_filters.items()
} }
), ),

View File

@ -153,9 +153,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
with suppress(ValueError): with suppress(ValueError):
if AwesomeVersion(version) < AwesomeVersion(HYPERION_VERSION_WARN_CUTOFF): if AwesomeVersion(version) < AwesomeVersion(HYPERION_VERSION_WARN_CUTOFF):
_LOGGER.warning( _LOGGER.warning(
"Using a Hyperion server version < %s is not recommended -- " (
"some features may be unavailable or may not function correctly. " "Using a Hyperion server version < %s is not recommended --"
"Please consider upgrading: %s", " some features may be unavailable or may not function"
" correctly. Please consider upgrading: %s"
),
HYPERION_VERSION_WARN_CUTOFF, HYPERION_VERSION_WARN_CUTOFF,
HYPERION_RELEASES_URL, HYPERION_RELEASES_URL,
) )

View File

@ -26,9 +26,9 @@ NAME_SUFFIX_HYPERION_PRIORITY_LIGHT = "Priority"
NAME_SUFFIX_HYPERION_COMPONENT_SWITCH = "Component" NAME_SUFFIX_HYPERION_COMPONENT_SWITCH = "Component"
NAME_SUFFIX_HYPERION_CAMERA = "" NAME_SUFFIX_HYPERION_CAMERA = ""
SIGNAL_INSTANCE_ADD = f"{DOMAIN}_instance_add_signal." "{}" SIGNAL_INSTANCE_ADD = f"{DOMAIN}_instance_add_signal.{{}}"
SIGNAL_INSTANCE_REMOVE = f"{DOMAIN}_instance_remove_signal." "{}" SIGNAL_INSTANCE_REMOVE = f"{DOMAIN}_instance_remove_signal.{{}}"
SIGNAL_ENTITY_REMOVE = f"{DOMAIN}_entity_remove_signal." "{}" SIGNAL_ENTITY_REMOVE = f"{DOMAIN}_entity_remove_signal.{{}}"
TYPE_HYPERION_CAMERA = "hyperion_camera" TYPE_HYPERION_CAMERA = "hyperion_camera"
TYPE_HYPERION_LIGHT = "hyperion_light" TYPE_HYPERION_LIGHT = "hyperion_light"

View File

@ -292,8 +292,10 @@ class HyperionBaseLight(LightEntity):
component = const.KEY_COMPONENTID_FROM_NAME[effect] component = const.KEY_COMPONENTID_FROM_NAME[effect]
else: else:
_LOGGER.warning( _LOGGER.warning(
(
"Use of Hyperion effect '%s' is deprecated and will be removed " "Use of Hyperion effect '%s' is deprecated and will be removed "
"in a future release. Please use '%s' instead", "in a future release. Please use '%s' instead"
),
effect, effect,
const.KEY_COMPONENTID_TO_NAME[effect], const.KEY_COMPONENTID_TO_NAME[effect],
) )
@ -433,8 +435,10 @@ class HyperionBaseLight(LightEntity):
self._update_effect_list() self._update_effect_list()
_LOGGER.debug( _LOGGER.debug(
(
"Hyperion full state update: On=%s,Brightness=%i,Effect=%s " "Hyperion full state update: On=%s,Brightness=%i,Effect=%s "
"(%i effects total),Color=%s", "(%i effects total),Color=%s"
),
self.is_on, self.is_on,
self._brightness, self._brightness,
self._effect, self._effect,

View File

@ -135,18 +135,21 @@ def validate_version_specific_config(conf: dict) -> dict:
if conf[CONF_API_VERSION] == API_VERSION_2: if conf[CONF_API_VERSION] == API_VERSION_2:
if CONF_TOKEN not in conf: if CONF_TOKEN not in conf:
raise vol.Invalid( raise vol.Invalid(
f"{CONF_TOKEN} and {CONF_BUCKET} are required when {CONF_API_VERSION} is {API_VERSION_2}" f"{CONF_TOKEN} and {CONF_BUCKET} are required when"
f" {CONF_API_VERSION} is {API_VERSION_2}"
) )
if CONF_USERNAME in conf: if CONF_USERNAME in conf:
raise vol.Invalid( raise vol.Invalid(
f"{CONF_USERNAME} and {CONF_PASSWORD} are only allowed when {CONF_API_VERSION} is {DEFAULT_API_VERSION}" f"{CONF_USERNAME} and {CONF_PASSWORD} are only allowed when"
f" {CONF_API_VERSION} is {DEFAULT_API_VERSION}"
) )
else: else:
if CONF_TOKEN in conf: if CONF_TOKEN in conf:
raise vol.Invalid( raise vol.Invalid(
f"{CONF_TOKEN} and {CONF_BUCKET} are only allowed when {CONF_API_VERSION} is {API_VERSION_2}" f"{CONF_TOKEN} and {CONF_BUCKET} are only allowed when"
f" {CONF_API_VERSION} is {API_VERSION_2}"
) )
return conf return conf

View File

@ -83,7 +83,8 @@ def validate_query_format_for_version(conf: dict) -> dict:
if conf[CONF_API_VERSION] == API_VERSION_2: if conf[CONF_API_VERSION] == API_VERSION_2:
if CONF_QUERIES_FLUX not in conf: if CONF_QUERIES_FLUX not in conf:
raise vol.Invalid( raise vol.Invalid(
f"{CONF_QUERIES_FLUX} is required when {CONF_API_VERSION} is {API_VERSION_2}" f"{CONF_QUERIES_FLUX} is required when {CONF_API_VERSION} is"
f" {API_VERSION_2}"
) )
for query in conf[CONF_QUERIES_FLUX]: for query in conf[CONF_QUERIES_FLUX]:
@ -95,7 +96,8 @@ def validate_query_format_for_version(conf: dict) -> dict:
else: else:
if CONF_QUERIES not in conf: if CONF_QUERIES not in conf:
raise vol.Invalid( raise vol.Invalid(
f"{CONF_QUERIES} is required when {CONF_API_VERSION} is {DEFAULT_API_VERSION}" f"{CONF_QUERIES} is required when {CONF_API_VERSION} is"
f" {DEFAULT_API_VERSION}"
) )
for query in conf[CONF_QUERIES]: for query in conf[CONF_QUERIES]:
@ -270,7 +272,10 @@ class InfluxFluxSensorData:
self.value = None self.value = None
self.full_query = None self.full_query = None
self.query_prefix = f'from(bucket:"{bucket}") |> range(start: {range_start}, stop: {range_stop}) |>' self.query_prefix = (
f'from(bucket:"{bucket}") |> range(start: {range_start}, stop:'
f" {range_stop}) |>"
)
if imports is not None: if imports is not None:
for i in imports: for i in imports:
self.query_prefix = f'import "{i}" {self.query_prefix}' self.query_prefix = f'import "{i}" {self.query_prefix}'
@ -334,7 +339,10 @@ class InfluxQLSensorData:
_LOGGER.error(RENDERING_WHERE_ERROR_MESSAGE, ex) _LOGGER.error(RENDERING_WHERE_ERROR_MESSAGE, ex)
return return
self.query = f"select {self.group}({self.field}) as {INFLUX_CONF_VALUE} from {self.measurement} where {where_clause}" self.query = (
f"select {self.group}({self.field}) as {INFLUX_CONF_VALUE} from"
f" {self.measurement} where {where_clause}"
)
_LOGGER.debug(RUNNING_QUERY_MESSAGE, self.query) _LOGGER.debug(RUNNING_QUERY_MESSAGE, self.query)