core/homeassistant/components/denon/media_player.py

304 lines
8.9 KiB
Python
Raw Normal View History

"""Support for Denon Network Receivers."""
from __future__ import annotations
2015-09-06 10:07:12 +00:00
import logging
2016-02-19 05:27:50 +00:00
import telnetlib
2015-09-06 10:07:12 +00:00
import voluptuous as vol
from homeassistant.components.media_player import (
PLATFORM_SCHEMA,
MediaPlayerEntity,
MediaPlayerEntityFeature,
2019-07-31 19:25:30 +00:00
)
from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
2015-09-06 10:07:12 +00:00
_LOGGER = logging.getLogger(__name__)
2019-07-31 19:25:30 +00:00
DEFAULT_NAME = "Music station"
SUPPORT_DENON = (
MediaPlayerEntityFeature.VOLUME_SET
| MediaPlayerEntityFeature.VOLUME_MUTE
| MediaPlayerEntityFeature.TURN_ON
| MediaPlayerEntityFeature.TURN_OFF
| MediaPlayerEntityFeature.SELECT_SOURCE
2019-07-31 19:25:30 +00:00
)
SUPPORT_MEDIA_MODES = (
MediaPlayerEntityFeature.PAUSE
| MediaPlayerEntityFeature.STOP
| MediaPlayerEntityFeature.PREVIOUS_TRACK
| MediaPlayerEntityFeature.NEXT_TRACK
| MediaPlayerEntityFeature.PLAY
2019-07-31 19:25:30 +00:00
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
NORMAL_INPUTS = {
"Cd": "CD",
"Dvd": "DVD",
"Blue ray": "BD",
"TV": "TV",
2019-08-02 21:20:07 +00:00
"Satellite / Cable": "SAT/CBL",
2019-07-31 19:25:30 +00:00
"Game": "GAME",
"Game2": "GAME2",
"Video Aux": "V.AUX",
"Dock": "DOCK",
}
MEDIA_MODES = {
"Tuner": "TUNER",
"Media server": "SERVER",
"Ipod dock": "IPOD",
"Net/USB": "NET/USB",
"Rapsody": "RHAPSODY",
"Napster": "NAPSTER",
"Pandora": "PANDORA",
"LastFM": "LASTFM",
"Flickr": "FLICKR",
"Favorites": "FAVORITES",
"Internet Radio": "IRADIO",
"USB/IPOD": "USB/IPOD",
}
# Sub-modes of 'NET/USB'
# {'USB': 'USB', 'iPod Direct': 'IPD', 'Internet Radio': 'IRP',
# 'Favorites': 'FVP'}
2015-09-06 10:07:12 +00:00
def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Denon platform."""
denon = DenonDevice(config[CONF_NAME], config[CONF_HOST])
2015-09-06 10:07:12 +00:00
if denon.update():
add_entities([denon])
2015-09-06 10:07:12 +00:00
class DenonDevice(MediaPlayerEntity):
2016-03-08 09:34:33 +00:00
"""Representation of a Denon device."""
2015-09-06 10:07:12 +00:00
def __init__(self, name, host):
2016-03-08 09:34:33 +00:00
"""Initialize the Denon device."""
2015-09-06 10:07:12 +00:00
self._name = name
self._host = host
2019-07-31 19:25:30 +00:00
self._pwstate = "PWSTANDBY"
self._volume = 0
# Initial value 60dB, changed if we get a MVMAX
self._volume_max = 60
self._source_list = NORMAL_INPUTS.copy()
self._source_list.update(MEDIA_MODES)
self._muted = False
2019-07-31 19:25:30 +00:00
self._mediasource = ""
self._mediainfo = ""
self._should_setup_sources = True
def _setup_sources(self, telnet):
# NSFRN - Network name
2019-07-31 19:25:30 +00:00
nsfrn = self.telnet_request(telnet, "NSFRN ?")[len("NSFRN ") :]
if nsfrn:
self._name = nsfrn
# SSFUN - Configured sources with (optional) names
self._source_list = {}
2019-07-31 19:25:30 +00:00
for line in self.telnet_request(telnet, "SSFUN ?", all_lines=True):
ssfun = line[len("SSFUN") :].split(" ", 1)
source = ssfun[0]
if len(ssfun) == 2 and ssfun[1]:
configured_name = ssfun[1]
else:
# No name configured, reusing the source name
configured_name = source
self._source_list[configured_name] = source
# SSSOD - Deleted sources
2019-07-31 19:25:30 +00:00
for line in self.telnet_request(telnet, "SSSOD ?", all_lines=True):
source, status = line[len("SSSOD") :].split(" ", 1)
if status == "DEL":
for pretty_name, name in self._source_list.items():
if source == name:
del self._source_list[pretty_name]
break
@classmethod
def telnet_request(cls, telnet, command, all_lines=False):
2016-03-08 09:34:33 +00:00
"""Execute `command` and return the response."""
_LOGGER.debug("Sending: %s", command)
2019-07-31 19:25:30 +00:00
telnet.write(command.encode("ASCII") + b"\r")
lines = []
while True:
2019-07-31 19:25:30 +00:00
line = telnet.read_until(b"\r", timeout=0.2)
if not line:
break
2019-07-31 19:25:30 +00:00
lines.append(line.decode("ASCII").strip())
2018-01-27 19:58:27 +00:00
_LOGGER.debug("Received: %s", line)
if all_lines:
return lines
2019-07-31 19:25:30 +00:00
return lines[0] if lines else ""
def telnet_command(self, command):
2016-03-08 09:34:33 +00:00
"""Establish a telnet connection and sends `command`."""
telnet = telnetlib.Telnet(self._host)
_LOGGER.debug("Sending: %s", command)
2019-07-31 19:25:30 +00:00
telnet.write(command.encode("ASCII") + b"\r")
telnet.read_very_eager() # skip response
telnet.close()
def update(self):
2016-03-08 09:34:33 +00:00
"""Get the latest details from the device."""
2015-09-06 10:07:12 +00:00
try:
telnet = telnetlib.Telnet(self._host)
2016-09-08 06:43:05 +00:00
except OSError:
return False
2015-09-06 10:07:12 +00:00
if self._should_setup_sources:
self._setup_sources(telnet)
self._should_setup_sources = False
2019-07-31 19:25:30 +00:00
self._pwstate = self.telnet_request(telnet, "PW?")
for line in self.telnet_request(telnet, "MV?", all_lines=True):
if line.startswith("MVMAX "):
# only grab two digit max, don't care about any half digit
2019-07-31 19:25:30 +00:00
self._volume_max = int(line[len("MVMAX ") : len("MVMAX XX")])
continue
2019-07-31 19:25:30 +00:00
if line.startswith("MV"):
self._volume = int(line[len("MV") :])
self._muted = self.telnet_request(telnet, "MU?") == "MUON"
self._mediasource = self.telnet_request(telnet, "SI?")[len("SI") :]
if self._mediasource in MEDIA_MODES.values():
self._mediainfo = ""
2019-07-31 19:25:30 +00:00
answer_codes = [
"NSE0",
"NSE1X",
"NSE2X",
"NSE3X",
"NSE4",
"NSE5",
"NSE6",
"NSE7",
"NSE8",
]
for line in self.telnet_request(telnet, "NSE", all_lines=True):
self._mediainfo += f"{line[len(answer_codes.pop(0)) :]}\n"
else:
self._mediainfo = self.source
telnet.close()
return True
2015-09-06 10:07:12 +00:00
@property
def name(self):
2016-03-08 09:34:33 +00:00
"""Return the name of the device."""
2015-09-06 10:07:12 +00:00
return self._name
@property
def state(self):
2016-03-08 09:34:33 +00:00
"""Return the state of the device."""
2019-07-31 19:25:30 +00:00
if self._pwstate == "PWSTANDBY":
2015-09-06 10:07:12 +00:00
return STATE_OFF
2019-07-31 19:25:30 +00:00
if self._pwstate == "PWON":
return STATE_ON
2015-09-06 10:07:12 +00:00
return None
2015-09-06 10:07:12 +00:00
@property
def volume_level(self):
2016-03-08 09:34:33 +00:00
"""Volume level of the media player (0..1)."""
return self._volume / self._volume_max
2015-09-06 10:07:12 +00:00
@property
def is_volume_muted(self):
"""Return boolean if volume is currently muted."""
return self._muted
2015-09-06 10:07:12 +00:00
@property
def source_list(self):
"""Return the list of available input sources."""
return sorted(self._source_list)
2015-09-06 10:07:12 +00:00
@property
def media_title(self):
"""Return the current media info."""
return self._mediainfo
2015-09-06 10:07:12 +00:00
@property
def supported_features(self):
"""Flag media player features that are supported."""
if self._mediasource in MEDIA_MODES.values():
return SUPPORT_DENON | SUPPORT_MEDIA_MODES
return SUPPORT_DENON
@property
def source(self):
"""Return the current input source."""
for pretty_name, name in self._source_list.items():
if self._mediasource == name:
return pretty_name
2015-09-06 10:07:12 +00:00
def turn_off(self):
2016-03-08 09:34:33 +00:00
"""Turn off media player."""
2019-07-31 19:25:30 +00:00
self.telnet_command("PWSTANDBY")
2015-09-06 10:07:12 +00:00
def volume_up(self):
2016-03-08 09:34:33 +00:00
"""Volume up media player."""
2019-07-31 19:25:30 +00:00
self.telnet_command("MVUP")
2015-09-06 10:07:12 +00:00
def volume_down(self):
2016-03-08 09:34:33 +00:00
"""Volume down media player."""
2019-07-31 19:25:30 +00:00
self.telnet_command("MVDOWN")
2015-09-06 10:07:12 +00:00
def set_volume_level(self, volume):
2016-03-08 09:34:33 +00:00
"""Set volume level, range 0..1."""
self.telnet_command(f"MV{round(volume * self._volume_max):02}")
2015-09-06 10:07:12 +00:00
def mute_volume(self, mute):
2016-03-08 09:34:33 +00:00
"""Mute (true) or unmute (false) media player."""
mute_status = "ON" if mute else "OFF"
self.telnet_command(f"MU{mute_status})")
2015-09-06 10:07:12 +00:00
def media_play(self):
2017-10-05 19:55:09 +00:00
"""Play media player."""
2019-07-31 19:25:30 +00:00
self.telnet_command("NS9A")
2015-09-06 10:07:12 +00:00
def media_pause(self):
2016-03-08 09:34:33 +00:00
"""Pause media player."""
2019-07-31 19:25:30 +00:00
self.telnet_command("NS9B")
2015-09-06 10:07:12 +00:00
def media_stop(self):
"""Pause media player."""
2019-07-31 19:25:30 +00:00
self.telnet_command("NS9C")
2015-09-06 10:07:12 +00:00
def media_next_track(self):
2016-03-08 09:34:33 +00:00
"""Send the next track command."""
2019-07-31 19:25:30 +00:00
self.telnet_command("NS9D")
2015-09-06 10:07:12 +00:00
def media_previous_track(self):
2016-03-08 09:34:33 +00:00
"""Send the previous track command."""
2019-07-31 19:25:30 +00:00
self.telnet_command("NS9E")
2015-09-06 10:07:12 +00:00
def turn_on(self):
2016-03-08 09:34:33 +00:00
"""Turn the media player on."""
2019-07-31 19:25:30 +00:00
self.telnet_command("PWON")
def select_source(self, source):
"""Select input source."""
self.telnet_command(f"SI{self._source_list.get(source)}")