From 17ab0ae2e0c06732843b134b3d78216d71467ea8 Mon Sep 17 00:00:00 2001 From: jasonl Date: Tue, 30 Nov 2021 11:22:15 -0600 Subject: [PATCH] Add volume validation, accept 0-100 and 0.0-1.0 --- README.md | 2 +- custom_components/sonos_cloud/media_player.py | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e18d800..786dc97 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ data: media_content_id: https://.ui.nabu.casa/local/sound_files/doorbell.mp3 media_content_type: music extra: - volume: 35 + volume: 35 # Can be provided as 0-100 or 0.0-1.0 ``` A special `media_content_id` of "CHIME" can be used to test the integration using the built-in sound provided by Sonos. This can be useful for validation if your own URLs are not playing correctly: diff --git a/custom_components/sonos_cloud/media_player.py b/custom_components/sonos_cloud/media_player.py index 04d8df8..0f70b65 100644 --- a/custom_components/sonos_cloud/media_player.py +++ b/custom_components/sonos_cloud/media_player.py @@ -12,6 +12,7 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_IDLE from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN, PLAYERS, SESSION @@ -65,7 +66,14 @@ async def async_play_media( _LOGGER.info("Playing %s", media_id) if extra := kwargs.get(ATTR_MEDIA_EXTRA): if volume := extra.get(ATTR_VOLUME): - data[ATTR_VOLUME] = volume + _LOGGER.info("Type of %s: %s", volume, type(volume)) + if type(volume) not in (int, float): + raise HomeAssistantError(f"Volume '{volume}' not a number") + if not 0 < volume <= 100: + raise HomeAssistantError(f"Volume '{volume}' not in acceptable range of 0-100") + if volume < 1: + volume = volume * 100 + data[ATTR_VOLUME] = int(volume) if media_id != "CHIME": data["streamUrl"] = media_id session = self.hass.data[DOMAIN][SESSION]