Use f-strings in integrations starting with "F"and"G" (#32150)

* Use f-strings in integrations starting with F

* Use f-strings in tests for integrations starting with F

* Use f-strings in integrations starting with G

* Use f-strings in tests for integrations starting with G

* Fix pylint error

* Fix broken test
This commit is contained in:
springstan authored and GitHub committed 2020-02-24 17:54:20 -08:00
1 parent 496bd3dddf
commit ad102b3840
59 files changed
+219 -344

No files matched your search

+4 -4
View File
@@ -247,8 +247,8 @@ class FibaroController:
room_name = self._room_map[device.roomID].name
device.room_name = room_name
device.friendly_name = f"{room_name} {device.name}"
device.ha_id = "scene_{}_{}_{}".format(
slugify(room_name), slugify(device.name), device.id
device.ha_id = (
f"scene_{slugify(room_name)}_{slugify(device.name)}_{device.id}"
)
device.unique_id_str = f"{self.hub_serial}.scene.{device.id}"
self._scene_map[device.id] = device
@@ -269,8 +269,8 @@ class FibaroController:
room_name = self._room_map[device.roomID].name
device.room_name = room_name
device.friendly_name = f"{room_name} {device.name}"
device.ha_id = "{}_{}_{}".format(
slugify(room_name), slugify(device.name), device.id
device.ha_id = (
f"{slugify(room_name)}_{slugify(device.name)}_{device.id}"
)
if (
device.enabled
@@ -1,7 +1,7 @@
"""Support for Fibaro binary sensors."""
import logging
from homeassistant.components.binary_sensor import ENTITY_ID_FORMAT, BinarySensorDevice
from homeassistant.components.binary_sensor import DOMAIN, BinarySensorDevice
from homeassistant.const import CONF_DEVICE_CLASS, CONF_ICON
from . import FIBARO_DEVICES, FibaroDevice
@@ -40,7 +40,7 @@ class FibaroBinarySensor(FibaroDevice, BinarySensorDevice):
"""Initialize the binary_sensor."""
self._state = None
super().__init__(fibaro_device)
self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id)
self.entity_id = f"{DOMAIN}.{self.ha_id}"
stype = None
devconf = fibaro_device.device_config
if fibaro_device.type in SENSOR_TYPES:
+2 -2
View File
@@ -4,7 +4,7 @@ import logging
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
ENTITY_ID_FORMAT,
DOMAIN,
CoverDevice,
)
@@ -29,7 +29,7 @@ class FibaroCover(FibaroDevice, CoverDevice):
def __init__(self, fibaro_device):
"""Initialize the Vera device."""
super().__init__(fibaro_device)
self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id)
self.entity_id = f"{DOMAIN}.{self.ha_id}"
@staticmethod
def bound(position):
+2 -2
View File
@@ -7,7 +7,7 @@ from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_HS_COLOR,
ATTR_WHITE_VALUE,
ENTITY_ID_FORMAT,
DOMAIN,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_WHITE_VALUE,
@@ -77,7 +77,7 @@ class FibaroLight(FibaroDevice, Light):
self._supported_flags |= SUPPORT_WHITE_VALUE
super().__init__(fibaro_device)
self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id)
self.entity_id = f"{DOMAIN}.{self.ha_id}"
@property
def brightness(self):
+2 -2
View File
@@ -1,7 +1,7 @@
"""Support for Fibaro sensors."""
import logging
from homeassistant.components.sensor import ENTITY_ID_FORMAT
from homeassistant.components.sensor import DOMAIN
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
DEVICE_CLASS_HUMIDITY,
@@ -53,7 +53,7 @@ class FibaroSensor(FibaroDevice, Entity):
self.current_value = None
self.last_changed_time = None
super().__init__(fibaro_device)
self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id)
self.entity_id = f"{DOMAIN}.{self.ha_id}"
if fibaro_device.type in SENSOR_TYPES:
self._unit = SENSOR_TYPES[fibaro_device.type][1]
self._icon = SENSOR_TYPES[fibaro_device.type][2]
+2 -2
View File
@@ -1,7 +1,7 @@
"""Support for Fibaro switches."""
import logging
from homeassistant.components.switch import ENTITY_ID_FORMAT, SwitchDevice
from homeassistant.components.switch import DOMAIN, SwitchDevice
from homeassistant.util import convert
from . import FIBARO_DEVICES, FibaroDevice
@@ -26,7 +26,7 @@ class FibaroSwitch(FibaroDevice, SwitchDevice):
"""Initialize the Fibaro device."""
self._state = False
super().__init__(fibaro_device)
self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id)
self.entity_id = f"{DOMAIN}.{self.ha_id}"
def turn_on(self, **kwargs):
"""Turn device on."""
+2 -6
View File
@@ -46,15 +46,11 @@ class FileNotificationService(BaseNotificationService):
"""Send a message to a file."""
with open(self.filepath, "a") as file:
if os.stat(self.filepath).st_size == 0:
title = "{} notifications (Log started: {})\n{}\n".format(
kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT),
dt_util.utcnow().isoformat(),
"-" * 80,
)
title = f"{kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)} notifications (Log started: {dt_util.utcnow().isoformat()})\n{'-' * 80}\n"
file.write(title)
if self.add_timestamp:
text = "{} {}\n".format(dt_util.utcnow().isoformat(), message)
text = f"{dt_util.utcnow().isoformat()} {message}\n"
else:
text = f"{message}\n"
file.write(text)
+15 -27
View File
@@ -181,16 +181,14 @@ def request_app_setup(hass, config, add_entities, config_path, discovery_info=No
start_url = f"{hass.config.api.base_url}{FITBIT_AUTH_CALLBACK_PATH}"
description = """Please create a Fitbit developer app at
description = f"""Please create a Fitbit developer app at
https://dev.fitbit.com/apps/new.
For the OAuth 2.0 Application Type choose Personal.
Set the Callback URL to {}.
Set the Callback URL to {start_url}.
They will provide you a Client ID and secret.
These need to be saved into the file located at: {}.
These need to be saved into the file located at: {config_path}.
Then come back here and hit the below button.
""".format(
start_url, config_path
)
"""
submit = "I have saved my Client ID and Client Secret into fitbit.conf."
@@ -308,9 +306,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
config_file.get(ATTR_CLIENT_ID), config_file.get(ATTR_CLIENT_SECRET)
)
redirect_uri = "{}{}".format(
hass.config.api.base_url, FITBIT_AUTH_CALLBACK_PATH
)
redirect_uri = f"{hass.config.api.base_url}{FITBIT_AUTH_CALLBACK_PATH}"
fitbit_auth_start_url, _ = oauth.authorize_token_url(
redirect_uri=redirect_uri,
@@ -355,26 +351,20 @@ class FitbitAuthCallbackView(HomeAssistantView):
result = None
if data.get("code") is not None:
redirect_uri = "{}{}".format(
hass.config.api.base_url, FITBIT_AUTH_CALLBACK_PATH
)
redirect_uri = f"{hass.config.api.base_url}{FITBIT_AUTH_CALLBACK_PATH}"
try:
result = self.oauth.fetch_access_token(data.get("code"), redirect_uri)
except MissingTokenError as error:
_LOGGER.error("Missing token: %s", error)
response_message = """Something went wrong when
response_message = f"""Something went wrong when
attempting authenticating with Fitbit. The error
encountered was {}. Please try again!""".format(
error
)
encountered was {error}. Please try again!"""
except MismatchingStateError as error:
_LOGGER.error("Mismatched state, CSRF error: %s", error)
response_message = """Something went wrong when
response_message = f"""Something went wrong when
attempting authenticating with Fitbit. The error
encountered was {}. Please try again!""".format(
error
)
encountered was {error}. Please try again!"""
else:
_LOGGER.error("Unknown error when authing")
response_message = """Something went wrong when
@@ -389,10 +379,8 @@ class FitbitAuthCallbackView(HomeAssistantView):
An unknown error occurred. Please try again!
"""
html_response = """<html><head><title>Fitbit Auth</title></head>
<body><h1>{}</h1></body></html>""".format(
response_message
)
html_response = f"""<html><head><title>Fitbit Auth</title></head>
<body><h1>{response_message}</h1></body></html>"""
if result:
config_contents = {
@@ -424,7 +412,7 @@ class FitbitSensor(Entity):
self.extra = extra
self._name = FITBIT_RESOURCES_LIST[self.resource_type][0]
if self.extra:
self._name = "{0} Battery".format(self.extra.get("deviceVersion"))
self._name = f"{self.extra.get('deviceVersion')} Battery"
unit_type = FITBIT_RESOURCES_LIST[self.resource_type][1]
if unit_type == "":
split_resource = self.resource_type.split("/")
@@ -460,7 +448,7 @@ class FitbitSensor(Entity):
if self.resource_type == "devices/battery" and self.extra:
battery_level = BATTERY_LEVELS[self.extra.get("battery")]
return icon_for_battery_level(battery_level=battery_level, charging=None)
return "mdi:{}".format(FITBIT_RESOURCES_LIST[self.resource_type][2])
return f"mdi:{FITBIT_RESOURCES_LIST[self.resource_type][2]}"
@property
def device_state_attributes(self):
@@ -513,7 +501,7 @@ class FitbitSensor(Entity):
self._state = raw_state
else:
try:
self._state = "{0:,}".format(int(raw_state))
self._state = f"{int(raw_state):,}"
except TypeError:
self._state = raw_state
@@ -168,7 +168,7 @@ class FlicButton(BinarySensorDevice):
@property
def name(self):
"""Return the name of the device."""
return "flic_{}".format(self.address.replace(":", ""))
return f"flic_{self.address.replace(':', '')}"
@property
def address(self):
@@ -192,9 +192,7 @@ class FlicButton(BinarySensorDevice):
def _queued_event_check(self, click_type, time_diff):
"""Generate a log message and returns true if timeout exceeded."""
time_string = "{:d} {}".format(
time_diff, "second" if time_diff == 1 else "seconds"
)
time_string = f"{time_diff:d} {'second' if time_diff == 1 else 'seconds'}"
if time_diff > self._timeout:
_LOGGER.warning(
+1 -1
View File
@@ -164,7 +164,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
"""Update lights."""
await flux.async_flux_update()
service_name = slugify("{} {}".format(name, "update"))
service_name = slugify(f"{name} update")
hass.services.async_register(DOMAIN, service_name, async_update)
+1 -1
View File
@@ -167,7 +167,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
ipaddr = device["ipaddr"]
if ipaddr in light_ips:
continue
device["name"] = "{} {}".format(device["id"], ipaddr)
device["name"] = f"{device['id']} {ipaddr}"
device[ATTR_MODE] = None
device[CONF_PROTOCOL] = None
device[CONF_CUSTOM_EFFECT] = None
+1 -1
View File
@@ -101,7 +101,7 @@ class FoobotSensor(Entity):
"""Initialize the sensor."""
self._uuid = device["uuid"]
self.foobot_data = data
self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0])
self._name = f"Foobot {device['name']} {SENSOR_TYPES[sensor_type][0]}"
self.type = sensor_type
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
+1 -6
View File
@@ -190,12 +190,7 @@ class HassFoscamCamera(Camera):
async def stream_source(self):
"""Return the stream source."""
if self._rtsp_port:
return "rtsp://{}:{}@{}:{}/videoMain".format(
self._username,
self._password,
self._foscam_session.host,
self._rtsp_port,
)
return f"rtsp://{self._username}:{self._password}@{self._foscam_session.host}:{self._rtsp_port}/videoMain"
return None
@property
@@ -52,12 +52,7 @@ def setup(hass, config):
def checkin_user(call):
"""Check a user in on Swarm."""
url = (
"https://api.foursquare.com/v2/checkins/add"
"?oauth_token={}"
"&v=20160802"
"&m=swarm"
).format(config[CONF_ACCESS_TOKEN])
url = f"https://api.foursquare.com/v2/checkins/add?oauth_token={config[CONF_ACCESS_TOKEN]}&v=20160802&m=swarm"
response = requests.post(url, data=call.data, timeout=10)
if response.status_code not in (200, 201):
+3 -3
View File
@@ -78,9 +78,9 @@ class FritzboxSwitch(SwitchDevice):
attrs[ATTR_STATE_LOCKED] = self._device.lock
if self._device.has_powermeter:
attrs[ATTR_TOTAL_CONSUMPTION] = "{:.3f}".format(
(self._device.energy or 0.0) / 1000
)
attrs[
ATTR_TOTAL_CONSUMPTION
] = f"{((self._device.energy or 0.0) / 1000):.3f}"
attrs[ATTR_TOTAL_CONSUMPTION_UNIT] = ATTR_TOTAL_CONSUMPTION_UNIT_VALUE
if self._device.has_temperature_sensor:
attrs[ATTR_TEMPERATURE] = str(
+2 -8
View File
@@ -90,11 +90,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
device = condition[CONF_DEVICE]
sensor_type = condition[CONF_SENSOR_TYPE]
scope = condition[CONF_SCOPE]
name = "Fronius {} {} {}".format(
condition[CONF_SENSOR_TYPE].replace("_", " ").capitalize(),
device if scope == SCOPE_DEVICE else SCOPE_SYSTEM,
config[CONF_RESOURCE],
)
name = f"Fronius {condition[CONF_SENSOR_TYPE].replace('_', ' ').capitalize()} {device if scope == SCOPE_DEVICE else SCOPE_SYSTEM} {config[CONF_RESOURCE]}"
if sensor_type == TYPE_INVERTER:
if scope == SCOPE_SYSTEM:
adapter_cls = FroniusInverterSystem
@@ -258,9 +254,7 @@ class FroniusTemplateSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(
self._name.replace("_", " ").capitalize(), self.parent.name
)
return f"{self._name.replace('_', ' ').capitalize()} {self.parent.name}"
@property
def state(self):
@@ -50,8 +50,8 @@ MANIFEST_JSON = {
"display": "standalone",
"icons": [
{
"src": "/static/icons/favicon-{size}x{size}.png".format(size=size),
"sizes": "{size}x{size}".format(size=size),
"src": f"/static/icons/favicon-{size}x{size}.png",
"sizes": f"{size}x{size}",
"type": "image/png",
"purpose": "maskable any",
}
+1 -3
View File
@@ -9,7 +9,6 @@ from homeassistant.components import websocket_api
DATA_STORAGE = "frontend_storage"
STORAGE_VERSION_USER_DATA = 1
STORAGE_KEY_USER_DATA = "frontend.user_data_{}"
async def async_setup_frontend_storage(hass):
@@ -31,8 +30,7 @@ def with_store(orig_func):
if store is None:
store = stores[user_id] = hass.helpers.storage.Store(
STORAGE_VERSION_USER_DATA,
STORAGE_KEY_USER_DATA.format(connection.user.id),
STORAGE_VERSION_USER_DATA, f"frontend.user_data_{connection.user.id}"
)
if user_id not in data:
@@ -55,7 +55,6 @@ SUPPORT_FRONTIER_SILICON = (
DEFAULT_PORT = 80
DEFAULT_PASSWORD = "1234"
DEVICE_URL = "http://{0}:{1}/device"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
@@ -83,7 +82,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
try:
async_add_entities(
[AFSAPIDevice(DEVICE_URL.format(host, port), password, name)], True
[AFSAPIDevice(f"http://{host}:{port}/device", password, name)], True
)
_LOGGER.debug("FSAPI device %s:%s -> %s", host, port, password)
return True
+1 -3
View File
@@ -251,9 +251,7 @@ class GaradgetCover(CoverDevice):
def _get_variable(self, var):
"""Get latest status."""
url = "{}/v1/devices/{}/{}?access_token={}".format(
self.particle_url, self.device_id, var, self.access_token
)
url = f"{self.particle_url}/v1/devices/{self.device_id}/{var}?access_token={self.access_token}"
ret = requests.get(url, timeout=10)
result = {}
for pairs in ret.json()["result"].split("|"):
+4 -8
View File
@@ -28,10 +28,6 @@ from .const import (
DOMAIN,
FEED,
PLATFORMS,
SIGNAL_DELETE_ENTITY,
SIGNAL_NEW_GEOLOCATION,
SIGNAL_STATUS,
SIGNAL_UPDATE_ENTITY,
VALID_CATEGORIES,
)
@@ -181,7 +177,7 @@ class GdacsFeedEntityManager:
@callback
def async_event_new_entity(self):
"""Return manager specific event to signal new entity."""
return SIGNAL_NEW_GEOLOCATION.format(self._config_entry_id)
return f"gdacs_new_geolocation_{self._config_entry_id}"
def get_entry(self, external_id):
"""Get feed entry by external id."""
@@ -199,14 +195,14 @@ class GdacsFeedEntityManager:
async def _update_entity(self, external_id):
"""Update entity."""
async_dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
async_dispatcher_send(self._hass, f"gdacs_update_{external_id}")
async def _remove_entity(self, external_id):
"""Remove entity."""
async_dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
async_dispatcher_send(self._hass, f"gdacs_delete_{external_id}")
async def _status_update(self, status_info):
"""Propagate status update."""
_LOGGER.debug("Status update received: %s", status_info)
self._status_info = status_info
async_dispatcher_send(self._hass, SIGNAL_STATUS.format(self._config_entry_id))
async_dispatcher_send(self._hass, f"gdacs_status_{self._config_entry_id}")
-6
View File
@@ -15,11 +15,5 @@ DEFAULT_ICON = "mdi:alert"
DEFAULT_RADIUS = 500.0
DEFAULT_SCAN_INTERVAL = timedelta(minutes=5)
SIGNAL_DELETE_ENTITY = "gdacs_delete_{}"
SIGNAL_UPDATE_ENTITY = "gdacs_update_{}"
SIGNAL_STATUS = "gdacs_status_{}"
SIGNAL_NEW_GEOLOCATION = "gdacs_new_geolocation_{}"
# Fetch valid categories from integration library.
VALID_CATEGORIES = list(EVENT_TYPE_MAP.values())
+3 -13
View File
@@ -13,13 +13,7 @@ from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util.unit_system import IMPERIAL_SYSTEM
from .const import (
DEFAULT_ICON,
DOMAIN,
FEED,
SIGNAL_DELETE_ENTITY,
SIGNAL_UPDATE_ENTITY,
)
from .const import DEFAULT_ICON, DOMAIN, FEED
_LOGGER = logging.getLogger(__name__)
@@ -102,14 +96,10 @@ class GdacsEvent(GeolocationEvent):
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self._remove_signal_delete = async_dispatcher_connect(
self.hass,
SIGNAL_DELETE_ENTITY.format(self._external_id),
self._delete_callback,
self.hass, f"gdacs_delete_{self._external_id}", self._delete_callback
)
self._remove_signal_update = async_dispatcher_connect(
self.hass,
SIGNAL_UPDATE_ENTITY.format(self._external_id),
self._update_callback,
self.hass, f"gdacs_update_{self._external_id}", self._update_callback
)
async def async_will_remove_from_hass(self) -> None:
+2 -2
View File
@@ -7,7 +7,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from homeassistant.util import dt
from .const import DEFAULT_ICON, DOMAIN, FEED, SIGNAL_STATUS
from .const import DEFAULT_ICON, DOMAIN, FEED
_LOGGER = logging.getLogger(__name__)
@@ -55,7 +55,7 @@ class GdacsSensor(Entity):
"""Call when entity is added to hass."""
self._remove_signal_status = async_dispatcher_connect(
self.hass,
SIGNAL_STATUS.format(self._config_entry_id),
f"gdacs_status_{self._config_entry_id}",
self._update_status_callback,
)
_LOGGER.debug("Waiting for updates %s", self._config_entry_id)
@@ -29,9 +29,6 @@ DEFAULT_UNIT_OF_MEASUREMENT = "km"
SCAN_INTERVAL = timedelta(minutes=5)
SIGNAL_DELETE_ENTITY = "geo_json_events_delete_{}"
SIGNAL_UPDATE_ENTITY = "geo_json_events_update_{}"
SOURCE = "geo_json_events"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
@@ -108,11 +105,11 @@ class GeoJsonFeedEntityManager:
def _update_entity(self, external_id):
"""Update entity."""
dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
dispatcher_send(self._hass, f"geo_json_events_update_{external_id}")
def _remove_entity(self, external_id):
"""Remove entity."""
dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
dispatcher_send(self._hass, f"geo_json_events_delete_{external_id}")
class GeoJsonLocationEvent(GeolocationEvent):
@@ -133,12 +130,12 @@ class GeoJsonLocationEvent(GeolocationEvent):
"""Call when entity is added to hass."""
self._remove_signal_delete = async_dispatcher_connect(
self.hass,
SIGNAL_DELETE_ENTITY.format(self._external_id),
f"geo_json_events_delete_{self._external_id}",
self._delete_callback,
)
self._remove_signal_update = async_dispatcher_connect(
self.hass,
SIGNAL_UPDATE_ENTITY.format(self._external_id),
f"geo_json_events_update_{self._external_id}",
self._update_callback,
)
@@ -118,9 +118,7 @@ class GeoRssServiceSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(
self._service_name, "Any" if self._category is None else self._category
)
return f"{self._service_name} {'Any' if self._category is None else self._category}"
@property
def state(self):
@@ -114,7 +114,7 @@ def _is_mobile_beacon(data, mobile_beacons):
def _device_name(data):
"""Return name of device tracker."""
if ATTR_BEACON_ID in data:
return "{}_{}".format(BEACON_DEV_PREFIX, data["name"])
return f"{BEACON_DEV_PREFIX}_{data['name']}"
return data["device"]
@@ -34,10 +34,6 @@ from .const import (
DOMAIN,
FEED,
PLATFORMS,
SIGNAL_DELETE_ENTITY,
SIGNAL_NEW_GEOLOCATION,
SIGNAL_STATUS,
SIGNAL_UPDATE_ENTITY,
)
_LOGGER = logging.getLogger(__name__)
@@ -200,7 +196,7 @@ class GeonetnzQuakesFeedEntityManager:
@callback
def async_event_new_entity(self):
"""Return manager specific event to signal new entity."""
return SIGNAL_NEW_GEOLOCATION.format(self._config_entry_id)
return f"geonetnz_quakes_new_geolocation_{self._config_entry_id}"
def get_entry(self, external_id):
"""Get feed entry by external id."""
@@ -222,14 +218,16 @@ class GeonetnzQuakesFeedEntityManager:
async def _update_entity(self, external_id):
"""Update entity."""
async_dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
async_dispatcher_send(self._hass, f"geonetnz_quakes_update_{external_id}")
async def _remove_entity(self, external_id):
"""Remove entity."""
async_dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
async_dispatcher_send(self._hass, f"geonetnz_quakes_delete_{external_id}")
async def _status_update(self, status_info):
"""Propagate status update."""
_LOGGER.debug("Status update received: %s", status_info)
self._status_info = status_info
async_dispatcher_send(self._hass, SIGNAL_STATUS.format(self._config_entry_id))
async_dispatcher_send(
self._hass, f"geonetnz_quakes_status_{self._config_entry_id}"
)
@@ -15,9 +15,3 @@ DEFAULT_MINIMUM_MAGNITUDE = 0.0
DEFAULT_MMI = 3
DEFAULT_RADIUS = 50.0
DEFAULT_SCAN_INTERVAL = timedelta(minutes=5)
SIGNAL_DELETE_ENTITY = "geonetnz_quakes_delete_{}"
SIGNAL_UPDATE_ENTITY = "geonetnz_quakes_update_{}"
SIGNAL_STATUS = "geonetnz_quakes_status_{}"
SIGNAL_NEW_GEOLOCATION = "geonetnz_quakes_new_geolocation_{}"
@@ -14,7 +14,7 @@ from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util.unit_system import IMPERIAL_SYSTEM
from .const import DOMAIN, FEED, SIGNAL_DELETE_ENTITY, SIGNAL_UPDATE_ENTITY
from .const import DOMAIN, FEED
_LOGGER = logging.getLogger(__name__)
@@ -75,12 +75,12 @@ class GeonetnzQuakesEvent(GeolocationEvent):
"""Call when entity is added to hass."""
self._remove_signal_delete = async_dispatcher_connect(
self.hass,
SIGNAL_DELETE_ENTITY.format(self._external_id),
f"geonetnz_quakes_delete_{self._external_id}",
self._delete_callback,
)
self._remove_signal_update = async_dispatcher_connect(
self.hass,
SIGNAL_UPDATE_ENTITY.format(self._external_id),
f"geonetnz_quakes_update_{self._external_id}",
self._update_callback,
)
@@ -7,7 +7,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from homeassistant.util import dt
from .const import DOMAIN, FEED, SIGNAL_STATUS
from .const import DOMAIN, FEED
_LOGGER = logging.getLogger(__name__)
@@ -53,7 +53,7 @@ class GeonetnzQuakesSensor(Entity):
"""Call when entity is added to hass."""
self._remove_signal_status = async_dispatcher_connect(
self.hass,
SIGNAL_STATUS.format(self._config_entry_id),
f"geonetnz_quakes_status_{self._config_entry_id}",
self._update_status_callback,
)
_LOGGER.debug("Waiting for updates %s", self._config_entry_id)
@@ -24,14 +24,7 @@ from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util.unit_system import METRIC_SYSTEM
from .config_flow import configured_instances
from .const import (
DEFAULT_RADIUS,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
FEED,
SIGNAL_NEW_SENSOR,
SIGNAL_UPDATE_ENTITY,
)
from .const import DEFAULT_RADIUS, DEFAULT_SCAN_INTERVAL, DOMAIN, FEED
_LOGGER = logging.getLogger(__name__)
@@ -173,7 +166,7 @@ class GeonetnzVolcanoFeedEntityManager:
@callback
def async_event_new_entity(self):
"""Return manager specific event to signal new entity."""
return SIGNAL_NEW_SENSOR.format(self._config_entry_id)
return f"geonetnz_volcano_new_sensor_{self._config_entry_id}"
def get_entry(self, external_id):
"""Get feed entry by external id."""
@@ -199,7 +192,7 @@ class GeonetnzVolcanoFeedEntityManager:
async def _update_entity(self, external_id):
"""Update entity."""
async_dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
async_dispatcher_send(self._hass, f"geonetnz_volcano_update_{external_id}")
async def _remove_entity(self, external_id):
"""Ignore removing entity."""
@@ -14,6 +14,3 @@ ATTR_HAZARDS = "hazards"
DEFAULT_ICON = "mdi:image-filter-hdr"
DEFAULT_RADIUS = 50.0
DEFAULT_SCAN_INTERVAL = timedelta(minutes=5)
SIGNAL_NEW_SENSOR = "geonetnz_volcano_new_sensor_{}"
SIGNAL_UPDATE_ENTITY = "geonetnz_volcano_update_{}"
@@ -23,7 +23,6 @@ from .const import (
DEFAULT_ICON,
DOMAIN,
FEED,
SIGNAL_UPDATE_ENTITY,
)
_LOGGER = logging.getLogger(__name__)
@@ -79,7 +78,7 @@ class GeonetnzVolcanoSensor(Entity):
"""Call when entity is added to hass."""
self._remove_signal_update = async_dispatcher_connect(
self.hass,
SIGNAL_UPDATE_ENTITY.format(self._external_id),
f"geonetnz_volcano_update_{self._external_id}",
self._update_callback,
)
+1 -3
View File
@@ -51,9 +51,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
except (TypeError, KeyError, NameError, ValueError) as ex:
_LOGGER.error("%s", ex)
hass.components.persistent_notification.create(
"Error: {}<br />"
"You will need to restart hass after fixing."
"".format(ex),
(f"Error: {ex}<br />You will need to restart hass after fixing."),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
+9 -7
View File
@@ -144,17 +144,17 @@ def do_authentication(hass, hass_config, config):
dev_flow = oauth.step1_get_device_and_user_codes()
except OAuth2DeviceCodeError as err:
hass.components.persistent_notification.create(
"Error: {}<br />You will need to restart hass after fixing." "".format(err),
f"Error: {err}<br />You will need to restart hass after fixing." "",
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return False
hass.components.persistent_notification.create(
"In order to authorize Home-Assistant to view your calendars "
'you must visit: <a href="{}" target="_blank">{}</a> and enter '
"code: {}".format(
dev_flow.verification_url, dev_flow.verification_url, dev_flow.user_code
(
f"In order to authorize Home-Assistant to view your calendars "
f'you must visit: <a href="{dev_flow.verification_url}" target="_blank">{dev_flow.verification_url}</a> and enter '
f"code: {dev_flow.user_code}"
),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
@@ -182,8 +182,10 @@ def do_authentication(hass, hass_config, config):
do_setup(hass, hass_config, config)
listener()
hass.components.persistent_notification.create(
"We are all setup now. Check {} for calendars that have "
"been found".format(YAML_DEVICES),
(
f"We are all setup now. Check {YAML_DEVICES} for calendars that have "
f"been found"
),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
@@ -53,7 +53,7 @@ def _get_homegraph_jwt(time, iss, key):
async def _get_homegraph_token(hass, jwt_signed):
headers = {
"Authorization": "Bearer {}".format(jwt_signed),
"Authorization": f"Bearer {jwt_signed}",
"Content-Type": "application/x-www-form-urlencoded",
}
data = {
@@ -185,7 +185,7 @@ class GoogleConfig(AbstractConfig):
async def _call():
headers = {
"Authorization": "Bearer {}".format(self._access_token),
"Authorization": f"Bearer {self._access_token}",
"X-GFE-SSL": "yes",
}
async with session.post(url, headers=headers, json=data) as res:
@@ -392,9 +392,7 @@ class ColorSettingTrait(_Trait):
if temp < min_temp or temp > max_temp:
raise SmartHomeError(
ERR_VALUE_OUT_OF_RANGE,
"Temperature should be between {} and {}".format(
min_temp, max_temp
),
f"Temperature should be between {min_temp} and {max_temp}",
)
await self.hass.services.async_call(
@@ -407,7 +405,7 @@ class ColorSettingTrait(_Trait):
elif "spectrumRGB" in params["color"]:
# Convert integer to hex format and left pad with 0's till length 6
hex_value = "{0:06x}".format(params["color"]["spectrumRGB"])
hex_value = f"{params['color']['spectrumRGB']:06x}"
color = color_util.color_RGB_to_hs(
*color_util.rgb_hex_to_rgb_list(hex_value)
)
@@ -746,9 +744,7 @@ class TemperatureSettingTrait(_Trait):
if temp < min_temp or temp > max_temp:
raise SmartHomeError(
ERR_VALUE_OUT_OF_RANGE,
"Temperature should be between {} and {}".format(
min_temp, max_temp
),
f"Temperature should be between {min_temp} and {max_temp}",
)
await self.hass.services.async_call(
@@ -769,8 +765,10 @@ class TemperatureSettingTrait(_Trait):
if temp_high < min_temp or temp_high > max_temp:
raise SmartHomeError(
ERR_VALUE_OUT_OF_RANGE,
"Upper bound for temperature range should be between "
"{} and {}".format(min_temp, max_temp),
(
f"Upper bound for temperature range should be between "
f"{min_temp} and {max_temp}"
),
)
temp_low = temp_util.convert(
@@ -782,8 +780,10 @@ class TemperatureSettingTrait(_Trait):
if temp_low < min_temp or temp_low > max_temp:
raise SmartHomeError(
ERR_VALUE_OUT_OF_RANGE,
"Lower bound for temperature range should be between "
"{} and {}".format(min_temp, max_temp),
(
f"Lower bound for temperature range should be between "
f"{min_temp} and {max_temp}"
),
)
supported = self.state.attributes.get(ATTR_SUPPORTED_FEATURES)
@@ -18,8 +18,6 @@ INTERVAL = timedelta(minutes=5)
DEFAULT_TIMEOUT = 10
UPDATE_URL = "https://{}:{}@domains.google.com/nic/update"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
@@ -62,7 +60,7 @@ async def async_setup(hass, config):
async def _update_google_domains(hass, session, domain, user, password, timeout):
"""Update Google Domains."""
url = UPDATE_URL.format(user, password)
url = f"https://{user}:{password}@domains.google.com/nic/update"
params = {"hostname": domain}
@@ -55,9 +55,7 @@ class GoogleMapsScanner:
self.scan_interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=60)
self._prev_seen = {}
credfile = "{}.{}".format(
hass.config.path(CREDENTIALS_FILE), slugify(self.username)
)
credfile = f"{hass.config.path(CREDENTIALS_FILE)}.{slugify(self.username)}"
try:
self.service = Service(credfile, self.username)
self._update_info()
@@ -75,7 +73,7 @@ class GoogleMapsScanner:
def _update_info(self, now=None):
for person in self.service.get_all_people():
try:
dev_id = "google_maps_{0}".format(slugify(person.id))
dev_id = f"google_maps_{slugify(person.id)}"
except TypeError:
_LOGGER.warning("No location(s) shared with this account")
return
@@ -163,7 +163,7 @@ def setup_platform(hass, config, add_entities_callback, discovery_info=None):
options[CONF_MODE] = travel_mode
titled_mode = options.get(CONF_MODE).title()
formatted_name = "{} - {}".format(DEFAULT_NAME, titled_mode)
formatted_name = f"{DEFAULT_NAME} - {titled_mode}"
name = config.get(CONF_NAME, formatted_name)
api_key = config.get(CONF_API_KEY)
origin = config.get(CONF_ORIGIN)
@@ -107,11 +107,7 @@ class GEMSensor(Entity):
@property
def unique_id(self):
"""Return a unique ID for this sensor."""
return "{serial}-{sensor_type}-{number}".format(
serial=self._monitor_serial_number,
sensor_type=self._sensor_type,
number=self._number,
)
return f"{self._monitor_serial_number}-{self._sensor_type }-{self._number}"
@property
def name(self):
@@ -249,9 +245,7 @@ class PulseCounter(GEMSensor):
@property
def unit_of_measurement(self):
"""Return the unit of measurement for this pulse counter."""
return "{counted_quantity}/{time_unit}".format(
counted_quantity=self._counted_quantity, time_unit=self._time_unit
)
return f"{self._counted_quantity}/{self._time_unit}"
@property
def device_state_attributes(self):
+5 -5
View File
@@ -74,7 +74,7 @@ GROUP_SCHEMA = vol.All(
CONF_ICON: cv.icon,
CONF_ALL: cv.boolean,
}
),
)
)
CONFIG_SCHEMA = vol.Schema(
@@ -231,7 +231,7 @@ async def async_setup(hass, config):
async def groups_service_handler(service):
"""Handle dynamic group service functions."""
object_id = service.data[ATTR_OBJECT_ID]
entity_id = ENTITY_ID_FORMAT.format(object_id)
entity_id = f"{DOMAIN}.{object_id}"
group = component.get_entity(entity_id)
# new group
@@ -311,7 +311,7 @@ async def async_setup(hass, config):
vol.Exclusive(ATTR_ENTITIES, "entities"): cv.entity_ids,
vol.Exclusive(ATTR_ADD_ENTITIES, "entities"): cv.entity_ids,
}
),
)
),
)
@@ -336,7 +336,7 @@ async def _async_process_config(hass, config, component):
# Don't create tasks and await them all. The order is important as
# groups get a number based on creation order.
await Group.async_create_group(
hass, name, entity_ids, icon=icon, object_id=object_id, mode=mode,
hass, name, entity_ids, icon=icon, object_id=object_id, mode=mode
)
@@ -388,7 +388,7 @@ class Group(Entity):
"""Initialize a group."""
return asyncio.run_coroutine_threadsafe(
Group.async_create_group(
hass, name, entity_ids, user_defined, icon, object_id, mode,
hass, name, entity_ids, user_defined, icon, object_id, mode
),
hass.loop,
).result()
+27 -32
View File
@@ -143,7 +143,7 @@ def get_next_departure(
tomorrow_where = f"OR calendar.{tomorrow_name} = 1"
tomorrow_order = f"calendar.{tomorrow_name} DESC,"
sql_query = """
sql_query = f"""
SELECT trip.trip_id, trip.route_id,
time(origin_stop_time.arrival_time) AS origin_arrival_time,
time(origin_stop_time.departure_time) AS origin_depart_time,
@@ -162,8 +162,8 @@ def get_next_departure(
destination_stop_time.stop_headsign AS dest_stop_headsign,
destination_stop_time.stop_sequence AS dest_stop_sequence,
destination_stop_time.timepoint AS dest_stop_timepoint,
calendar.{yesterday_name} AS yesterday,
calendar.{today_name} AS today,
calendar.{yesterday.strftime("%A").lower()} AS yesterday,
calendar.{now.strftime("%A").lower()} AS today,
{tomorrow_select}
calendar.start_date AS start_date,
calendar.end_date AS end_date
@@ -178,8 +178,8 @@ def get_next_departure(
ON trip.trip_id = destination_stop_time.trip_id
INNER JOIN stops end_station
ON destination_stop_time.stop_id = end_station.stop_id
WHERE (calendar.{yesterday_name} = 1
OR calendar.{today_name} = 1
WHERE (calendar.{yesterday.strftime("%A").lower()} = 1
OR calendar.{now.strftime("%A").lower()} = 1
{tomorrow_where}
)
AND start_station.stop_id = :origin_station_id
@@ -187,18 +187,12 @@ def get_next_departure(
AND origin_stop_sequence < dest_stop_sequence
AND calendar.start_date <= :today
AND calendar.end_date >= :today
ORDER BY calendar.{yesterday_name} DESC,
calendar.{today_name} DESC,
ORDER BY calendar.{yesterday.strftime("%A").lower()} DESC,
calendar.{now.strftime("%A").lower()} DESC,
{tomorrow_order}
origin_stop_time.departure_time
LIMIT :limit
""".format(
yesterday_name=yesterday.strftime("%A").lower(),
today_name=now.strftime("%A").lower(),
tomorrow_select=tomorrow_select,
tomorrow_where=tomorrow_where,
tomorrow_order=tomorrow_order,
)
"""
result = schedule.engine.execute(
text(sql_query),
origin_station_id=start_station_id,
@@ -220,7 +214,7 @@ def get_next_departure(
if yesterday_start is None:
yesterday_start = row["origin_depart_date"]
if yesterday_start != row["origin_depart_date"]:
idx = "{} {}".format(now_date, row["origin_depart_time"])
idx = f"{now_date} {row['origin_depart_time']}"
timetable[idx] = {**row, **extras}
yesterday_last = idx
@@ -233,7 +227,7 @@ def get_next_departure(
idx_prefix = now_date
else:
idx_prefix = tomorrow_date
idx = "{} {}".format(idx_prefix, row["origin_depart_time"])
idx = f"{idx_prefix} {row['origin_depart_time']}"
timetable[idx] = {**row, **extras}
today_last = idx
@@ -247,7 +241,7 @@ def get_next_departure(
tomorrow_start = row["origin_depart_date"]
extras["first"] = True
if tomorrow_start == row["origin_depart_date"]:
idx = "{} {}".format(tomorrow_date, row["origin_depart_time"])
idx = f"{tomorrow_date} {row['origin_depart_time']}"
timetable[idx] = {**row, **extras}
# Flag last departures.
@@ -273,24 +267,27 @@ def get_next_departure(
origin_arrival = now
if item["origin_arrival_time"] > item["origin_depart_time"]:
origin_arrival -= datetime.timedelta(days=1)
origin_arrival_time = "{} {}".format(
origin_arrival.strftime(dt_util.DATE_STR_FORMAT), item["origin_arrival_time"]
origin_arrival_time = (
f"{origin_arrival.strftime(dt_util.DATE_STR_FORMAT)} "
f"{item['origin_arrival_time']}"
)
origin_depart_time = "{} {}".format(now_date, item["origin_depart_time"])
origin_depart_time = f"{now_date} {item['origin_depart_time']}"
dest_arrival = now
if item["dest_arrival_time"] < item["origin_depart_time"]:
dest_arrival += datetime.timedelta(days=1)
dest_arrival_time = "{} {}".format(
dest_arrival.strftime(dt_util.DATE_STR_FORMAT), item["dest_arrival_time"]
dest_arrival_time = (
f"{dest_arrival.strftime(dt_util.DATE_STR_FORMAT)} "
f"{item['dest_arrival_time']}"
)
dest_depart = dest_arrival
if item["dest_depart_time"] < item["dest_arrival_time"]:
dest_depart += datetime.timedelta(days=1)
dest_depart_time = "{} {}".format(
dest_depart.strftime(dt_util.DATE_STR_FORMAT), item["dest_depart_time"]
dest_depart_time = (
f"{dest_depart.strftime(dt_util.DATE_STR_FORMAT)} "
f"{item['dest_depart_time']}"
)
depart_time = dt_util.parse_datetime(origin_depart_time)
@@ -511,15 +508,13 @@ class GTFSDepartureSensor(Entity):
else:
self._icon = ICON
name = "{agency} {origin} to {destination} next departure"
if not self._departure:
name = "{default}"
self._name = self._custom_name or name.format(
agency=getattr(self._agency, "agency_name", DEFAULT_NAME),
default=DEFAULT_NAME,
origin=self.origin,
destination=self.destination,
name = (
f"{getattr(self._agency, 'agency_name', DEFAULT_NAME)} "
f"{self.origin} to {self.destination} next departure"
)
if not self._departure:
name = f"{DEFAULT_NAME}"
self._name = self._custom_name or name
def update_attributes(self) -> None:
"""Update state attributes."""