Skip to content

Commit

Permalink
Migrate samsungctl to samsungtvws
Browse files Browse the repository at this point in the history
  • Loading branch information
xchwarze committed Oct 17, 2019
1 parent b5a1893 commit e8a0dd6
Show file tree
Hide file tree
Showing 4 changed files with 331 additions and 58 deletions.
5 changes: 2 additions & 3 deletions custom_components/samsungtv_custom/manifest.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
{
"domain": "samsungtv_custom",
"name": "Samsungtv Custom",
"documentation": "https://github.com/roberodin/ha-samsungtv-custom",
"documentation": "https://github.com/xchwarze/ha-samsungtv-custom",
"requirements": [
"samsungctl[websocket]==0.7.1",
"wakeonlan==1.1.6"
],
"dependencies": [],
"codeowners": ["@roberodin"],
"codeowners": ["@xchwarze"],
"homeassistant": "0.99.3"
}
100 changes: 45 additions & 55 deletions custom_components/samsungtv_custom/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@
import socket
import json
import voluptuous as vol
import os
import wakeonlan
import websocket

# Load WS implementation from plugin folder
from custom_components.samsungtv_custom.samsungtvws.remote import SamsungTVWS

from homeassistant import util
from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA
from homeassistant.components.media_player.const import (
MEDIA_TYPE_CHANNEL,
Expand Down Expand Up @@ -35,12 +42,14 @@
_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = "Samsung TV Remote"
DEFAULT_PORT = 55000
DEFAULT_TIMEOUT = 1
KEY_PRESS_TIMEOUT = 1.2
DEFAULT_PORT = 8002
DEFAULT_TIMEOUT = 5
KEY_PRESS_TIMEOUT = 1
KNOWN_DEVICES_KEY = "samsungtv_known_devices"
SOURCES = {"TV": "KEY_TV", "HDMI": "KEY_HDMI"}
CONF_SOURCELIST = "sourcelist"
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=2)
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)

SUPPORT_SAMSUNGTV = (
SUPPORT_PAUSE
Expand All @@ -65,7 +74,6 @@
}
)


def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Samsung TV platform."""
known_devices = hass.data.get(KNOWN_DEVICES_KEY)
Expand All @@ -79,7 +87,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
sourcelist = json.loads(config.get(CONF_SOURCELIST))
else:
sourcelist = SOURCES

# Is this a manual configuration?
if config.get(CONF_HOST) is not None:
host = config.get(CONF_HOST)
Expand Down Expand Up @@ -118,82 +126,67 @@ class SamsungTVDevice(MediaPlayerDevice):

def __init__(self, host, port, name, timeout, mac, uuid, sourcelist):
"""Initialize the Samsung device."""
from samsungctl import exceptions
from samsungctl import Remote
import wakeonlan

# Save a reference to the imported classes
self._exceptions_class = exceptions
self._remote_class = Remote
self._name = name
self._mac = mac
self._uuid = uuid
self._wol = wakeonlan
# Assume that the TV is not muted
self._muted = False
# Assume that the TV is in Play mode
self._playing = True
self._state = None
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
# Generate a configuration for the Samsung library
self._config = {
"name": "HomeAssistant",
"description": name,
"id": "ha.component.samsung",
"port": port,
"host": host,
"timeout": timeout,
}

self._sourcelist = sourcelist

if self._config["port"] in (8001, 8002):
self._config["method"] = "websocket"
else:
self._config["method"] = "legacy"

token_file = os.path.dirname(os.path.realpath(__file__)) + '/tv-token.txt'
self._remote = SamsungTVWS(
name=name,
host=host,
port=port,
timeout=timeout,
key_press_delay=KEY_PRESS_TIMEOUT,
token_file=token_file
)

@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update(self):
"""Update state of device."""
self.send_key("KEY")

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)
self.send_key("KEY", 1)

return self._remote

def send_key(self, key):
def send_key(self, key, retry_count = 1):
"""Send a key to the tv and handles exceptions."""
if self._power_off_in_progress() and key not in ("KEY_POWER", "KEY_POWEROFF"):
_LOGGER.info("TV is powering off, not sending command: %s", key)
return

try:
# recreate connection if connection was dead
retry_count = 1
for _ in range(retry_count + 1):
try:
self.get_remote().control(key)
self._remote.send_key(key)
break
except (self._exceptions_class.ConnectionClosed, BrokenPipeError):
# BrokenPipe can occur when the commands is sent to fast
self._remote = None
except (
ConnectionResetError,
AttributeError,
BrokenPipeError
):
self._remote.close()

self._state = STATE_ON
except (
self._exceptions_class.UnhandledResponse,
self._exceptions_class.AccessDenied,
):
except websocket._exceptions.WebSocketTimeoutException:
# We got a response so it's on.
self._state = STATE_ON
self._remote = None
self._remote.close()
_LOGGER.debug("Failed sending command %s", key, exc_info=True)
return

except OSError:
self._state = STATE_OFF
self._remote = None
self._remote.close()

if self._power_off_in_progress():
self._state = STATE_OFF

Expand Down Expand Up @@ -233,20 +226,17 @@ 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._end_of_power_off = dt_util.utcnow() + timedelta(seconds=15)
self.send_key("KEY_POWER")

if self._config["method"] == "websocket":
self.send_key("KEY_POWER")
else:
self.send_key("KEY_POWEROFF")
# Force closing of remote session to provide instant UI feedback
try:
self.get_remote().close()
self._remote = None
self._remote.close()
except OSError:
_LOGGER.debug("Could not establish connection.")

Expand Down Expand Up @@ -311,7 +301,7 @@ async def async_play_media(self, media_type, media_id, **kwargs):
def turn_on(self):
"""Turn the media player on."""
if self._mac:
self._wol.send_magic_packet(self._mac)
wakeonlan.send_magic_packet(self._mac)
else:
self.send_key("KEY_POWERON")

Expand Down
22 changes: 22 additions & 0 deletions custom_components/samsungtv_custom/samsungtvws/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
SamsungTVWS - Samsung Smart TV WS API wrapper
Copyright (C) 2019 Xchwarze
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1335 USA
"""
from .remote import SamsungTVWS
Loading

0 comments on commit e8a0dd6

Please sign in to comment.