Skip to content

Instantly share code, notes, and snippets.

@jnimmo
Created February 5, 2019 21:12
Show Gist options
  • Save jnimmo/77237a7db2cba37b7663a3ab6f05598a to your computer and use it in GitHub Desktop.
Save jnimmo/77237a7db2cba37b7663a3ab6f05598a to your computer and use it in GitHub Desktop.
"""
Support for interface with an Samsung TV.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.samsungtv/
"""
import logging
import socket
# from datetime import timedelta
import voluptuous as vol
from homeassistant.components.media_player import (
DOMAIN, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET,
SUPPORT_PLAY, MediaPlayerDevice, PLATFORM_SCHEMA, SUPPORT_TURN_ON,
SUPPORT_SELECT_SOURCE)
from homeassistant.const import (
ATTR_ENTITY_ID, CONF_HOST, CONF_MAC, CONF_NAME, CONF_PORT,
STATE_OFF, STATE_ON, STATE_UNKNOWN)
import homeassistant.helpers.config_validation as cv
# from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
ATTR_KEY = 'key_code'
CONF_TIMEOUT = 'timeout'
CONF_SOURCES = 'sources'
CONF_KEY = 'key'
DEFAULT_NAME = 'Samsung TV Remote'
DEFAULT_PORT = 55000
DEFAULT_TIMEOUT = 5
KNOWN_DEVICES_KEY = 'samsungtv_known_devices'
SERVICE_SEND_KEY = 'send_key'
SAMSUNGTV_SEND_KEY_SCHEMA = vol.Schema({
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_KEY): cv.string,
})
SUPPORT_SAMSUNGTV = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | \
SUPPORT_VOLUME_MUTE | SUPPORT_PREVIOUS_TRACK | \
SUPPORT_NEXT_TRACK | SUPPORT_TURN_OFF | SUPPORT_PLAY | \
SUPPORT_SELECT_SOURCE
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
vol.Optional(CONF_SOURCES): vol.All(cv.ensure_list, [
{
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_KEY): cv.string
}
]),
})
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Samsung TV platform."""
known_devices = hass.data.get(KNOWN_DEVICES_KEY)
if known_devices is None:
known_devices = set()
hass.data[KNOWN_DEVICES_KEY] = known_devices
# Is this a manual configuration?
if config.get(CONF_HOST) is not None:
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
mac = config.get(CONF_MAC)
timeout = config.get(CONF_TIMEOUT)
elif discovery_info is not None:
tv_name = discovery_info.get('name')
model = discovery_info.get('model_name')
host = discovery_info.get('host')
name = "{} ({})".format(tv_name, model)
port = DEFAULT_PORT
timeout = DEFAULT_TIMEOUT
mac = None
else:
_LOGGER.warning("Cannot determine device")
return
# Only add a device once, so discovered devices do not override manual
# config.
ip_addr = socket.gethostbyname(host)
if ip_addr not in known_devices:
known_devices.add(ip_addr)
add_devices([SamsungTVDevice(host, port, name, timeout, mac)])
_LOGGER.info("Samsung TV %s:%d added as '%s'", host, port, name)
else:
_LOGGER.info("Ignoring duplicate Samsung TV %s:%d", host, port)
def service_send_key_handler(service):
"""Map services to methods on Alarm."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
key = service.data.get(ATTR_KEY)
for device in known_devices:
if device.entity_id in entity_ids:
device.send_key(device, key)
hass.services.register(DOMAIN, SERVICE_SEND_KEY,
service_send_key_handler,
schema=SAMSUNGTV_SEND_KEY_SCHEMA)
class SamsungTVDevice(MediaPlayerDevice):
"""Representation of a Samsung TV."""
def __init__(self, host, port, name, timeout, mac):
"""Initialize the Samsung device."""
import samsungctl
# Save a reference to the imported classes
self._exceptions_class = samsungctl.exceptions
self._remote_class = samsungctl.Remote
self._name = name
self._mac = mac
# Assume that the TV is not muted
self._muted = False
# Assume that the TV is in Play mode
self._playing = True
self._state = STATE_UNKNOWN
self._remote = None
# Mark the end of a shutdown command (need to wait 15 seconds before
# sending the next command to avoid turning the TV back ON).
self._end_of_power_off = None
self._method = None
self._volume = None
if port == 8001 or port == 8002:
self._method = 'websocket'
else:
self._method = 'legacy'
# Generate a configuration for the Samsung library
self._config = samsungctl.Config(
name='HomeAssistant',
description='HomeAssistant',
id='ha.component.samsungtv',
method=self._method,
port=port,
host=host,
mac=mac
)
self._config.log_level = logging.DEBUG
def update(self):
"""Retrieve the latest data."""
# Send an empty key to see if we are still connected
# self.send_key('KEY')s
# remote = self.get_remote()
if self.get_remote().power is True:
self._state = STATE_ON
self._muted = self.get_remote().mute
self._volume = self.get_remote().volume
else:
self._state = STATE_OFF
def get_remote(self):
"""Create or return a remote control instance."""
if self._remote is None:
# We need to create a new instance to reconnect.
self._remote = self._remote_class(self._config)
return self._remote
def send_key(self, key):
"""Send a key to the tv and handles exceptions."""
self.get_remote().control(key)
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
return self._volume / 100
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
return self._muted
@property
def supported_features(self):
"""Flag media player features that are supported."""
if self._mac:
return SUPPORT_SAMSUNGTV | SUPPORT_TURN_ON
return SUPPORT_SAMSUNGTV
def turn_off(self):
"""Turn off media player."""
self.get_remote().power = False
self._state = STATE_OFF
def volume_up(self):
"""Volume up the media player."""
self.send_key('KEY_VOLUP')
def volume_down(self):
"""Volume down media player."""
self.send_key('KEY_VOLDOWN')
def mute_volume(self, mute):
"""Send mute command."""
self.send_key('KEY_MUTE')
def media_play_pause(self):
"""Simulate play pause media player."""
if self._playing:
self.media_pause()
else:
self.media_play()
def media_play(self):
"""Send play command."""
self._playing = True
self.send_key('KEY_PLAY')
def media_pause(self):
"""Send media pause command to media player."""
self._playing = False
self.send_key('KEY_PAUSE')
def media_next_track(self):
"""Send next track command."""
self.send_key('KEY_FF')
def media_previous_track(self):
"""Send the previous track command."""
self.send_key('KEY_REWIND')
def turn_on(self):
"""Turn the media player on."""
try:
self.get_remote().power = True
self._state = STATE_ON
except self._exceptions_class.SamsungTVError:
self._state = STATE_OFF
def set_volume_level(self, volume):
"""Send the volume level."""
self.get_remote().volume = volume * 100
@property
def source_list(self):
"""List of available input sources."""
return ['DTV', 'HDMI', 'HDMI1', 'HDMI2', 'HDMI3', 'HDMI4']
def select_source(self, source):
"""List of available input sources."""
self.send_key('KEY_' + source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment