From d4658e0ed59904ccf8464408061148b6c703693e Mon Sep 17 00:00:00 2001 From: SashaXser <24498484+SashaXser@users.noreply.github.com> Date: Wed, 20 Dec 2023 18:05:08 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D1=80=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Рефракторинг на основе новых возможностей Python --- custom_components/yandex_station/__init__.py | 8 +-- custom_components/yandex_station/climate.py | 27 ++++---- .../yandex_station/config_flow.py | 2 +- .../yandex_station/core/utils.py | 49 ++++++++------- .../yandex_station/core/yandex_glagol.py | 3 +- .../yandex_station/core/yandex_quasar.py | 14 +++-- .../yandex_station/humidifier.py | 19 +++--- custom_components/yandex_station/intent.py | 2 +- .../yandex_station/media_player.py | 63 +++++++++---------- custom_components/yandex_station/remote.py | 3 +- custom_components/yandex_station/select.py | 2 +- custom_components/yandex_station/sensor.py | 21 ++++--- .../yandex_station/water_heater.py | 30 ++++----- tests/test_misc.py | 4 +- 14 files changed, 120 insertions(+), 127 deletions(-) diff --git a/custom_components/yandex_station/__init__.py b/custom_components/yandex_station/__init__.py index 52c54c4..94f3a97 100644 --- a/custom_components/yandex_station/__init__.py +++ b/custom_components/yandex_station/__init__.py @@ -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 @@ -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) diff --git a/custom_components/yandex_station/climate.py b/custom_components/yandex_station/climate.py index de794e1..c32187a 100644 --- a/custom_components/yandex_station/climate.py +++ b/custom_components/yandex_station/climate.py @@ -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): @@ -115,19 +113,22 @@ 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) - elif hvac_mode == HVAC_MODE_HEAT: - if self._preset_modes is not None: - await self.quasar.device_action(self.device["id"], on=True) - else: - await self.quasar.device_action( - self.device["id"], on=True, thermostat=hvac_mode - ) - else: + if ( + hvac_mode != HVAC_MODE_OFF + and hvac_mode == HVAC_MODE_HEAT + and self._preset_modes is not None + ): + await self.quasar.device_action(self.device["id"], on=True) + elif ( + hvac_mode != HVAC_MODE_OFF + and hvac_mode == HVAC_MODE_HEAT + or hvac_mode != HVAC_MODE_OFF + ): await self.quasar.device_action( self.device["id"], on=True, thermostat=hvac_mode ) + else: + await self.quasar.device_action(self.device["id"], on=False) async def async_set_temperature(self, **kwargs): await self.quasar.device_action( diff --git a/custom_components/yandex_station/config_flow.py b/custom_components/yandex_station/config_flow.py index d588987..52a6bf7 100644 --- a/custom_components/yandex_station/config_flow.py +++ b/custom_components/yandex_station/config_flow.py @@ -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( diff --git a/custom_components/yandex_station/core/utils.py b/custom_components/yandex_station/core/utils.py index 7d1a79c..16dee83 100644 --- a/custom_components/yandex_station/core/utils.py +++ b/custom_components/yandex_station/core/utils.py @@ -103,14 +103,19 @@ def update_form(name: str, **kwargs): def find_station(devices, name: str = None): """Найти станцию по ID, имени или просто первую попавшуюся.""" - for device in devices: - if device.get("entity") and ( - device["quasar_info"]["device_id"] == name - or device["name"] == name - or name is None - ): - return device["entity"].entity_id - return None + return next( + ( + device["entity"].entity_id + for device in devices + if device.get("entity") + and ( + device["quasar_info"]["device_id"] == name + or device["name"] == name + or name is None + ) + ), + None, + ) async def error(hass: HomeAssistantType, text: str): @@ -138,10 +143,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): @@ -185,13 +190,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": @@ -252,12 +256,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}") @@ -294,7 +298,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) @@ -365,8 +371,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): @@ -404,7 +409,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() @@ -433,7 +438,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) diff --git a/custom_components/yandex_station/core/yandex_glagol.py b/custom_components/yandex_station/core/yandex_glagol.py index 289166b..3c239b5 100644 --- a/custom_components/yandex_station/core/yandex_glagol.py +++ b/custom_components/yandex_station/core/yandex_glagol.py @@ -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 = ( diff --git a/custom_components/yandex_station/core/yandex_quasar.py b/custom_components/yandex_station/core/yandex_quasar.py index 4730fa8..526f870 100644 --- a/custom_components/yandex_station/core/yandex_quasar.py +++ b/custom_components/yandex_station/core/yandex_quasar.py @@ -70,10 +70,14 @@ def __init__(self, session: YandexSession): @property def hass_id(self): - for device in self.devices: - if device["name"] == "Yandex Intents": - return device["id"] - return None + return next( + ( + device["id"] + for device in self.devices + if device["name"] == "Yandex Intents" + ), + None, + ) async def init(self): """Основная функция. Возвращает список колонок.""" @@ -454,7 +458,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: diff --git a/custom_components/yandex_station/humidifier.py b/custom_components/yandex_station/humidifier.py index 1322fa5..3f4848c 100644 --- a/custom_components/yandex_station/humidifier.py +++ b/custom_components/yandex_station/humidifier.py @@ -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.""" @@ -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.""" diff --git a/custom_components/yandex_station/intent.py b/custom_components/yandex_station/intent.py index 2a9977f..cd771ae 100644 --- a/custom_components/yandex_station/intent.py +++ b/custom_components/yandex_station/intent.py @@ -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}", }, ) diff --git a/custom_components/yandex_station/media_player.py b/custom_components/yandex_station/media_player.py index 8fa2214..f0e15c6 100644 --- a/custom_components/yandex_station/media_player.py +++ b/custom_components/yandex_station/media_player.py @@ -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 @@ -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: @@ -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) @@ -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"] @@ -706,7 +705,7 @@ async def async_set_volume_level(self, volume: float): # https://github.com/AlexxIT/YandexStation/issues/324 if isinstance(volume, str): try: - volume = float(volume) + volume = volume except Exception: return @@ -803,19 +802,16 @@ async def async_play_media( if query.get("volume_level"): extra.setdefault("volume_level", float(query["volume_level"])) # provider, music - from 3rd party TTS (ex google) - if media_type in ("provider", "music"): + if media_type in {"provider", "music"}: 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 @@ -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 @@ -889,26 +885,25 @@ async def async_play_media( await self.glagol.send(payload) - else: - if media_type.startswith(("text:", "dialog:")): - media_id = self.yandex_dialog(media_type, media_id) - await self.quasar.send(self.device, media_id) + elif media_type.startswith(("text:", "dialog:")): + media_id = self.yandex_dialog(media_type, media_id) + await self.quasar.send(self.device, media_id) - elif media_type == "text": - media_id = utils.fix_cloud_text(media_id) - await self.quasar.send(self.device, media_id, is_tts=True) + elif media_type == "text": + media_id = utils.fix_cloud_text(media_id) + await self.quasar.send(self.device, media_id, is_tts=True) - elif media_type == "command": - media_id = utils.fix_cloud_text(media_id) - await self.quasar.send(self.device, media_id) + elif media_type == "command": + media_id = utils.fix_cloud_text(media_id) + await self.quasar.send(self.device, media_id) - elif media_type == "brightness": - await self._set_brightness(media_id) - return + elif media_type == "brightness": + await self._set_brightness(media_id) + return - else: - _LOGGER.warning(f"Unsupported cloud media: {media_type}") - return + else: + _LOGGER.warning(f"Unsupported cloud media: {media_type}") + return class YandexStation(YandexStationBase): @@ -995,14 +990,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: diff --git a/custom_components/yandex_station/remote.py b/custom_components/yandex_station/remote.py index 7aea5b6..d076474 100644 --- a/custom_components/yandex_station/remote.py +++ b/custom_components/yandex_station/remote.py @@ -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) diff --git a/custom_components/yandex_station/select.py b/custom_components/yandex_station/select.py index df39778..3f74b66 100644 --- a/custom_components/yandex_station/select.py +++ b/custom_components/yandex_station/select.py @@ -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: diff --git a/custom_components/yandex_station/sensor.py b/custom_components/yandex_station/sensor.py index b5eacab..c31f8be 100644 --- a/custom_components/yandex_station/sensor.py +++ b/custom_components/yandex_station/sensor.py @@ -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) diff --git a/custom_components/yandex_station/water_heater.py b/custom_components/yandex_station/water_heater.py index bde3f5a..5b5c89e 100644 --- a/custom_components/yandex_station/water_heater.py +++ b/custom_components/yandex_station/water_heater.py @@ -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"]) @@ -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 diff --git a/tests/test_misc.py b/tests/test_misc.py index dddf267..91ce4b0 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -12,7 +12,7 @@ def test_media_source(): id2 = utils.encode_media_source({**query2}) assert id2 == "?message=Привет?!" - id3 = utils.encode_media_source({**query1, **query2}) + id3 = utils.encode_media_source(query1 | query2) assert id3 == id1 + id2 media_id = media_source.generate_media_source_id("tts", id1) @@ -22,4 +22,4 @@ def test_media_source(): assert utils.decode_media_source(media_id) == query2 media_id = media_source.generate_media_source_id("tts", id1 + id2) - assert utils.decode_media_source(media_id) == {**query1, **query2} + assert utils.decode_media_source(media_id) == query1 | query2 From 65b9c2220b58e455a2718ce332d6ea8e7e9b81a4 Mon Sep 17 00:00:00 2001 From: SashaXser <24498484+SashaXser@users.noreply.github.com> Date: Thu, 28 Dec 2023 15:40:02 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=E2=84=962?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/yandex_station/climate.py | 24 ++++++------- .../yandex_station/core/utils.py | 21 +++++------ .../yandex_station/core/yandex_quasar.py | 12 +++---- .../yandex_station/media_player.py | 35 ++++++++++--------- 4 files changed, 41 insertions(+), 51 deletions(-) diff --git a/custom_components/yandex_station/climate.py b/custom_components/yandex_station/climate.py index c32187a..65447b4 100644 --- a/custom_components/yandex_station/climate.py +++ b/custom_components/yandex_station/climate.py @@ -112,23 +112,21 @@ 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 - and hvac_mode == HVAC_MODE_HEAT - and self._preset_modes is not None - ): - await self.quasar.device_action(self.device["id"], on=True) - elif ( - hvac_mode != HVAC_MODE_OFF - and hvac_mode == HVAC_MODE_HEAT - or hvac_mode != HVAC_MODE_OFF - ): + if hvac_mode == HVAC_MODE_OFF: + await self.quasar.device_action(self.device["id"], on=False) + elif hvac_mode == HVAC_MODE_HEAT: + if self._preset_modes is not None: + await self.quasar.device_action(self.device["id"], on=True) + else: + await self.quasar.device_action( + self.device["id"], on=True, thermostat=hvac_mode + ) + else: await self.quasar.device_action( self.device["id"], on=True, thermostat=hvac_mode ) - else: - await self.quasar.device_action(self.device["id"], on=False) async def async_set_temperature(self, **kwargs): await self.quasar.device_action( diff --git a/custom_components/yandex_station/core/utils.py b/custom_components/yandex_station/core/utils.py index 16dee83..88d7ef9 100644 --- a/custom_components/yandex_station/core/utils.py +++ b/custom_components/yandex_station/core/utils.py @@ -103,19 +103,14 @@ def update_form(name: str, **kwargs): def find_station(devices, name: str = None): """Найти станцию по ID, имени или просто первую попавшуюся.""" - return next( - ( - device["entity"].entity_id - for device in devices - if device.get("entity") - and ( - device["quasar_info"]["device_id"] == name - or device["name"] == name - or name is None - ) - ), - None, - ) + for device in devices: + if device.get("entity") and ( + device["quasar_info"]["device_id"] == name + or device["name"] == name + or name is None + ): + return device["entity"].entity_id + return None async def error(hass: HomeAssistantType, text: str): diff --git a/custom_components/yandex_station/core/yandex_quasar.py b/custom_components/yandex_station/core/yandex_quasar.py index 526f870..81c3892 100644 --- a/custom_components/yandex_station/core/yandex_quasar.py +++ b/custom_components/yandex_station/core/yandex_quasar.py @@ -70,14 +70,10 @@ def __init__(self, session: YandexSession): @property def hass_id(self): - return next( - ( - device["id"] - for device in self.devices - if device["name"] == "Yandex Intents" - ), - None, - ) + for device in self.devices: + if device["name"] == "Yandex Intents": + return device["id"] + return None async def init(self): """Основная функция. Возвращает список колонок.""" diff --git a/custom_components/yandex_station/media_player.py b/custom_components/yandex_station/media_player.py index f0e15c6..e9d7ff3 100644 --- a/custom_components/yandex_station/media_player.py +++ b/custom_components/yandex_station/media_player.py @@ -705,7 +705,7 @@ async def async_set_volume_level(self, volume: float): # https://github.com/AlexxIT/YandexStation/issues/324 if isinstance(volume, str): try: - volume = volume + volume = float(volume) except Exception: return @@ -802,7 +802,7 @@ async def async_play_media( if query.get("volume_level"): extra.setdefault("volume_level", float(query["volume_level"])) # provider, music - from 3rd party TTS (ex google) - if media_type in {"provider", "music"}: + if media_type in ("provider", "music"): media_type = "text" if not media_id: @@ -885,25 +885,26 @@ async def async_play_media( await self.glagol.send(payload) - elif media_type.startswith(("text:", "dialog:")): - media_id = self.yandex_dialog(media_type, media_id) - await self.quasar.send(self.device, media_id) + else: + if media_type.startswith(("text:", "dialog:")): + media_id = self.yandex_dialog(media_type, media_id) + await self.quasar.send(self.device, media_id) - elif media_type == "text": - media_id = utils.fix_cloud_text(media_id) - await self.quasar.send(self.device, media_id, is_tts=True) + elif media_type == "text": + media_id = utils.fix_cloud_text(media_id) + await self.quasar.send(self.device, media_id, is_tts=True) - elif media_type == "command": - media_id = utils.fix_cloud_text(media_id) - await self.quasar.send(self.device, media_id) + elif media_type == "command": + media_id = utils.fix_cloud_text(media_id) + await self.quasar.send(self.device, media_id) - elif media_type == "brightness": - await self._set_brightness(media_id) - return + elif media_type == "brightness": + await self._set_brightness(media_id) + return - else: - _LOGGER.warning(f"Unsupported cloud media: {media_type}") - return + else: + _LOGGER.warning(f"Unsupported cloud media: {media_type}") + return class YandexStation(YandexStationBase):