Use literal string interpolation in integrations K-M (f-strings) (#26389)
This commit is contained in:
parent
ef0e9431b6
commit
7203027cbf
51 changed files with 104 additions and 121 deletions
|
@ -66,7 +66,7 @@ class KankunSwitch(SwitchDevice):
|
||||||
self._hass = hass
|
self._hass = hass
|
||||||
self._name = name
|
self._name = name
|
||||||
self._state = False
|
self._state = False
|
||||||
self._url = "http://{}:{}{}".format(host, port, path)
|
self._url = f"http://{host}:{port}{path}"
|
||||||
if user is not None:
|
if user is not None:
|
||||||
self._auth = (user, passwd)
|
self._auth = (user, passwd)
|
||||||
else:
|
else:
|
||||||
|
@ -78,7 +78,7 @@ class KankunSwitch(SwitchDevice):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
req = requests.get(
|
req = requests.get(
|
||||||
"{}?set={}".format(self._url, newstate), auth=self._auth, timeout=5
|
f"{self._url}?set={newstate}", auth=self._auth, timeout=5
|
||||||
)
|
)
|
||||||
return req.json()["ok"]
|
return req.json()["ok"]
|
||||||
except requests.RequestException:
|
except requests.RequestException:
|
||||||
|
@ -89,9 +89,7 @@ class KankunSwitch(SwitchDevice):
|
||||||
_LOGGER.info("Querying state from: %s", self._url)
|
_LOGGER.info("Querying state from: %s", self._url)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
req = requests.get(
|
req = requests.get(f"{self._url}?get=state", auth=self._auth, timeout=5)
|
||||||
"{}?get=state".format(self._url), auth=self._auth, timeout=5
|
|
||||||
)
|
|
||||||
return req.json()["state"] == "on"
|
return req.json()["state"] == "on"
|
||||||
except requests.RequestException:
|
except requests.RequestException:
|
||||||
_LOGGER.error("State query failed")
|
_LOGGER.error("State query failed")
|
||||||
|
|
|
@ -32,7 +32,7 @@ CONF_REMOTES = "remotes"
|
||||||
CONF_SENSOR = "sensor"
|
CONF_SENSOR = "sensor"
|
||||||
CONF_REMOTE = "remote"
|
CONF_REMOTE = "remote"
|
||||||
|
|
||||||
CODES_YAML = "{}_codes.yaml".format(DOMAIN)
|
CODES_YAML = f"{DOMAIN}_codes.yaml"
|
||||||
|
|
||||||
CODE_SCHEMA = vol.Schema(
|
CODE_SCHEMA = vol.Schema(
|
||||||
{
|
{
|
||||||
|
|
|
@ -140,7 +140,7 @@ def _check_deprecated_turn_off(hass, turn_off_action):
|
||||||
method = DEPRECATED_TURN_OFF_ACTIONS[turn_off_action]
|
method = DEPRECATED_TURN_OFF_ACTIONS[turn_off_action]
|
||||||
new_config = OrderedDict(
|
new_config = OrderedDict(
|
||||||
[
|
[
|
||||||
("service", "{}.{}".format(DOMAIN, SERVICE_CALL_METHOD)),
|
("service", f"{DOMAIN}.{SERVICE_CALL_METHOD}"),
|
||||||
(
|
(
|
||||||
"data_template",
|
"data_template",
|
||||||
OrderedDict([("entity_id", "{{ entity_id }}"), ("method", method)]),
|
OrderedDict([("entity_id", "{{ entity_id }}"), ("method", method)]),
|
||||||
|
@ -281,18 +281,18 @@ class KodiDevice(MediaPlayerDevice):
|
||||||
|
|
||||||
if username is not None:
|
if username is not None:
|
||||||
kwargs["auth"] = aiohttp.BasicAuth(username, password)
|
kwargs["auth"] = aiohttp.BasicAuth(username, password)
|
||||||
image_auth_string = "{}:{}@".format(username, password)
|
image_auth_string = f"{username}:{password}@"
|
||||||
else:
|
else:
|
||||||
image_auth_string = ""
|
image_auth_string = ""
|
||||||
|
|
||||||
http_protocol = "https" if encryption else "http"
|
http_protocol = "https" if encryption else "http"
|
||||||
ws_protocol = "wss" if encryption else "ws"
|
ws_protocol = "wss" if encryption else "ws"
|
||||||
|
|
||||||
self._http_url = "{}://{}:{}/jsonrpc".format(http_protocol, host, port)
|
self._http_url = f"{http_protocol}://{host}:{port}/jsonrpc"
|
||||||
self._image_url = "{}://{}{}:{}/image".format(
|
self._image_url = "{}://{}{}:{}/image".format(
|
||||||
http_protocol, image_auth_string, host, port
|
http_protocol, image_auth_string, host, port
|
||||||
)
|
)
|
||||||
self._ws_url = "{}://{}:{}/jsonrpc".format(ws_protocol, host, tcp_port)
|
self._ws_url = f"{ws_protocol}://{host}:{tcp_port}/jsonrpc"
|
||||||
|
|
||||||
self._http_server = jsonrpc_async.Server(self._http_url, **kwargs)
|
self._http_server = jsonrpc_async.Server(self._http_url, **kwargs)
|
||||||
if websocket:
|
if websocket:
|
||||||
|
@ -326,14 +326,14 @@ class KodiDevice(MediaPlayerDevice):
|
||||||
turn_on_action = script.Script(
|
turn_on_action = script.Script(
|
||||||
self.hass,
|
self.hass,
|
||||||
turn_on_action,
|
turn_on_action,
|
||||||
"{} turn ON script".format(self.name),
|
f"{self.name} turn ON script",
|
||||||
self.async_update_ha_state(True),
|
self.async_update_ha_state(True),
|
||||||
)
|
)
|
||||||
if turn_off_action is not None:
|
if turn_off_action is not None:
|
||||||
turn_off_action = script.Script(
|
turn_off_action = script.Script(
|
||||||
self.hass,
|
self.hass,
|
||||||
_check_deprecated_turn_off(hass, turn_off_action),
|
_check_deprecated_turn_off(hass, turn_off_action),
|
||||||
"{} turn OFF script".format(self.name),
|
f"{self.name} turn OFF script",
|
||||||
)
|
)
|
||||||
self._turn_on_action = turn_on_action
|
self._turn_on_action = turn_on_action
|
||||||
self._turn_off_action = turn_off_action
|
self._turn_off_action = turn_off_action
|
||||||
|
|
|
@ -62,7 +62,7 @@ async def async_get_service(hass, config, discovery_info=None):
|
||||||
)
|
)
|
||||||
|
|
||||||
http_protocol = "https" if encryption else "http"
|
http_protocol = "https" if encryption else "http"
|
||||||
url = "{}://{}:{}/jsonrpc".format(http_protocol, host, port)
|
url = f"{http_protocol}://{host}:{port}/jsonrpc"
|
||||||
|
|
||||||
if username is not None:
|
if username is not None:
|
||||||
auth = aiohttp.BasicAuth(username, password)
|
auth = aiohttp.BasicAuth(username, password)
|
||||||
|
|
|
@ -538,7 +538,7 @@ class KonnectedView(HomeAssistantView):
|
||||||
)
|
)
|
||||||
|
|
||||||
auth = request.headers.get(AUTHORIZATION, None)
|
auth = request.headers.get(AUTHORIZATION, None)
|
||||||
if not hmac.compare_digest("Bearer {}".format(self.auth_token), auth):
|
if not hmac.compare_digest(f"Bearer {self.auth_token}", auth):
|
||||||
return self.json_message("unauthorized", status_code=HTTP_UNAUTHORIZED)
|
return self.json_message("unauthorized", status_code=HTTP_UNAUTHORIZED)
|
||||||
pin_num = int(pin_num)
|
pin_num = int(pin_num)
|
||||||
device = data[CONF_DEVICES].get(device_id)
|
device = data[CONF_DEVICES].get(device_id)
|
||||||
|
|
|
@ -92,7 +92,7 @@ class KWBSensor(Entity):
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Return the name."""
|
"""Return the name."""
|
||||||
return "{} {}".format(self._client_name, self._name)
|
return f"{self._client_name} {self._name}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def available(self) -> bool:
|
def available(self) -> bool:
|
||||||
|
|
|
@ -72,7 +72,7 @@ class LastfmSensor(Entity):
|
||||||
@property
|
@property
|
||||||
def entity_id(self):
|
def entity_id(self):
|
||||||
"""Return the entity ID."""
|
"""Return the entity ID."""
|
||||||
return "sensor.lastfm_{}".format(self._name)
|
return f"sensor.lastfm_{self._name}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self):
|
def state(self):
|
||||||
|
@ -84,7 +84,7 @@ class LastfmSensor(Entity):
|
||||||
self._cover = self._user.get_image()
|
self._cover = self._user.get_image()
|
||||||
self._playcount = self._user.get_playcount()
|
self._playcount = self._user.get_playcount()
|
||||||
last = self._user.get_recent_tracks(limit=2)[0]
|
last = self._user.get_recent_tracks(limit=2)[0]
|
||||||
self._lastplayed = "{} - {}".format(last.track.artist, last.track.title)
|
self._lastplayed = f"{last.track.artist} - {last.track.title}"
|
||||||
top = self._user.get_top_tracks(limit=1)[0]
|
top = self._user.get_top_tracks(limit=1)[0]
|
||||||
toptitle = re.search("', '(.+?)',", str(top))
|
toptitle = re.search("', '(.+?)',", str(top))
|
||||||
topartist = re.search("'(.+?)',", str(top))
|
topartist = re.search("'(.+?)',", str(top))
|
||||||
|
@ -93,7 +93,7 @@ class LastfmSensor(Entity):
|
||||||
self._state = "Not Scrobbling"
|
self._state = "Not Scrobbling"
|
||||||
return
|
return
|
||||||
now = self._user.get_now_playing()
|
now = self._user.get_now_playing()
|
||||||
self._state = "{} - {}".format(now.artist, now.title)
|
self._state = f"{now.artist} - {now.title}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def device_state_attributes(self):
|
def device_state_attributes(self):
|
||||||
|
|
|
@ -38,7 +38,7 @@ def has_unique_connection_names(connections):
|
||||||
if suffix == 0:
|
if suffix == 0:
|
||||||
connection[CONF_NAME] = DEFAULT_NAME
|
connection[CONF_NAME] = DEFAULT_NAME
|
||||||
else:
|
else:
|
||||||
connection[CONF_NAME] = "{}{:d}".format(DEFAULT_NAME, suffix)
|
connection[CONF_NAME] = f"{DEFAULT_NAME}{suffix:d}"
|
||||||
|
|
||||||
schema = vol.Schema(vol.Unique())
|
schema = vol.Schema(vol.Unique())
|
||||||
schema([connection.get(CONF_NAME) for connection in connections])
|
schema([connection.get(CONF_NAME) for connection in connections])
|
||||||
|
|
|
@ -99,7 +99,7 @@ class Life360ConfigFlow(config_entries.ConfigFlow):
|
||||||
)
|
)
|
||||||
return self.async_abort(reason="unexpected")
|
return self.async_abort(reason="unexpected")
|
||||||
return self.async_create_entry(
|
return self.async_create_entry(
|
||||||
title="{} (from configuration)".format(username),
|
title=f"{username} (from configuration)",
|
||||||
data={
|
data={
|
||||||
CONF_USERNAME: username,
|
CONF_USERNAME: username,
|
||||||
CONF_PASSWORD: password,
|
CONF_PASSWORD: password,
|
||||||
|
|
|
@ -159,7 +159,7 @@ class Life360Scanner:
|
||||||
_errs = self._errs.get(key, 0)
|
_errs = self._errs.get(key, 0)
|
||||||
if _errs < self._max_errs:
|
if _errs < self._max_errs:
|
||||||
self._errs[key] = _errs = _errs + 1
|
self._errs[key] = _errs = _errs + 1
|
||||||
msg = "{}: {}".format(key, err_msg)
|
msg = f"{key}: {err_msg}"
|
||||||
if _errs >= self._error_threshold:
|
if _errs >= self._error_threshold:
|
||||||
if _errs == self._max_errs:
|
if _errs == self._max_errs:
|
||||||
msg = "Suppressing further errors until OK: " + msg
|
msg = "Suppressing further errors until OK: " + msg
|
||||||
|
@ -233,14 +233,12 @@ class Life360Scanner:
|
||||||
convert(float(gps_accuracy), LENGTH_FEET, LENGTH_METERS)
|
convert(float(gps_accuracy), LENGTH_FEET, LENGTH_METERS)
|
||||||
)
|
)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
self._err(
|
self._err(dev_id, f"GPS data invalid: {lat}, {lon}, {gps_accuracy}")
|
||||||
dev_id, "GPS data invalid: {}, {}, {}".format(lat, lon, gps_accuracy)
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
self._ok(dev_id)
|
self._ok(dev_id)
|
||||||
|
|
||||||
msg = "Updating {}".format(dev_id)
|
msg = f"Updating {dev_id}"
|
||||||
if prev_seen:
|
if prev_seen:
|
||||||
msg += "; Time since last update: {}".format(last_seen - prev_seen)
|
msg += "; Time since last update: {}".format(last_seen - prev_seen)
|
||||||
_LOGGER.debug(msg)
|
_LOGGER.debug(msg)
|
||||||
|
@ -401,7 +399,7 @@ class Life360Scanner:
|
||||||
except (Life360Error, KeyError):
|
except (Life360Error, KeyError):
|
||||||
pass
|
pass
|
||||||
if incl_circle:
|
if incl_circle:
|
||||||
err_key = 'get_circle_members "{}"'.format(circle_name)
|
err_key = f'get_circle_members "{circle_name}"'
|
||||||
try:
|
try:
|
||||||
members = api.get_circle_members(circle_id)
|
members = api.get_circle_members(circle_id)
|
||||||
except Life360Error as exc:
|
except Life360Error as exc:
|
||||||
|
|
|
@ -509,7 +509,7 @@ class LIFXLight(Light):
|
||||||
@property
|
@property
|
||||||
def who(self):
|
def who(self):
|
||||||
"""Return a string identifying the bulb."""
|
"""Return a string identifying the bulb."""
|
||||||
return "%s (%s)" % (self.bulb.ip_addr, self.name)
|
return f"{self.bulb.ip_addr} ({self.name})"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def min_mireds(self):
|
def min_mireds(self):
|
||||||
|
|
|
@ -31,7 +31,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
|
||||||
token = config.get(CONF_TOKEN)
|
token = config.get(CONF_TOKEN)
|
||||||
timeout = config.get(CONF_TIMEOUT)
|
timeout = config.get(CONF_TIMEOUT)
|
||||||
|
|
||||||
headers = {AUTHORIZATION: "Bearer {}".format(token)}
|
headers = {AUTHORIZATION: f"Bearer {token}"}
|
||||||
|
|
||||||
url = LIFX_API_URL.format("scenes")
|
url = LIFX_API_URL.format("scenes")
|
||||||
|
|
||||||
|
|
|
@ -237,16 +237,16 @@ class SetIntentHandler(intent.IntentHandler):
|
||||||
response = intent_obj.create_response()
|
response = intent_obj.create_response()
|
||||||
|
|
||||||
if not speech_parts: # No attributes changed
|
if not speech_parts: # No attributes changed
|
||||||
speech = "Turned on {}".format(state.name)
|
speech = f"Turned on {state.name}"
|
||||||
else:
|
else:
|
||||||
parts = ["Changed {} to".format(state.name)]
|
parts = [f"Changed {state.name} to"]
|
||||||
for index, part in enumerate(speech_parts):
|
for index, part in enumerate(speech_parts):
|
||||||
if index == 0:
|
if index == 0:
|
||||||
parts.append(" {}".format(part))
|
parts.append(f" {part}")
|
||||||
elif index != len(speech_parts) - 1:
|
elif index != len(speech_parts) - 1:
|
||||||
parts.append(", {}".format(part))
|
parts.append(f", {part}")
|
||||||
else:
|
else:
|
||||||
parts.append(" and {}".format(part))
|
parts.append(f" and {part}")
|
||||||
speech = "".join(parts)
|
speech = "".join(parts)
|
||||||
|
|
||||||
response.async_set_speech(speech)
|
response.async_set_speech(speech)
|
||||||
|
|
|
@ -100,7 +100,7 @@ class LinksysSmartWifiDeviceScanner(DeviceScanner):
|
||||||
]
|
]
|
||||||
headers = {"X-JNAP-Action": "http://linksys.com/jnap/core/Transaction"}
|
headers = {"X-JNAP-Action": "http://linksys.com/jnap/core/Transaction"}
|
||||||
return requests.post(
|
return requests.post(
|
||||||
"http://{}/JNAP/".format(self.host),
|
f"http://{self.host}/JNAP/",
|
||||||
timeout=DEFAULT_TIMEOUT,
|
timeout=DEFAULT_TIMEOUT,
|
||||||
headers=headers,
|
headers=headers,
|
||||||
json=data,
|
json=data,
|
||||||
|
|
|
@ -59,7 +59,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||||
if system == "android":
|
if system == "android":
|
||||||
os.listdir(os.path.join(DEFAULT_PATH, "battery"))
|
os.listdir(os.path.join(DEFAULT_PATH, "battery"))
|
||||||
else:
|
else:
|
||||||
os.listdir(os.path.join(DEFAULT_PATH, "BAT{}".format(battery_id)))
|
os.listdir(os.path.join(DEFAULT_PATH, f"BAT{battery_id}"))
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
_LOGGER.error("No battery found")
|
_LOGGER.error("No battery found")
|
||||||
return False
|
return False
|
||||||
|
|
|
@ -178,7 +178,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice):
|
||||||
"""Title of current playing media."""
|
"""Title of current playing media."""
|
||||||
if self._current_channel:
|
if self._current_channel:
|
||||||
if self._current_program:
|
if self._current_program:
|
||||||
return "{}: {}".format(self._current_channel, self._current_program)
|
return f"{self._current_channel}: {self._current_program}"
|
||||||
return self._current_channel
|
return self._current_channel
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|
|
@ -22,7 +22,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
DOMAIN = "locative"
|
DOMAIN = "locative"
|
||||||
TRACKER_UPDATE = "{}_tracker_update".format(DOMAIN)
|
TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
|
||||||
|
|
||||||
|
|
||||||
ATTR_DEVICE_ID = "device"
|
ATTR_DEVICE_ID = "device"
|
||||||
|
@ -76,12 +76,10 @@ async def handle_webhook(hass, webhook_id, request):
|
||||||
|
|
||||||
if direction == "enter":
|
if direction == "enter":
|
||||||
async_dispatcher_send(hass, TRACKER_UPDATE, device, gps_location, location_name)
|
async_dispatcher_send(hass, TRACKER_UPDATE, device, gps_location, location_name)
|
||||||
return web.Response(
|
return web.Response(text=f"Setting location to {location_name}", status=HTTP_OK)
|
||||||
text="Setting location to {}".format(location_name), status=HTTP_OK
|
|
||||||
)
|
|
||||||
|
|
||||||
if direction == "exit":
|
if direction == "exit":
|
||||||
current_state = hass.states.get("{}.{}".format(DEVICE_TRACKER, device))
|
current_state = hass.states.get(f"{DEVICE_TRACKER}.{device}")
|
||||||
|
|
||||||
if current_state is None or current_state.state == location_name:
|
if current_state is None or current_state.state == location_name:
|
||||||
location_name = STATE_NOT_HOME
|
location_name = STATE_NOT_HOME
|
||||||
|
@ -108,7 +106,7 @@ async def handle_webhook(hass, webhook_id, request):
|
||||||
|
|
||||||
_LOGGER.error("Received unidentified message from Locative: %s", direction)
|
_LOGGER.error("Received unidentified message from Locative: %s", direction)
|
||||||
return web.Response(
|
return web.Response(
|
||||||
text="Received unidentified message: {}".format(direction),
|
text=f"Received unidentified message: {direction}",
|
||||||
status=HTTP_UNPROCESSABLE_ENTITY,
|
status=HTTP_UNPROCESSABLE_ENTITY,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -188,7 +188,7 @@ def humanify(hass, events):
|
||||||
- if 2+ sensor updates in GROUP_BY_MINUTES, show last
|
- if 2+ sensor updates in GROUP_BY_MINUTES, show last
|
||||||
- if home assistant stop and start happen in same minute call it restarted
|
- if home assistant stop and start happen in same minute call it restarted
|
||||||
"""
|
"""
|
||||||
domain_prefixes = tuple("{}.".format(dom) for dom in CONTINUOUS_DOMAINS)
|
domain_prefixes = tuple(f"{dom}." for dom in CONTINUOUS_DOMAINS)
|
||||||
|
|
||||||
# Group events in batches of GROUP_BY_MINUTES
|
# Group events in batches of GROUP_BY_MINUTES
|
||||||
for _, g_events in groupby(
|
for _, g_events in groupby(
|
||||||
|
@ -332,7 +332,7 @@ def humanify(hass, events):
|
||||||
entity_id = data.get(ATTR_ENTITY_ID)
|
entity_id = data.get(ATTR_ENTITY_ID)
|
||||||
value = data.get(ATTR_VALUE)
|
value = data.get(ATTR_VALUE)
|
||||||
|
|
||||||
value_msg = " to {}".format(value) if value else ""
|
value_msg = f" to {value}" if value else ""
|
||||||
message = "send command {}{} for {}".format(
|
message = "send command {}{} for {}".format(
|
||||||
data[ATTR_SERVICE], value_msg, data[ATTR_DISPLAY_NAME]
|
data[ATTR_SERVICE], value_msg, data[ATTR_DISPLAY_NAME]
|
||||||
)
|
)
|
||||||
|
@ -519,7 +519,7 @@ def _keep_event(event, entities_filter):
|
||||||
domain = DOMAIN_HOMEKIT
|
domain = DOMAIN_HOMEKIT
|
||||||
|
|
||||||
if not entity_id and domain:
|
if not entity_id and domain:
|
||||||
entity_id = "%s." % (domain,)
|
entity_id = f"{domain}."
|
||||||
|
|
||||||
return not entity_id or entities_filter(entity_id)
|
return not entity_id or entities_filter(entity_id)
|
||||||
|
|
||||||
|
@ -530,7 +530,7 @@ def _entry_message_from_state(domain, state):
|
||||||
if domain in ["device_tracker", "person"]:
|
if domain in ["device_tracker", "person"]:
|
||||||
if state.state == STATE_NOT_HOME:
|
if state.state == STATE_NOT_HOME:
|
||||||
return "is away"
|
return "is away"
|
||||||
return "is at {}".format(state.state)
|
return f"is at {state.state}"
|
||||||
|
|
||||||
if domain == "sun":
|
if domain == "sun":
|
||||||
if state.state == sun.STATE_ABOVE_HORIZON:
|
if state.state == sun.STATE_ABOVE_HORIZON:
|
||||||
|
@ -596,9 +596,9 @@ def _entry_message_from_state(domain, state):
|
||||||
"vibration",
|
"vibration",
|
||||||
]:
|
]:
|
||||||
if state.state == STATE_ON:
|
if state.state == STATE_ON:
|
||||||
return "detected {}".format(device_class)
|
return f"detected {device_class}"
|
||||||
if state.state == STATE_OFF:
|
if state.state == STATE_OFF:
|
||||||
return "cleared (no {} detected)".format(device_class)
|
return f"cleared (no {device_class} detected)"
|
||||||
|
|
||||||
if state.state == STATE_ON:
|
if state.state == STATE_ON:
|
||||||
# Future: combine groups and its entity entries ?
|
# Future: combine groups and its entity entries ?
|
||||||
|
@ -607,4 +607,4 @@ def _entry_message_from_state(domain, state):
|
||||||
if state.state == STATE_OFF:
|
if state.state == STATE_OFF:
|
||||||
return "turned off"
|
return "turned off"
|
||||||
|
|
||||||
return "changed to {}".format(state.state)
|
return f"changed to {state.state}"
|
||||||
|
|
|
@ -24,7 +24,7 @@ def setup(hass, config):
|
||||||
"""Set up the Logentries component."""
|
"""Set up the Logentries component."""
|
||||||
conf = config[DOMAIN]
|
conf = config[DOMAIN]
|
||||||
token = conf.get(CONF_TOKEN)
|
token = conf.get(CONF_TOKEN)
|
||||||
le_wh = "{}{}".format(DEFAULT_HOST, token)
|
le_wh = f"{DEFAULT_HOST}{token}"
|
||||||
|
|
||||||
def logentries_event_listener(event):
|
def logentries_event_listener(event):
|
||||||
"""Listen for new messages on the bus and sends them to Logentries."""
|
"""Listen for new messages on the bus and sends them to Logentries."""
|
||||||
|
|
|
@ -156,7 +156,7 @@ async def async_setup_entry(hass, entry):
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
# The TimeoutError exception object returns nothing when casted to a
|
# The TimeoutError exception object returns nothing when casted to a
|
||||||
# string, so we'll handle it separately.
|
# string, so we'll handle it separately.
|
||||||
err = "{}s timeout exceeded when connecting to Logi Circle API".format(_TIMEOUT)
|
err = f"{_TIMEOUT}s timeout exceeded when connecting to Logi Circle API"
|
||||||
hass.components.persistent_notification.create(
|
hass.components.persistent_notification.create(
|
||||||
"Error: {}<br />"
|
"Error: {}<br />"
|
||||||
"You will need to restart hass after fixing."
|
"You will need to restart hass after fixing."
|
||||||
|
|
|
@ -179,7 +179,7 @@ class LogiCircleFlowHandler(config_entries.ConfigFlow):
|
||||||
account_id = (await logi_session.account)["accountId"]
|
account_id = (await logi_session.account)["accountId"]
|
||||||
await logi_session.close()
|
await logi_session.close()
|
||||||
return self.async_create_entry(
|
return self.async_create_entry(
|
||||||
title="Logi Circle ({})".format(account_id),
|
title=f"Logi Circle ({account_id})",
|
||||||
data={
|
data={
|
||||||
CONF_CLIENT_ID: client_id,
|
CONF_CLIENT_ID: client_id,
|
||||||
CONF_CLIENT_SECRET: client_secret,
|
CONF_CLIENT_SECRET: client_secret,
|
||||||
|
|
|
@ -49,7 +49,7 @@ class LogiSensor(Entity):
|
||||||
"""Initialize a sensor for Logi Circle camera."""
|
"""Initialize a sensor for Logi Circle camera."""
|
||||||
self._sensor_type = sensor_type
|
self._sensor_type = sensor_type
|
||||||
self._camera = camera
|
self._camera = camera
|
||||||
self._id = "{}-{}".format(self._camera.mac_address, self._sensor_type)
|
self._id = f"{self._camera.mac_address}-{self._sensor_type}"
|
||||||
self._icon = "mdi:{}".format(SENSOR_TYPES.get(self._sensor_type)[2])
|
self._icon = "mdi:{}".format(SENSOR_TYPES.get(self._sensor_type)[2])
|
||||||
self._name = "{0} {1}".format(
|
self._name = "{0} {1}".format(
|
||||||
self._camera.name, SENSOR_TYPES.get(self._sensor_type)[0]
|
self._camera.name, SENSOR_TYPES.get(self._sensor_type)[0]
|
||||||
|
|
|
@ -34,7 +34,7 @@ SENSOR_PM2_5 = "P2"
|
||||||
SENSOR_PRESSURE = "pressure"
|
SENSOR_PRESSURE = "pressure"
|
||||||
SENSOR_TEMPERATURE = "temperature"
|
SENSOR_TEMPERATURE = "temperature"
|
||||||
|
|
||||||
TOPIC_UPDATE = "{0}_data_update".format(DOMAIN)
|
TOPIC_UPDATE = f"{DOMAIN}_data_update"
|
||||||
|
|
||||||
VOLUME_MICROGRAMS_PER_CUBIC_METER = "µg/m3"
|
VOLUME_MICROGRAMS_PER_CUBIC_METER = "µg/m3"
|
||||||
|
|
||||||
|
|
|
@ -114,7 +114,7 @@ class LutronDevice(Entity):
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Return the name of the device."""
|
"""Return the name of the device."""
|
||||||
return "{} {}".format(self._area_name, self._lutron_device.name)
|
return f"{self._area_name} {self._lutron_device.name}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def should_poll(self):
|
def should_poll(self):
|
||||||
|
@ -132,7 +132,7 @@ class LutronButton:
|
||||||
|
|
||||||
def __init__(self, hass, keypad, button):
|
def __init__(self, hass, keypad, button):
|
||||||
"""Register callback for activity on the button."""
|
"""Register callback for activity on the button."""
|
||||||
name = "{}: {}".format(keypad.name, button.name)
|
name = f"{keypad.name}: {button.name}"
|
||||||
self._hass = hass
|
self._hass = hass
|
||||||
self._has_release_event = (
|
self._has_release_event = (
|
||||||
button.button_type is not None and "RaiseLower" in button.button_type
|
button.button_type is not None and "RaiseLower" in button.button_type
|
||||||
|
|
|
@ -85,7 +85,7 @@ class LyftSensor(Entity):
|
||||||
self._sensortype = sensorType
|
self._sensortype = sensorType
|
||||||
self._name = "{} {}".format(self._product["display_name"], self._sensortype)
|
self._name = "{} {}".format(self._product["display_name"], self._sensortype)
|
||||||
if "lyft" not in self._name.lower():
|
if "lyft" not in self._name.lower():
|
||||||
self._name = "Lyft{}".format(self._name)
|
self._name = f"Lyft{self._name}"
|
||||||
if self._sensortype == "time":
|
if self._sensortype == "time":
|
||||||
self._unit_of_measurement = "min"
|
self._unit_of_measurement = "min"
|
||||||
elif self._sensortype == "price":
|
elif self._sensortype == "price":
|
||||||
|
|
|
@ -108,10 +108,10 @@ class MagicSeaweedSensor(Entity):
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Return the name of the sensor."""
|
"""Return the name of the sensor."""
|
||||||
if self.hour is None and "forecast" in self.type:
|
if self.hour is None and "forecast" in self.type:
|
||||||
return "{} {}".format(self.client_name, self._name)
|
return f"{self.client_name} {self._name}"
|
||||||
if self.hour is None:
|
if self.hour is None:
|
||||||
return "Current {} {}".format(self.client_name, self._name)
|
return f"Current {self.client_name} {self._name}"
|
||||||
return "{} {} {}".format(self.hour, self.client_name, self._name)
|
return f"{self.hour} {self.client_name} {self._name}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self):
|
def state(self):
|
||||||
|
|
|
@ -19,7 +19,7 @@ CONF_SANDBOX = "sandbox"
|
||||||
|
|
||||||
DEFAULT_SANDBOX = False
|
DEFAULT_SANDBOX = False
|
||||||
|
|
||||||
MESSAGE_RECEIVED = "{}_message_received".format(DOMAIN)
|
MESSAGE_RECEIVED = f"{DOMAIN}_message_received"
|
||||||
|
|
||||||
CONFIG_SCHEMA = vol.Schema(
|
CONFIG_SCHEMA = vol.Schema(
|
||||||
{
|
{
|
||||||
|
@ -75,7 +75,7 @@ async def verify_webhook(hass, token=None, timestamp=None, signature=None):
|
||||||
|
|
||||||
hmac_digest = hmac.new(
|
hmac_digest = hmac.new(
|
||||||
key=bytes(hass.data[DOMAIN][CONF_API_KEY], "utf-8"),
|
key=bytes(hass.data[DOMAIN][CONF_API_KEY], "utf-8"),
|
||||||
msg=bytes("{}{}".format(timestamp, token), "utf-8"),
|
msg=bytes(f"{timestamp}{token}", "utf-8"),
|
||||||
digestmod=hashlib.sha256,
|
digestmod=hashlib.sha256,
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
|
|
||||||
|
|
|
@ -74,7 +74,7 @@ class MaryTTSProvider(Provider):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with async_timeout.timeout(10):
|
with async_timeout.timeout(10):
|
||||||
url = "http://{}:{}/process?".format(self._host, self._port)
|
url = f"http://{self._host}:{self._port}/process?"
|
||||||
|
|
||||||
audio = self._codec.upper()
|
audio = self._codec.upper()
|
||||||
if audio == "WAV":
|
if audio == "WAV":
|
||||||
|
|
|
@ -83,7 +83,7 @@ class MetOfficeWeather(WeatherEntity):
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Return the name of the sensor."""
|
"""Return the name of the sensor."""
|
||||||
return "{} {}".format(self._name, self.site.name)
|
return f"{self._name} {self.site.name}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def condition(self):
|
def condition(self):
|
||||||
|
|
|
@ -115,8 +115,8 @@ class MicrosoftProvider(Provider):
|
||||||
self._gender = gender
|
self._gender = gender
|
||||||
self._type = ttype
|
self._type = ttype
|
||||||
self._output = DEFAULT_OUTPUT
|
self._output = DEFAULT_OUTPUT
|
||||||
self._rate = "{}%".format(rate)
|
self._rate = f"{rate}%"
|
||||||
self._volume = "{}%".format(volume)
|
self._volume = f"{volume}%"
|
||||||
self._pitch = pitch
|
self._pitch = pitch
|
||||||
self._contour = contour
|
self._contour = contour
|
||||||
self.name = "Microsoft"
|
self.name = "Microsoft"
|
||||||
|
|
|
@ -92,7 +92,7 @@ async def async_setup(hass, config):
|
||||||
g_id = slugify(name)
|
g_id = slugify(name)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await face.call_api("put", "persongroups/{0}".format(g_id), {"name": name})
|
await face.call_api("put", f"persongroups/{g_id}", {"name": name})
|
||||||
face.store[g_id] = {}
|
face.store[g_id] = {}
|
||||||
|
|
||||||
entities[g_id] = MicrosoftFaceGroupEntity(hass, face, g_id, name)
|
entities[g_id] = MicrosoftFaceGroupEntity(hass, face, g_id, name)
|
||||||
|
@ -109,7 +109,7 @@ async def async_setup(hass, config):
|
||||||
g_id = slugify(service.data[ATTR_NAME])
|
g_id = slugify(service.data[ATTR_NAME])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await face.call_api("delete", "persongroups/{0}".format(g_id))
|
await face.call_api("delete", f"persongroups/{g_id}")
|
||||||
face.store.pop(g_id)
|
face.store.pop(g_id)
|
||||||
|
|
||||||
entity = entities.pop(g_id)
|
entity = entities.pop(g_id)
|
||||||
|
@ -126,7 +126,7 @@ async def async_setup(hass, config):
|
||||||
g_id = service.data[ATTR_GROUP]
|
g_id = service.data[ATTR_GROUP]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await face.call_api("post", "persongroups/{0}/train".format(g_id))
|
await face.call_api("post", f"persongroups/{g_id}/train")
|
||||||
except HomeAssistantError as err:
|
except HomeAssistantError as err:
|
||||||
_LOGGER.error("Can't train group '%s' with error: %s", g_id, err)
|
_LOGGER.error("Can't train group '%s' with error: %s", g_id, err)
|
||||||
|
|
||||||
|
@ -141,7 +141,7 @@ async def async_setup(hass, config):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
user_data = await face.call_api(
|
user_data = await face.call_api(
|
||||||
"post", "persongroups/{0}/persons".format(g_id), {"name": name}
|
"post", f"persongroups/{g_id}/persons", {"name": name}
|
||||||
)
|
)
|
||||||
|
|
||||||
face.store[g_id][name] = user_data["personId"]
|
face.store[g_id][name] = user_data["personId"]
|
||||||
|
@ -160,9 +160,7 @@ async def async_setup(hass, config):
|
||||||
p_id = face.store[g_id].get(name)
|
p_id = face.store[g_id].get(name)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await face.call_api(
|
await face.call_api("delete", f"persongroups/{g_id}/persons/{p_id}")
|
||||||
"delete", "persongroups/{0}/persons/{1}".format(g_id, p_id)
|
|
||||||
)
|
|
||||||
|
|
||||||
face.store[g_id].pop(name)
|
face.store[g_id].pop(name)
|
||||||
await entities[g_id].async_update_ha_state()
|
await entities[g_id].async_update_ha_state()
|
||||||
|
@ -186,7 +184,7 @@ async def async_setup(hass, config):
|
||||||
|
|
||||||
await face.call_api(
|
await face.call_api(
|
||||||
"post",
|
"post",
|
||||||
"persongroups/{0}/persons/{1}/persistedFaces".format(g_id, p_id),
|
f"persongroups/{g_id}/persons/{p_id}/persistedFaces",
|
||||||
image.content,
|
image.content,
|
||||||
binary=True,
|
binary=True,
|
||||||
)
|
)
|
||||||
|
@ -218,7 +216,7 @@ class MicrosoftFaceGroupEntity(Entity):
|
||||||
@property
|
@property
|
||||||
def entity_id(self):
|
def entity_id(self):
|
||||||
"""Return entity id."""
|
"""Return entity id."""
|
||||||
return "{0}.{1}".format(DOMAIN, self._id)
|
return f"{DOMAIN}.{self._id}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self):
|
def state(self):
|
||||||
|
@ -249,7 +247,7 @@ class MicrosoftFace:
|
||||||
self.websession = async_get_clientsession(hass)
|
self.websession = async_get_clientsession(hass)
|
||||||
self.timeout = timeout
|
self.timeout = timeout
|
||||||
self._api_key = api_key
|
self._api_key = api_key
|
||||||
self._server_url = "https://{0}.{1}".format(server_loc, FACE_API_URL)
|
self._server_url = f"https://{server_loc}.{FACE_API_URL}"
|
||||||
self._store = {}
|
self._store = {}
|
||||||
self._entities = entities
|
self._entities = entities
|
||||||
|
|
||||||
|
@ -270,9 +268,7 @@ class MicrosoftFace:
|
||||||
self.hass, self, g_id, group["name"]
|
self.hass, self, g_id, group["name"]
|
||||||
)
|
)
|
||||||
|
|
||||||
persons = await self.call_api(
|
persons = await self.call_api("get", f"persongroups/{g_id}/persons")
|
||||||
"get", "persongroups/{0}/persons".format(g_id)
|
|
||||||
)
|
|
||||||
|
|
||||||
for person in persons:
|
for person in persons:
|
||||||
self._store[g_id][person["name"]] = person["personId"]
|
self._store[g_id][person["name"]] = person["personId"]
|
||||||
|
|
|
@ -30,7 +30,7 @@ def validate_attributes(list_attributes):
|
||||||
"""Validate face attributes."""
|
"""Validate face attributes."""
|
||||||
for attr in list_attributes:
|
for attr in list_attributes:
|
||||||
if attr not in SUPPORTED_ATTRIBUTES:
|
if attr not in SUPPORTED_ATTRIBUTES:
|
||||||
raise vol.Invalid("Invalid attribute {0}".format(attr))
|
raise vol.Invalid(f"Invalid attribute {attr}")
|
||||||
return list_attributes
|
return list_attributes
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -85,7 +85,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
|
||||||
|
|
||||||
prefix = config.get(CONF_NAME)
|
prefix = config.get(CONF_NAME)
|
||||||
if prefix:
|
if prefix:
|
||||||
name = "{} {}".format(prefix, name)
|
name = f"{prefix} {name}"
|
||||||
|
|
||||||
devs.append(
|
devs.append(
|
||||||
MiFloraSensor(poller, parameter, name, unit, icon, force_update, median)
|
MiFloraSensor(poller, parameter, name, unit, icon, force_update, median)
|
||||||
|
|
|
@ -166,7 +166,7 @@ def setup(hass, config):
|
||||||
|
|
||||||
def get_minio_endpoint(host: str, port: int) -> str:
|
def get_minio_endpoint(host: str, port: int) -> str:
|
||||||
"""Create minio endpoint from host and port."""
|
"""Create minio endpoint from host and port."""
|
||||||
return "{}:{}".format(host, port)
|
return f"{host}:{port}"
|
||||||
|
|
||||||
|
|
||||||
class QueueListener(threading.Thread):
|
class QueueListener(threading.Thread):
|
||||||
|
|
|
@ -94,7 +94,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||||
|
|
||||||
prefix = config.get(CONF_NAME)
|
prefix = config.get(CONF_NAME)
|
||||||
if prefix:
|
if prefix:
|
||||||
name = "{} {}".format(prefix, name)
|
name = f"{prefix} {name}"
|
||||||
|
|
||||||
devs.append(
|
devs.append(
|
||||||
MiTempBtSensor(poller, parameter, device, name, unit, force_update, median)
|
MiTempBtSensor(poller, parameter, device, name, unit, force_update, median)
|
||||||
|
|
|
@ -53,7 +53,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||||
|
|
||||||
async_dispatcher_connect(
|
async_dispatcher_connect(
|
||||||
hass,
|
hass,
|
||||||
"{}_{}_register".format(DOMAIN, ENTITY_TYPE),
|
f"{DOMAIN}_{ENTITY_TYPE}_register",
|
||||||
partial(handle_sensor_registration, webhook_id),
|
partial(handle_sensor_registration, webhook_id),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -21,7 +21,7 @@ from .helpers import device_info
|
||||||
|
|
||||||
def sensor_id(webhook_id, unique_id):
|
def sensor_id(webhook_id, unique_id):
|
||||||
"""Return a unique sensor ID."""
|
"""Return a unique sensor ID."""
|
||||||
return "{}_{}".format(webhook_id, unique_id)
|
return f"{webhook_id}_{unique_id}"
|
||||||
|
|
||||||
|
|
||||||
class MobileAppEntity(Entity):
|
class MobileAppEntity(Entity):
|
||||||
|
|
|
@ -53,7 +53,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||||
|
|
||||||
async_dispatcher_connect(
|
async_dispatcher_connect(
|
||||||
hass,
|
hass,
|
||||||
"{}_{}_register".format(DOMAIN, ENTITY_TYPE),
|
f"{DOMAIN}_{ENTITY_TYPE}_register",
|
||||||
partial(handle_sensor_registration, webhook_id),
|
partial(handle_sensor_registration, webhook_id),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -220,13 +220,13 @@ async def handle_webhook(
|
||||||
|
|
||||||
unique_id = data[ATTR_SENSOR_UNIQUE_ID]
|
unique_id = data[ATTR_SENSOR_UNIQUE_ID]
|
||||||
|
|
||||||
unique_store_key = "{}_{}".format(webhook_id, unique_id)
|
unique_store_key = f"{webhook_id}_{unique_id}"
|
||||||
|
|
||||||
if unique_store_key in hass.data[DOMAIN][entity_type]:
|
if unique_store_key in hass.data[DOMAIN][entity_type]:
|
||||||
_LOGGER.error("Refusing to re-register existing sensor %s!", unique_id)
|
_LOGGER.error("Refusing to re-register existing sensor %s!", unique_id)
|
||||||
return error_response(
|
return error_response(
|
||||||
ERR_SENSOR_DUPLICATE_UNIQUE_ID,
|
ERR_SENSOR_DUPLICATE_UNIQUE_ID,
|
||||||
"{} {} already exists!".format(entity_type, unique_id),
|
f"{entity_type} {unique_id} already exists!",
|
||||||
status=409,
|
status=409,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -257,13 +257,13 @@ async def handle_webhook(
|
||||||
|
|
||||||
unique_id = sensor[ATTR_SENSOR_UNIQUE_ID]
|
unique_id = sensor[ATTR_SENSOR_UNIQUE_ID]
|
||||||
|
|
||||||
unique_store_key = "{}_{}".format(webhook_id, unique_id)
|
unique_store_key = f"{webhook_id}_{unique_id}"
|
||||||
|
|
||||||
if unique_store_key not in hass.data[DOMAIN][entity_type]:
|
if unique_store_key not in hass.data[DOMAIN][entity_type]:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Refusing to update non-registered sensor: %s", unique_store_key
|
"Refusing to update non-registered sensor: %s", unique_store_key
|
||||||
)
|
)
|
||||||
err_msg = "{} {} is not registered".format(entity_type, unique_id)
|
err_msg = f"{entity_type} {unique_id} is not registered"
|
||||||
resp[unique_id] = {
|
resp[unique_id] = {
|
||||||
"success": False,
|
"success": False,
|
||||||
"error": {"code": ERR_SENSOR_NOT_REGISTERED, "message": err_msg},
|
"error": {"code": ERR_SENSOR_NOT_REGISTERED, "message": err_msg},
|
||||||
|
|
|
@ -50,7 +50,7 @@ class MochadLight(Light):
|
||||||
|
|
||||||
self._controller = ctrl
|
self._controller = ctrl
|
||||||
self._address = dev[CONF_ADDRESS]
|
self._address = dev[CONF_ADDRESS]
|
||||||
self._name = dev.get(CONF_NAME, "x10_light_dev_{}".format(self._address))
|
self._name = dev.get(CONF_NAME, f"x10_light_dev_{self._address}")
|
||||||
self._comm_type = dev.get(mochad.CONF_COMM_TYPE, "pl")
|
self._comm_type = dev.get(mochad.CONF_COMM_TYPE, "pl")
|
||||||
self.light = device.Device(ctrl, self._address, comm_type=self._comm_type)
|
self.light = device.Device(ctrl, self._address, comm_type=self._comm_type)
|
||||||
self._brightness = 0
|
self._brightness = 0
|
||||||
|
@ -95,12 +95,12 @@ class MochadLight(Light):
|
||||||
if self._brightness > brightness:
|
if self._brightness > brightness:
|
||||||
bdelta = self._brightness - brightness
|
bdelta = self._brightness - brightness
|
||||||
mochad_brightness = self._calculate_brightness_value(bdelta)
|
mochad_brightness = self._calculate_brightness_value(bdelta)
|
||||||
self.light.send_cmd("dim {}".format(mochad_brightness))
|
self.light.send_cmd(f"dim {mochad_brightness}")
|
||||||
self._controller.read_data()
|
self._controller.read_data()
|
||||||
elif self._brightness < brightness:
|
elif self._brightness < brightness:
|
||||||
bdelta = brightness - self._brightness
|
bdelta = brightness - self._brightness
|
||||||
mochad_brightness = self._calculate_brightness_value(bdelta)
|
mochad_brightness = self._calculate_brightness_value(bdelta)
|
||||||
self.light.send_cmd("bright {}".format(mochad_brightness))
|
self.light.send_cmd(f"bright {mochad_brightness}")
|
||||||
self._controller.read_data()
|
self._controller.read_data()
|
||||||
|
|
||||||
def turn_on(self, **kwargs):
|
def turn_on(self, **kwargs):
|
||||||
|
@ -109,7 +109,7 @@ class MochadLight(Light):
|
||||||
with mochad.REQ_LOCK:
|
with mochad.REQ_LOCK:
|
||||||
if self._brightness_levels > 32:
|
if self._brightness_levels > 32:
|
||||||
out_brightness = self._calculate_brightness_value(brightness)
|
out_brightness = self._calculate_brightness_value(brightness)
|
||||||
self.light.send_cmd("xdim {}".format(out_brightness))
|
self.light.send_cmd(f"xdim {out_brightness}")
|
||||||
self._controller.read_data()
|
self._controller.read_data()
|
||||||
else:
|
else:
|
||||||
self.light.send_cmd("on")
|
self.light.send_cmd("on")
|
||||||
|
|
|
@ -170,7 +170,7 @@ class ModbusThermostat(ClimateDevice):
|
||||||
[x.to_bytes(2, byteorder="big") for x in result.registers]
|
[x.to_bytes(2, byteorder="big") for x in result.registers]
|
||||||
)
|
)
|
||||||
val = struct.unpack(self._structure, byte_string)[0]
|
val = struct.unpack(self._structure, byte_string)[0]
|
||||||
register_value = format(val, ".{}f".format(self._precision))
|
register_value = format(val, f".{self._precision}f")
|
||||||
return register_value
|
return register_value
|
||||||
|
|
||||||
def write_register(self, register, value):
|
def write_register(self, register, value):
|
||||||
|
|
|
@ -54,7 +54,7 @@ def number(value: Any) -> Union[int, float]:
|
||||||
value = float(value)
|
value = float(value)
|
||||||
return value
|
return value
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
raise vol.Invalid("invalid number {}".format(value))
|
raise vol.Invalid(f"invalid number {value}")
|
||||||
|
|
||||||
|
|
||||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||||
|
|
|
@ -19,7 +19,7 @@ from homeassistant.helpers.dispatcher import dispatcher_send
|
||||||
from homeassistant.helpers.event import track_time_interval
|
from homeassistant.helpers.event import track_time_interval
|
||||||
|
|
||||||
DOMAIN = "mopar"
|
DOMAIN = "mopar"
|
||||||
DATA_UPDATED = "{}_data_updated".format(DOMAIN)
|
DATA_UPDATED = f"{DOMAIN}_data_updated"
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
|
@ -56,7 +56,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||||
host = config.get(CONF_HOST)
|
host = config.get(CONF_HOST)
|
||||||
port = config.get(CONF_PORT)
|
port = config.get(CONF_PORT)
|
||||||
|
|
||||||
url = "{}:{}".format(host, port)
|
url = f"{host}:{port}"
|
||||||
|
|
||||||
add_entities([MpcHcDevice(name, url)], True)
|
add_entities([MpcHcDevice(name, url)], True)
|
||||||
|
|
||||||
|
@ -73,9 +73,7 @@ class MpcHcDevice(MediaPlayerDevice):
|
||||||
def update(self):
|
def update(self):
|
||||||
"""Get the latest details."""
|
"""Get the latest details."""
|
||||||
try:
|
try:
|
||||||
response = requests.get(
|
response = requests.get(f"{self._url}/variables.html", data=None, timeout=3)
|
||||||
"{}/variables.html".format(self._url), data=None, timeout=3
|
|
||||||
)
|
|
||||||
|
|
||||||
mpchc_variables = re.findall(r'<p id="(.+?)">(.+?)</p>', response.text)
|
mpchc_variables = re.findall(r'<p id="(.+?)">(.+?)</p>', response.text)
|
||||||
|
|
||||||
|
@ -88,7 +86,7 @@ class MpcHcDevice(MediaPlayerDevice):
|
||||||
"""Send a command to MPC-HC via its window message ID."""
|
"""Send a command to MPC-HC via its window message ID."""
|
||||||
try:
|
try:
|
||||||
params = {"wm_command": command_id}
|
params = {"wm_command": command_id}
|
||||||
requests.get("{}/command.html".format(self._url), params=params, timeout=3)
|
requests.get(f"{self._url}/command.html", params=params, timeout=3)
|
||||||
except requests.exceptions.RequestException:
|
except requests.exceptions.RequestException:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Could not send command %d to MPC-HC at: %s", command_id, self._url
|
"Could not send command %d to MPC-HC at: %s", command_id, self._url
|
||||||
|
|
|
@ -211,7 +211,7 @@ class MpdDevice(MediaPlayerDevice):
|
||||||
if title is None:
|
if title is None:
|
||||||
return name
|
return name
|
||||||
|
|
||||||
return "{}: {}".format(name, title)
|
return f"{name}: {title}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def media_artist(self):
|
def media_artist(self):
|
||||||
|
|
|
@ -86,7 +86,7 @@ async def async_start(
|
||||||
"""Process the received message."""
|
"""Process the received message."""
|
||||||
payload = msg.payload
|
payload = msg.payload
|
||||||
topic = msg.topic
|
topic = msg.topic
|
||||||
topic_trimmed = topic.replace("{}/".format(discovery_topic), "", 1)
|
topic_trimmed = topic.replace(f"{discovery_topic}/", "", 1)
|
||||||
match = TOPIC_MATCHER.match(topic_trimmed)
|
match = TOPIC_MATCHER.match(topic_trimmed)
|
||||||
|
|
||||||
if not match:
|
if not match:
|
||||||
|
@ -134,9 +134,7 @@ async def async_start(
|
||||||
|
|
||||||
if payload:
|
if payload:
|
||||||
# Attach MQTT topic to the payload, used for debug prints
|
# Attach MQTT topic to the payload, used for debug prints
|
||||||
setattr(
|
setattr(payload, "__configuration_source__", f"MQTT (topic: '{topic}')")
|
||||||
payload, "__configuration_source__", "MQTT (topic: '{}')".format(topic)
|
|
||||||
)
|
|
||||||
|
|
||||||
if CONF_PLATFORM in payload and "schema" not in payload:
|
if CONF_PLATFORM in payload and "schema" not in payload:
|
||||||
platform = payload[CONF_PLATFORM]
|
platform = payload[CONF_PLATFORM]
|
||||||
|
|
|
@ -339,7 +339,7 @@ class MqttVacuum(
|
||||||
elif self._cleaning:
|
elif self._cleaning:
|
||||||
self._status = "Cleaning"
|
self._status = "Cleaning"
|
||||||
elif self._error:
|
elif self._error:
|
||||||
self._status = "Error: {}".format(self._error)
|
self._status = f"Error: {self._error}"
|
||||||
else:
|
else:
|
||||||
self._status = "Stopped"
|
self._status = "Stopped"
|
||||||
|
|
||||||
|
@ -360,7 +360,7 @@ class MqttVacuum(
|
||||||
self.hass,
|
self.hass,
|
||||||
self._sub_state,
|
self._sub_state,
|
||||||
{
|
{
|
||||||
"topic{}".format(i): {
|
f"topic{i}": {
|
||||||
"topic": topic,
|
"topic": topic,
|
||||||
"msg_callback": message_received,
|
"msg_callback": message_received,
|
||||||
"qos": self._qos,
|
"qos": self._qos,
|
||||||
|
@ -550,7 +550,7 @@ class MqttVacuum(
|
||||||
mqtt.async_publish(
|
mqtt.async_publish(
|
||||||
self.hass, self._set_fan_speed_topic, fan_speed, self._qos, self._retain
|
self.hass, self._set_fan_speed_topic, fan_speed, self._qos, self._retain
|
||||||
)
|
)
|
||||||
self._status = "Setting fan to {}...".format(fan_speed)
|
self._status = f"Setting fan to {fan_speed}..."
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
|
|
||||||
async def async_send_command(self, command, params=None, **kwargs):
|
async def async_send_command(self, command, params=None, **kwargs):
|
||||||
|
@ -566,5 +566,5 @@ class MqttVacuum(
|
||||||
mqtt.async_publish(
|
mqtt.async_publish(
|
||||||
self.hass, self._send_command_topic, message, self._qos, self._retain
|
self.hass, self._send_command_topic, message, self._qos, self._retain
|
||||||
)
|
)
|
||||||
self._status = "Sending command {}...".format(message)
|
self._status = f"Sending command {message}..."
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
|
|
|
@ -56,7 +56,7 @@ def is_persistence_file(value):
|
||||||
"""Validate that persistence file path ends in either .pickle or .json."""
|
"""Validate that persistence file path ends in either .pickle or .json."""
|
||||||
if value.endswith((".json", ".pickle")):
|
if value.endswith((".json", ".pickle")):
|
||||||
return value
|
return value
|
||||||
raise vol.Invalid("{} does not end in either `.json` or `.pickle`".format(value))
|
raise vol.Invalid(f"{value} does not end in either `.json` or `.pickle`")
|
||||||
|
|
||||||
|
|
||||||
def deprecated(key):
|
def deprecated(key):
|
||||||
|
@ -138,7 +138,7 @@ def _get_mysensors_name(gateway, node_id, child_id):
|
||||||
),
|
),
|
||||||
node_name,
|
node_name,
|
||||||
)
|
)
|
||||||
return "{} {}".format(node_name, child_id)
|
return f"{node_name} {child_id}"
|
||||||
|
|
||||||
|
|
||||||
@callback
|
@callback
|
||||||
|
|
|
@ -44,7 +44,7 @@ def is_serial_port(value):
|
||||||
ports = ("COM{}".format(idx + 1) for idx in range(256))
|
ports = ("COM{}".format(idx + 1) for idx in range(256))
|
||||||
if value in ports:
|
if value in ports:
|
||||||
return value
|
return value
|
||||||
raise vol.Invalid("{} is not a serial port".format(value))
|
raise vol.Invalid(f"{value} is not a serial port")
|
||||||
return cv.isdevice(value)
|
return cv.isdevice(value)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -26,7 +26,7 @@ class MySensorsNotificationDevice(mysensors.device.MySensorsDevice):
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
"""Return the representation."""
|
"""Return the representation."""
|
||||||
return "<MySensorsNotificationDevice {}>".format(self.name)
|
return f"<MySensorsNotificationDevice {self.name}>"
|
||||||
|
|
||||||
|
|
||||||
class MySensorsNotificationService(BaseNotificationService):
|
class MySensorsNotificationService(BaseNotificationService):
|
||||||
|
|
|
@ -41,19 +41,16 @@ class MyStromView(HomeAssistantView):
|
||||||
|
|
||||||
if button_action is None:
|
if button_action is None:
|
||||||
_LOGGER.error("Received unidentified message from myStrom button: %s", data)
|
_LOGGER.error("Received unidentified message from myStrom button: %s", data)
|
||||||
return (
|
return (f"Received unidentified message: {data}", HTTP_UNPROCESSABLE_ENTITY)
|
||||||
"Received unidentified message: {}".format(data),
|
|
||||||
HTTP_UNPROCESSABLE_ENTITY,
|
|
||||||
)
|
|
||||||
|
|
||||||
button_id = data[button_action]
|
button_id = data[button_action]
|
||||||
entity_id = "{}.{}_{}".format(DOMAIN, button_id, button_action)
|
entity_id = f"{DOMAIN}.{button_id}_{button_action}"
|
||||||
if entity_id not in self.buttons:
|
if entity_id not in self.buttons:
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
"New myStrom button/action detected: %s/%s", button_id, button_action
|
"New myStrom button/action detected: %s/%s", button_id, button_action
|
||||||
)
|
)
|
||||||
self.buttons[entity_id] = MyStromBinarySensor(
|
self.buttons[entity_id] = MyStromBinarySensor(
|
||||||
"{}_{}".format(button_id, button_action)
|
f"{button_id}_{button_action}"
|
||||||
)
|
)
|
||||||
self.add_entities([self.buttons[entity_id]])
|
self.add_entities([self.buttons[entity_id]])
|
||||||
else:
|
else:
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue