Skip to content

Commit

Permalink
Merge pull request #425 from SashaXser/master
Browse files Browse the repository at this point in the history
Рефракторинг
  • Loading branch information
AlexxIT authored Jan 6, 2024
2 parents 1fce075 + 65b9c22 commit 23d7b8b
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 87 deletions.
8 changes: 2 additions & 6 deletions custom_components/yandex_station/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,7 @@ async def _setup_entry_from_config(hass: HomeAssistant):
if entry.unique_id == config[CONF_USERNAME]:
return

# load config/.yandex_station.json
x_token = utils.load_token_from_json(hass)
if x_token:
if x_token := utils.load_token_from_json(hass):
config["x_token"] = x_token

# need username and token or password
Expand Down Expand Up @@ -327,9 +325,7 @@ async def _setup_devices(hass: HomeAssistant, quasar: YandexQuasar):

for device in quasar.speakers + quasar.modules:
did = device["quasar_info"]["device_id"]
# support device_id in upper/lower cases
upd = confdevices.get(did) or confdevices.get(did.lower())
if upd:
if upd := confdevices.get(did) or confdevices.get(did.lower()):
device.update(upd)


Expand Down
5 changes: 2 additions & 3 deletions custom_components/yandex_station/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,7 @@ def preset_modes(self):

@property
def current_temperature(self):
if self._c_temp is None:
return self._t_temp
return self._c_temp
return self._t_temp if self._c_temp is None else self._c_temp

@property
def target_temperature(self):
Expand All @@ -114,6 +112,7 @@ def min_temp(self):
def max_temp(self):
return self._max_temp


async def async_set_hvac_mode(self, hvac_mode):
if hvac_mode == HVAC_MODE_OFF:
await self.quasar.device_action(self.device["id"], on=False)
Expand Down
2 changes: 1 addition & 1 deletion custom_components/yandex_station/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ async def _check_yandex_response(self, resp: LoginResponse):
)

elif resp.error_captcha_required:
_LOGGER.debug(f"Captcha required")
_LOGGER.debug("Captcha required")
return self.async_show_form(
step_id="captcha",
data_schema=vol.Schema(
Expand Down
28 changes: 14 additions & 14 deletions custom_components/yandex_station/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,10 @@ async def has_custom_icons(hass: HomeAssistantType):

resources = hass.data["lovelace"]["resources"]
await resources.async_get_info()
for resource in resources.async_items():
if "/yandex-icons.js" in resource["url"]:
return True
return False
return any(
"/yandex-icons.js" in resource["url"]
for resource in resources.async_items()
)


def play_video_by_descriptor(provider: str, item_id: str):
Expand Down Expand Up @@ -185,13 +185,12 @@ def play_video_by_descriptor(provider: str, item_id: str):

async def get_media_payload(text: str, session):
for k, v in RE_MEDIA.items():
m = v.search(text)
if m:
if m := v.search(text):
if k in ("youtube", "kinopoisk", "strm", "yavideo"):
return play_video_by_descriptor(k, m[1])

elif k == "vk":
url = "https://vk.com/" + m[1]
url = f"https://vk.com/{m[1]}"
return play_video_by_descriptor("yavideo", url)

elif k == "music.yandex.playlist":
Expand Down Expand Up @@ -252,12 +251,12 @@ async def get_tts_message(session: ClientSession, url: str):
m = RE_ID3.findall(data)
if len(m) == 1 and m[0][0] == b"TIT2":
# old Hass version has valid ID3 tags with `TIT2` for Title
_LOGGER.debug(f"Получение TTS из ID3")
_LOGGER.debug("Получение TTS из ID3")
m = m[0]
elif len(m) == 3 and m[2][0] == b"Text":
# latest Hass version has bug with `Text` for all tags
# there are 3 tags and the last one we need
_LOGGER.debug(f"Получение TTS из битого ID3")
_LOGGER.debug("Получение TTS из битого ID3")
m = m[2]
else:
_LOGGER.debug(f"Невозможно получить TTS: {data}")
Expand Down Expand Up @@ -294,7 +293,9 @@ async def recognition_lang(request):
_LOGGER.debug("Send fixed recognition lang to client")
return web.Response(body=raw, content_type="application/javascript")

hass.http.app.router.add_get("/frontend_latest/" + child.name, recognition_lang)
hass.http.app.router.add_get(
f"/frontend_latest/{child.name}", recognition_lang
)

resource = hass.http.app.router._resources.pop()
hass.http.app.router._resources.insert(40, resource)
Expand Down Expand Up @@ -365,8 +366,7 @@ def get_media_players(hass: HomeAssistant, speaker_id: str) -> List[dict]:
# check entity_components because MPD not in entity_registry and DLNA has
# wrong supported_features
try:
conf = hass.data[DOMAIN][DATA_CONFIG].get(CONF_MEDIA_PLAYERS)
if conf:
if conf := hass.data[DOMAIN][DATA_CONFIG].get(CONF_MEDIA_PLAYERS):
if isinstance(conf, dict):
return [{"entity_id": k, "name": v} for k, v in conf.items()]
if isinstance(conf, list):
Expand Down Expand Up @@ -404,7 +404,7 @@ def encode_media_source(query: dict) -> str:
"""Convert message param as URL query and all other params as hex path."""
if "message" in query:
message = query.pop("message")
return encode_media_source(query) + "?message=" + message
return f"{encode_media_source(query)}?message={message}"
return URL.build(query=query).query_string.encode().hex()


Expand Down Expand Up @@ -433,7 +433,7 @@ def get_url(hass: HomeAssistant, sid: str, url: str):
sid = sid.lower()
uid = hashlib.md5(url.encode()).hexdigest()
StreamingView.links[sid] = url
return network.get_url(hass) + f"/api/yandex_station/{sid}/{uid}.mp3"
return f"{network.get_url(hass)}/api/yandex_station/{sid}/{uid}.mp3"

async def head(self, request: web.Request, sid: str, uid: str):
url: str = self.links.get(sid)
Expand Down
3 changes: 1 addition & 2 deletions custom_components/yandex_station/core/yandex_glagol.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ async def _connect(self, fails: int):

response = None

resp = data.get("vinsResponse")
if resp:
if resp := data.get("vinsResponse"):
try:
# payload only in yandex module
card = (
Expand Down
2 changes: 1 addition & 1 deletion custom_components/yandex_station/core/yandex_quasar.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ async def set_account_config(self, key: str, value):
if kv.get("api") == "user/settings":
# https://iot.quasar.yandex.ru/m/user/settings
r = await self.session.post(
URL_USER + "/settings", json={kv["key"]: kv["values"][value]}
f"{URL_USER}/settings", json={kv["key"]: kv["values"][value]}
)

else:
Expand Down
19 changes: 9 additions & 10 deletions custom_components/yandex_station/humidifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,11 @@ def supported_features(self):
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device specific state attributes."""
attributes = {
return {
"is_muted": self.is_muted,
"is_ionization_on": self.is_ionization_on,
"is_backlight_on": self.is_backlight_on,
}
return attributes

async def init_params(self, capabilities: dict):
"""Initialize parameters."""
Expand Down Expand Up @@ -156,16 +155,16 @@ async def async_update(self):
continue
instance = capability["state"]["instance"]
value = capability["state"]["value"]
if instance == "on":
self._is_on = value
if instance == "humidity":
self._target_humidity = value
if instance == "mute":
self._is_muted = value
if instance == "ionization":
self._is_ionization_on = value
if instance == "backlight":
self._is_backlight_on = value
elif instance == "humidity":
self._target_humidity = value
elif instance == "ionization":
self._is_ionization_on = value
elif instance == "mute":
self._is_muted = value
elif instance == "on":
self._is_on = value

async def async_turn_on(self, **kwargs):
"""Turn on."""
Expand Down
2 changes: 1 addition & 1 deletion custom_components/yandex_station/intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ async def async_handle(self, intent: Intent) -> IntentResponse:
{
"entity_id": self.intent_type,
"media_content_id": intent.text_input,
"media_content_type": "question:" + self.request_id,
"media_content_type": f"question:{self.request_id}",
},
)

Expand Down
28 changes: 11 additions & 17 deletions custom_components/yandex_station/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def __init__(self, quasar: YandexQuasar, device: dict):
self.entity_id += "yandex_tv"
else:
self.entity_id += "yandex_station"
self.entity_id += "_" + self._attr_unique_id.lower()
self.entity_id += f"_{self._attr_unique_id.lower()}"

# ADDITIONAL CLASS FUNCTION

Expand Down Expand Up @@ -463,7 +463,7 @@ async def _shopping_list(self):
]
for name in add_to:
# плохо работает, если добавлять всё сразу через запятую
text = "Добавь в список покупок " + name
text = f"Добавь в список покупок {name}"
await self.glagol.send({"command": "sendText", "text": text})

if add_to or remove_from:
Expand All @@ -474,7 +474,7 @@ async def _shopping_list(self):
self.debug(f"Новый список покупок: {alice_list}")

data.items = [
{"name": name, "id": "alice" + uuid.uuid4().hex, "complete": False}
{"name": name, "id": f"alice{uuid.uuid4().hex}", "complete": False}
for name in alice_list
]
await self.hass.async_add_executor_job(data.save)
Expand Down Expand Up @@ -626,8 +626,7 @@ def async_set_state(self, data: dict):

try:
if pstate["extra"].get("stateType") in ("music", "radio"):
url = pstate["extra"]["coverURI"]
if url:
if url := pstate["extra"]["coverURI"]:
miur = "https://" + url.replace("%%", "400x400")
elif extra_item:
miur = extra_item["thumbnail_url_16x9"]
Expand Down Expand Up @@ -807,15 +806,12 @@ async def async_play_media(
media_type = "text"

if not media_id:
_LOGGER.warning(f"Получено пустое media_id")
_LOGGER.warning("Получено пустое media_id")
return

# tts for backward compatibility and mini-media-player support
if media_type == "tts":
if self._attr_sound_mode == SOUND_MODE1:
media_type = "text"
else:
media_type = "command"
media_type = "text" if self._attr_sound_mode == SOUND_MODE1 else "command"
elif media_type == "brightness":
await self._set_brightness(media_id)
return
Expand Down Expand Up @@ -878,8 +874,8 @@ async def async_play_media(
return

elif media_type.startswith("question"):
request_id = media_type.split(":", 1)[1] if ":" in media_type else None
card = await self.glagol.send({"command": "sendText", "text": media_id})
request_id = media_type.split(":", 1)[1] if ":" in media_type else None
await self.response(card, request_id)
return

Expand Down Expand Up @@ -995,14 +991,12 @@ def async_set_state(self, data: dict):
if state["aliceState"] != "IDLE":
self.sync_mute = False
self.hass.create_task(self.async_mute_volume(False))
else:
# выключаем громкость колонки, когда с ней не разговариваем
if state["aliceState"] == "IDLE":
self.sync_mute = True
self.hass.create_task(self.async_mute_volume(True))
elif state["aliceState"] == "IDLE":
self.sync_mute = True
self.hass.create_task(self.async_mute_volume(True))

async def sync_play_media(self, player_state: dict):
self.debug(f"Sync state: play_media")
self.debug("Sync state: play_media")

url = await get_mp3(self.quasar.session, player_state)
if not url:
Expand Down
3 changes: 1 addition & 2 deletions custom_components/yandex_station/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ def is_on(self) -> bool:
return True

async def async_send_command(self, command: Iterable[str], **kwargs: Any) -> None:
num_repeats = kwargs.get(ATTR_NUM_REPEATS)
if num_repeats:
if num_repeats := kwargs.get(ATTR_NUM_REPEATS):
command *= num_repeats

delay = kwargs.get(ATTR_DELAY_SECS, 0)
Expand Down
2 changes: 1 addition & 1 deletion custom_components/yandex_station/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def __init__(self, quasar: YandexQuasar, device: dict):
name=self.device["name"],
)

self.entity_id = "media_player.yandex_station_" + self._attr_unique_id.lower()
self.entity_id = f"media_player.yandex_station_{self._attr_unique_id.lower()}"

async def async_update(self):
try:
Expand Down
21 changes: 11 additions & 10 deletions custom_components/yandex_station/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,16 +103,17 @@ async def async_setup_entry(hass, entry, async_add_entities):
if device["type"].startswith(item):
data = await quasar.get_device(device["id"])
for prop in data["properties"]:
for description in SENSOR_TYPES:
if prop["parameters"]["instance"] == description.key:
devices.append(
YandexSensor(
quasar,
device,
prop["parameters"]["name"],
description,
)
)
devices.extend(
YandexSensor(
quasar,
device,
prop["parameters"]["name"],
description,
)
for description in SENSOR_TYPES
if prop["parameters"]["instance"]
== description.key
)
async_add_entities(devices, True)


Expand Down
30 changes: 13 additions & 17 deletions custom_components/yandex_station/water_heater.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,18 @@ async def init_params(self, capabilities: list):
continue

inst = cap["parameters"]["instance"]
if inst == "temperature":
if inst == "keep_warm":
self._attr_supported_features |= SUPPORT_AWAY_MODE
elif inst == "tea_mode":
self._attr_operation_list += [
mode["value"] for mode in cap["parameters"]["modes"]
]
elif inst == "temperature":
assert cap["parameters"]["unit"] == "unit.temperature.celsius"
self._attr_min_temp = cap["parameters"]["range"]["min"]
self._attr_max_temp = cap["parameters"]["range"]["max"]
self._attr_precision = cap["parameters"]["range"]["precision"]
self._attr_supported_features |= SUPPORT_TARGET_TEMPERATURE
elif inst == "tea_mode":
self._attr_operation_list += [
mode["value"] for mode in cap["parameters"]["modes"]
]
elif inst == "mute":
pass
elif inst == "keep_warm":
self._attr_supported_features |= SUPPORT_AWAY_MODE

async def async_update(self):
data = await self.quasar.get_device(self.device["id"])
Expand All @@ -80,20 +78,18 @@ async def async_update(self):
continue

inst = cap["state"]["instance"]
if inst == "on":
if inst == "keep_warm":
self._attr_is_away_mode_on = cap["state"]["value"]

elif inst == "on":
self._attr_current_operation = (
"on" if cap["state"]["value"] else "off"
)
elif inst == "temperature":
self._attr_target_temperature = cap["state"]["value"]
elif inst == "tea_mode":
if self._attr_current_operation == "on":
self._attr_current_operation = cap["state"]["value"]
elif inst == "mute":
pass
elif inst == "keep_warm":
self._attr_is_away_mode_on = cap["state"]["value"]

elif inst == "temperature":
self._attr_target_temperature = cap["state"]["value"]
for prop in data["properties"]:
if not prop["retrievable"]:
continue
Expand Down
Loading

0 comments on commit 23d7b8b

Please sign in to comment.