Core: [0.81.0] Samsung TV not working

Created on 26 Oct 2018  ·  223Comments  ·  Source: home-assistant/core

Home Assistant release with the issue:
0.81.0b2

Last working Home Assistant release (if known):
0.80.3

Operating environment (Hass.io/Docker/Windows/etc.):

  • Hass.io on a Raspberry Pi 3 Model B (32gb SD)
  • Hass.io supervisor 138
  • HassOS 1.11

Component/platform:
samsungtv

Description of problem:
Media player not working under 0.81.0b2. It shows off although the TV is on. Reverted back to 0.80.3 and everything started working again. No specific errors in the log.

Problem-relevant configuration.yaml entries and (fill out even if it seems unimportant):

media_player:
  - platform: samsungtv
    host: 192.168.86.67
    name: '[TV] Bedroom'
    mac: [REDACTED]

samsungtv

Most helpful comment

I just wanted to let everyone know I have been working diligently on getting the samsungctl library finished up. I am ironing out some more kinks. Just did a massive addition to the library.

activating voice recognition
mouse control
text input
H and J (2016 and 2015) encrypted TV command support
powering on an off 2014+ models
power status
volume direct input
getting the volume
mute direct input
getting the mute
brightness direct input
getting the brightness
contrast direct input
getting the contrast
sharpness direct input
getting the sharpness
aspect ratio
getting the aspect ratio
tuner channel direct input (<= 2015)
getting the tuner channel (<= 2015)
getting active source, changing the source OSD (<= 2015)
full application support. including but not limited to. listing all installed applications, starting an app, listing app content, application id's, names, title, metadata, icons, content groups. content, content icons, playing content... and more.
and a whole slew of other features.

TV discovery that will locate any TV's on the network and properly set up all of the configuration information needed to connect to them.

Supports multiple TV's

Easier loading and saving of config data (allows you to bypass discovery) by use of a Config class. (still backwards compatible with the dictionaries. config files are saved as a flat file and not json data, the files allow for comment lines

Automatic mac address discovery (Linux, Windows, OSX) to send the WOL packets

Removal of the exceptions if you connect and the TV is powered off. so reduced code on the Home Assistant side of things.

Automatic turning on of the TV if you are pairing to the TV. and the TV will return to the state it was at before pairing started once the pairing process is complete. (2014 +)

A really big thing that I think the people that work on home assistant will appreciate. You are not going to have to work very hard to write the code for the GUI.
There are so many variations in supported features across the models and years.. I threw you guys a bone. one simple property will dump the entire command structure for the TV as a dictionary. in the dictionary will be

function name
the function object

for the parameters and the returned values
param/value name
data type (the actual python data type object, int, float, str, bool....)
choices (if any)
minimum (if any)
maximum (if any)
increment/step (if any)
default value (if any)
This should make it really simple for the GUI controls to be created dynamically.

You can also set up some kind of polling to get events for various things changing on the TV(s)

I also expanded the available key codes. there are now 243. including discrete codes for each source. and they are all nicely organized with descriptions for most of them and another bonus.. the keys are grouped together by function with a group name.
an example of some of the group names
Input
Channel
Volume
Navigation
Media
Aspect Ratio
Picture Mode

If you know how to write python code and you are willing to help. please by all means. I wouldn't mind the help.

All 223 comments

Similar problem here, 2016 model year tv, homeassistant 0.81.0b2, raspberry pi 3b+, hass-os.
Homeassistant frontend shows as TV as "unknown" instead of "on".
I can adjust volume, and turn off from the frontend.
When TV is off, the frontend correctly shows TV as "off", however I cannot turn on from frontend, and log shows samsungtv component is taking longer than expected.
Reverted to 0.80.3, and all functions, front end display work as expected.

experiencing the same issues...not sure what changed

updated to 0.81.0 and the issue is still there

@Gio76

I'm having this issue as well. Unfortunately, it looks like this is a TV firmware update problem. Samsung may have broke or disabled the websocket control. Is your TV on the new firmware 1250?

Here is the underlying library HA uses:
https://github.com/Ape/samsungctl/issues/93

I use the Samsung TV component to turn on or off a few lights based on the state of the TV.
When I updated to 0.81.0 the automation will not trigger.
Updated from .80.2 where it was working.
Using an UE65KS7005.
Downgraded to 0.80.3 and it started working again.

@murph24

I'm currently on 1530. If they disabled the websocket that would explain why I don't get a prompt from the TV to allow access to external devices. That sucks, I relied heavily on this components for automations

@Murph24

I actually don't think the TV firmware is the culprit of the issue. In fact I just downgraded to 0.80.3 and everything is working fine. For reference my TV is a 2015 model: UA55J6200

I have the same problem. When tv is on the state reports as unknown. In 0.80.3 everything is fine. So the problem isn't a firmware update by samsung. Is it still the same with 0.81.1 ? Hopefully there is a solution because i have few automations too with that

There was a change in 0.81 where we removed the ping-check and started sending empty key to determine if the TV is on, this was done due to the fact that a TV in standby mode would answer to ping command and therefor never off.
There where also a change to use unknown rather than on, the frontend did not display play/pause in on mode.

I think we can resolve the "off"-bug if I could get someone to run a couple of scripts on broken system.

My tv reports always correctly as off in standby mode. Also the ping components report as off. I dont have the off bug in 0.81, only the unknown. Hopefully u can change the unknown state. Grtz

@kennedyshead

Anything I can help with?

There was a change in 0.81 where we removed the ping-check and started sending empty key to determine if the TV is on, this was done due to the fact that a TV in standby mode would answer to ping command and therefor never off.
There where also a change to use unknown rather than on, the frontend did not display play/pause in on mode.

I think we can resolve the "off"-bug if I could get someone to run a couple of scripts on broken system.

@kennedyshead

Me too, if I can help running some script or test, please tell me. My TV is a J5500 from 2015.

I have NU8000 and seeing the same issue. Let me know if there is anything that I can help with.

Also having issues, cannot turn on the TV, and when it is on the state is 'unknown'

@Gio76 If you try running samsungctl --host 192.168.0.10 --name myremote KEY and give me that output That is if you have the always off problem.
For the turn on problem I think its because it does not support wake on lan.

I can confirm this issue. When the tv is on the state reports unknown. It is not due to a firmware upgrade (d8000 model)

Issue originated in 81.0

Not sure if this will help but this is the error from my logs. I am having the same issue that I can't mute/unmute, turn on, or turn off. The tv is a MU8000 and all of those commands were working in .80.3

Update for media_player.samsung_tv_remote fails
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 221, in async_update_ha_state
await self.async_device_update()
File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 349, in async_device_update
await self.hass.async_add_executor_job(self.update)
File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(self.args, *self.kwargs)
File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/samsungtv.py", line 124, in update
self.send_key("KEY")
File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/samsungtv.py", line 145, in send_key
self.get_remote().control(key)
File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/samsungtv.py", line 130, in get_remote
self._remote = self._remote_class(self._config)
File "/usr/local/lib/python3.6/site-packages/samsungctl/remote.py", line 11, in __init__
self.remote = RemoteWebsocket(config)
File "/usr/local/lib/python3.6/site-packages/samsungctl/remote_websocket.py", line 30, in __init__
self._read_response()
File "/usr/local/lib/python3.6/site-packages/samsungctl/remote_websocket.py", line 67, in _read_response
response = self.connection.recv()
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 298, in recv
opcode, data = self.recv_data()
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 315, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 328, in recv_data_frame
frame = self.recv_frame()
File "/usr/local/lib/python3.6/site-packages/websocket/_core.py", line 360, in recv_frame
return self.frame_buffer.recv_frame()
File "/usr/local/lib/python3.6/site-packages/websocket/_abnf.py", line 334, in recv_frame
frame.validate(self.skip_utf8_validation)
File "/usr/local/lib/python3.6/site-packages/websocket/_abnf.py", line 149, in validate
raise WebSocketProtocolException("Invalid close opcode.")
websocket._exceptions.WebSocketProtocolException: Invalid close opcode.

@kennedyshead I'm also willing to run scripts to help

@Gio76 If you try running samsungctl --host 192.168.0.10 --name myremote KEY and give me that output That is if you have the always off problem.
For the turn on problem I think its because it does not support wake on lan.

This is the output:

Traceback (most recent call last):
  File "/usr/local/bin/samsungctl", line 9, in <module>
    load_entry_point('samsungctl==0.7.1', 'console_scripts', 'samsungctl')()
  File "/Library/Python/2.7/site-packages/samsungctl/__main__.py", line 110, in main
    with Remote(config) as remote:
  File "/Library/Python/2.7/site-packages/samsungctl/remote.py", line 9, in __init__
    self.remote = RemoteLegacy(config)
  File "/Library/Python/2.7/site-packages/samsungctl/remote_legacy.py", line 22, in __init__
    self.connection.connect((config["host"], config["port"]))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 61] Connection refused

@Gio76 If you try running samsungctl --host 192.168.0.10 --name myremote KEY and give me that output That is if you have the always off problem.
For the turn on problem I think its because it does not support wake on lan.

Hi, can you clarify this a bit? Are you saying certain TV's don't support wake on lan or the updated samsungtv component doesn't support wake on lan?

As I understand it, the old component used wake on lan successfully to turn on TV if necessary.

@Gio76

  1. is 192.168.1.10 the ip of your TV? (just making sure ;) ).
  2. Is this in ON or OFF mode?

and also, try setting the port to 8001 in yaml config.

media_player:
  - platform: samsungtv
    host: 192.168.86.67
    port: 8001
    name: '[TV] Bedroom'
    mac: [REDACTED]

@Gio76

  1. is 192.168.1.10 the ip of your TV? (just making sure ;) ).
  2. Is this in ON or OFF mode?
  1. My TV's IP is different. I have of course updated the command line when testing:
    samsungctl --host 192.168.86.67 --name myremote KEY
  2. You mean if the TV was on or off when I run the command? The traceback I previously sent you, was executed with the TV ON. If the TV is OFF (stand-by) I get this instead:
Traceback (most recent call last):
  File "/usr/local/bin/samsungctl", line 9, in <module>
    load_entry_point('samsungctl==0.7.1', 'console_scripts', 'samsungctl')()
  File "/Library/Python/2.7/site-packages/samsungctl/__main__.py", line 110, in main
    with Remote(config) as remote:
  File "/Library/Python/2.7/site-packages/samsungctl/remote.py", line 9, in __init__
    self.remote = RemoteLegacy(config)
  File "/Library/Python/2.7/site-packages/samsungctl/remote_legacy.py", line 22, in __init__
    self.connection.connect((config["host"], config["port"]))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 60] Operation timed out

and also, try setting the port to 8001 in yaml config.

media_player:
  - platform: samsungtv
    host: 192.168.86.67
    port: 8001
    name: '[TV] Bedroom'
    mac: [REDACTED]

Port 8001 has never worked for me, even when the component used to actually work (prior to 0.81.0). If the TV is OFF (stand-by) is correctly shows ass off, however if the TV is ON the entity shows as unknown

Unknown is unfourtunatly the new ON mode, it will give you the paus/play buttons.

Test this file as a replacement for components/media_player/samsungtv.py in your installation:
https://gist.github.com/kennedyshead/f37d8e3194343594eacc6cdb22fc5c41
@Gio76

@kennedyshead

Sorry to the silly question, but since I am using Hass.io, do I create the folders components/media_player/ inside config?

Unknown is unfourtunatly the new ON mode, it will give you the paus/play buttons.

Test this file as a replacement for components/media_player/samsungtv.py in your installation:
https://gist.github.com/kennedyshead/f37d8e3194343594eacc6cdb22fc5c41
@Gio76

This is correct, I read it in the release notes of 0.81.0. Though I find it more a weird workaround.
See #6969

Oh... hm sorry, I have 0 experience with Hass.io... This file will show you the correct status for the TV as far as I can tell from your stacktrace.
You should enable anynet allshare what ever on the TV and it will work as intended anyway.

@Devqon I think its a bit weird to, but I have 0 knowledge of the frontend code and It will do until that is fixed (if it gets a fix). We should create an issue for it

Unknown is unfourtunatly the new ON mode, it will give you the paus/play buttons.

Test this file as a replacement for components/media_player/samsungtv.py in your installation:
https://gist.github.com/kennedyshead/f37d8e3194343594eacc6cdb22fc5c41
@Gio76

Unfortunately that didn't work. Just to clarify, the issue I have is not related to pause/play button but to the fact the status of the TV entity always shows as OFF even when the TV is ON.

Where there any new stacktraces? Its odd that did not work

No new stacktraces

@Gio76 you on discord? Test the updated gist please.

@kennedyshead I am.. # 6268

I got a KS9000 (EU, equivilent to KS8000 in the US) running RPi3 and Hassio. No programming knowledge but wish to help if it’s possible. I use this component a lot and would love it to work again.

Just wanted to add - For me the big problem is that the component doesn't detect when off. So if it has been set to unknown it won't change to off when I turn off the tv. Have port 8001.

+1 with unknown problem

@Gio76 Could you solve the OFF state issue?

I’m on Hassio, TV is a UE55MU7000. Everything working in 0.80.3 including wake on lan, off status when in standby, on status when powered on. 0.81 causes the TV status to switch from “unknown” to “off” and back to “unknown” every minute that the TV is powered on. In standby it just reports “off”. Downgraded back to 0.80.3 and everything is back to normal.

@pablolassalle unfortunately no, still waiting for a fix.

One workaround to use latest homeassistant and have working samsuntv component is to use the previous samsungtv version from homeassisatnt v0.80.3 as a custom component. This is very easy. Create a new folder "custom_components" in your "config" folder. Create a subfolder "media_player" and place the old samsungtv.py file in this folder. Now, anytime you upgrade homeassistant, the samsungtv component from 0.80.3 will override the new version. I plan to use this until reported problems are fixed, however, I think some of this issues may depend on the year/model of tv so this may be a permanent solution.

Hey @Hackashaq666, that is a simple but very clever way around this issue...genius!

Silly question, how would I get hold of the old samsungtv.py? I'm on Hass.io so I don't have access to most files

I also am using hassio on raspberry pi3b+. This is not a problem.
All versions of homeassistant are available for download in github.
Link for 0.80.3:
https://github.com/home-assistant/home-assistant/archive/0.80.3.zip
Extract the samsungtv.py file from
\home-assistant-0.80.3.zip\home-assistant-0.80.3\homeassistant\components\media_player
And place in your homeassistant
\config\custom_components\media_player

I use the hassio addon "Samba share" to access the \config folder on the raspberry pi from my windows computer.

Spot on....cheers @Hackashaq666

@kennedyshead Can you take a look at your edits and reconsider?

I think #17357 has something to do with this...

https://github.com/home-assistant/home-assistant/commit/1cbb5b8e51e849dfa37185fc133c599170196ec0#diff-a43590df2ca31e1387a03c586a5a56aa

The error is Media player not working under 0.81.0b2. It shows off although the TV is on. Reverted back to 0.80.3 and everything started working again. No specific errors in the log.

That have nothing to do with unknown/off state.

I will make a PR for ON state as soon as the frontend shows play/pause buttons in that state

Issue is still there in 0.82.0 as well. Cannot read state of the TV nor control it.

I'm on 0.82.1 and only the Turn ON/OFF works while turning ON the TV (turn OFF does not work). I have a 2017 Samsung QLED TV QE65Q8FAMT on the latest firmware. Any news when this will be fixed ? Thanks guys.

Link for 0.80.3:
https://github.com/home-assistant/home-assistant/archive/0.80.3.zip
Extract the samsungtv.py file from
\home-assistant-0.80.3.zip\home-assistant-0.80.3\homeassistant\components\media_player
And place in your homeassistant
\config\custom_components\media_player

@Hackashaq666 I tried this but I cannot get the custom component to work. In the log file this error appears:

2018-11-18 20:52:02 ERROR (MainThread) [homeassistant.setup] Error during setup of component samsungtv
Traceback (most recent call last):
   File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/setup.py", line 148, in _async_setup_component
     component.setup, hass, processed_config)  # type: ignore
 AttributeError: module 'custom_components.samsungtv' has no attribute 'setup'

I already tried to use another name (samsungtv_old.py) but then the same error occurs.

Gday,

Ive downgraded the samsungtv.py to 80.3 (and also 79.0) and I have had success (with both) at detecting the state of the TV but both will not turn the TV off. Im assuming the TV on works via WOL and then all other commands are via websockets. Correct? In any case, Ive done some debugging via a python install on a PC. I receive a WebSocketProtocolException: Invalid close opcode. when issuing the command so I put in a few debug statements to see what is going on.

Here is the URL sent:
ws://192.168.1.10:8001/api/v2/channels/samsung.remote.control?name=c2Ftc3VuZ2N0bA==
and the data packet "name=":
{'name': 'samsungctl', 'description': 'PC', 'id': '', 'host': '192.168.1.10', 'port': 8001, 'method': 'websocket', 'timeout': 1}
The response I receive is below:

b'\x03'
b'\xed'
fin=1 opcode=8 data=b'\x03\xednotack'

Although the error is invalid opcode, its actually testing code (1005) in the validation in _abnf.py:

if not self._is_valid_close_status(code):
                raise WebSocketProtocolException("Invalid close opcode.")

@staticmethod
    def _is_valid_close_status(code):
        return code in VALID_CLOSE_STATUS or (3000 <= code < 5000)

I hope this helps with a fix. Seems like the TV is not ACKing the websocket call. Ive not had any software updates since this started to fail so Im pretty confident its a websockets implementation issue. Fingers crossed we can get this one back on track.

Ahh... seems we are in good hands: A temporary solution and work being done for a fix here: https://github.com/Ape/samsungctl/issues/93

I think two different problems are interfering here:

  1. A firmware update by Samsung caused some disfunctionality
  2. A change in the Samsung TV component in HA 0.81 has some disadvantages.

I have a K-series Samsung TV. It does not receive firmware updates anymore. My problems started when I upgraded from HA 0.80 to 0.82. When I go back to 0.80 the problems are gone. So in my case there is no firmware upgrade involved.
My problem: when turning the TV on the state in HA will be: "UNKNOWN". When turning the tv off it takes very long till HA sees the TV as off. In HA 0.80 it took about 15 seconds. In 0.82 it takes about 15 minutes.

Looks like this issue is fixed in 0.83. It’s working again for me.

Ainda não foi corrigido o problema do reconhecimento das TV's Samsung na Versão 0.83.2

Just tried to downgrade _samsungtv.py_ to the: _https://github.com/home-assistant/home-assistant/archive/0.80.3.zip_ version. And this fixes the problem for me.

to override the built in component, it needs to be placed here: _/config/custom_components/media_player/samsungtv.py_

Running Home assistant 0.83.2, _media_player.samsung_tv_remote_ would always stay in "off" state. After downgrade, the component works again.

I have a Samsung _UE55H6475_ , firmware 2880

There are two problems. Only one is fixed. We can now detect if the TV is on or off using the custom component.

Unfortunately no buttons work on the newer TVs (1250 bios) because of the port change (8002) and https requirement as shown here: https://github.com/Ape/samsungctl/issues/93

There is a fix that I have got working from a pc running python however I have no idea how to get to the python libraries on my rpi hassio install to implement this fix. I have asked this question here but have had no replies: https://community.home-assistant.io/t/python-site-packages-location/81025

Can anyone offer any advice on how to get to the python package location on rpi installs?

@cnschulz To get this to work you can create a "custom component" to override the library:

  1. Create folder \config\custom_components\samsungctl -> Add all files\folders from the fixed samsungctl library here

  2. Make a copy of homeassistant's samsungtv.py component. Change the three import statements referencing samsungctl to be:

import custom_components.samsungctl as samsungctl

(below are in def __init__)
from custom_components.samsungctl import exceptions
from custom_components.samsungctl import Remote

put that file here:
\config\custom_components\media_player

Just tried to downgrade _samsungtv.py_ to the: _https://github.com/home-assistant/home-assistant/archive/0.80.3.zip_ version. And this fixes the problem for me.

to override the built in component, it needs to be placed here: _/config/custom_components/media_player/samsungtv.py_

Running Home assistant 0.83.2, _media_player.samsung_tv_remote_ would always stay in "off" state. After downgrade, the component works again.

I have a Samsung _UE55H6475_ , firmware 2880

Thanks this worked perfectly!

Seems like new websocket with ssl support implemented here - https://github.com/kdschlosser/samsungctl

@Sirse unfortunately it's python2?

I have just tried the new files but get errors in the log when trying to send any remote codes like vol up/down:

2019-01-09 00:50:54 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/homeassistant/helpers/service.py", line 279, in _handle_service_platform_call
    await func(entity, data)
  File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/homeassistant/.homeassistant/custom_components/media_player/samsungtv.py", line 237, in mute_volume
    self.send_key('KEY_MUTE')
  File "/home/homeassistant/.homeassistant/custom_components/media_player/samsungtv.py", line 166, in send_key
    self.get_remote().control(key)
  File "/home/homeassistant/.homeassistant/custom_components/media_player/samsungtv.py", line 151, in get_remote
    self._remote = self._remote_class(self._config)
  File "/home/homeassistant/.homeassistant/custom_components/samsungctl/remote.py", line 11, in __init__
    self.remote = RemoteLegacy(config)
  File "/home/homeassistant/.homeassistant/custom_components/samsungctl/remote_legacy.py", line 39, in __init__
    self._read_response(True)
  File "/home/homeassistant/.homeassistant/custom_components/samsungctl/remote_legacy.py", line 71, in _read_response
    tv_name_len = int(codecs.encode(header[1:3], 'hex'), 16)
ValueError: invalid literal for int() with base 16: b''

I have just tried the new files but get errors in the log when trying to send any remote codes like vol up/down:

Change the following lines in samsungtv.py:

if self._config['port'] == 8001: self._config['method'] = 'websocket'
to:
if self._config['port'] == 8002: self._config['method'] = 'websocket'

And change in your config file the port to 8002.

Seems like new websocket with ssl support implemented here - https://github.com/kdschlosser/samsungctl

This sounded promising but, unfortunately, also doesn't work on my Samsung TV. That is, I can connect through the websocket (the console interface comes up) but I can't send any commands to the TV

This worked on my TV (UE50J6250), i.e. I could change volumen etc
https://github.com/eclair4151/SmartCrypto

For details see:
https://github.com/kdschlosser/samsungctl/issues/40

Any chance somebody could implement SmartCrypto into the samsungtv platform?

The H_J branch of samsungctl now has full support for TVs with encrypted communication:
https://github.com/kdschlosser/samsungctl/tree/H_J

Would be great to see this integrated in HA soon!
Maybe @jnimmo is working on it already?

The H_J branch of samsungctl now has full support for TVs with encrypted communication:
https://github.com/kdschlosser/samsungctl/tree/H_J

Would be great to see this integrated in HA soon!
Maybe @jnimmo is working on it already?

Sorry I've been on holiday from my leave for the last week ;) Also just waiting for the new library name/publishing on PyPip etc, but should be able to pick it up in another week. Having a play with what new functionality we can include at the same time.

Hi James,

Thanks for your work on this. Ive been trying madly to figure out how to
expose another service on my own custom implementation of samsungtv on HA.
It would be great if there was support for sending any key to the TV.
There is a function in smasungctl called send_key I believe but I cant
figure out how to modify the add-in to expose it. Is this something you
many be able to do?

On Thu, 24 Jan 2019 at 08:16, James Nimmo notifications@github.com wrote:

The H_J branch of samsungctl now has full support for TVs with encrypted
communication:
https://github.com/kdschlosser/samsungctl/tree/H_J

Would be great to see this integrated in HA soon!
Maybe @jnimmo https://github.com/jnimmo is working on it already?

Sorry I've been on holiday from my leave for the last week ;) Also just
waiting for the new library name/publishing on PyPip etc, but should be
able to pick it up in another week. Having a play with what new
functionality we can include at the same time.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/issues/17802#issuecomment-456969154,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABNw5OXyEUiQpFBv2OxZ7u4OjYmmd75rks5vGNFIgaJpZM4X7co9
.

I've done this before for another component, I just can't remember which one - I'll dig out my Pine64 and grab the code off it!

Cheers, any help appreciated. This could solve some issues a few people
have. Ie: direct source selection doesn't work for my TV but pressing the
hdmi button once selects hdmi 1,twice 2 and so on.

On 24 Jan 2019 08:35, "James Nimmo" notifications@github.com wrote:

I've done this before for another component, I just can't remember which
one - I'll dig out my Pine64 and grab the code off it!


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/issues/17802#issuecomment-456975234,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABNw5DwhSIEm0XqHCDEbcoDB6C75jwjuks5vGNWsgaJpZM4X7co9
.

I just wanted to let everyone know I have been working diligently on getting the samsungctl library finished up. I am ironing out some more kinks. Just did a massive addition to the library.

activating voice recognition
mouse control
text input
H and J (2016 and 2015) encrypted TV command support
powering on an off 2014+ models
power status
volume direct input
getting the volume
mute direct input
getting the mute
brightness direct input
getting the brightness
contrast direct input
getting the contrast
sharpness direct input
getting the sharpness
aspect ratio
getting the aspect ratio
tuner channel direct input (<= 2015)
getting the tuner channel (<= 2015)
getting active source, changing the source OSD (<= 2015)
full application support. including but not limited to. listing all installed applications, starting an app, listing app content, application id's, names, title, metadata, icons, content groups. content, content icons, playing content... and more.
and a whole slew of other features.

TV discovery that will locate any TV's on the network and properly set up all of the configuration information needed to connect to them.

Supports multiple TV's

Easier loading and saving of config data (allows you to bypass discovery) by use of a Config class. (still backwards compatible with the dictionaries. config files are saved as a flat file and not json data, the files allow for comment lines

Automatic mac address discovery (Linux, Windows, OSX) to send the WOL packets

Removal of the exceptions if you connect and the TV is powered off. so reduced code on the Home Assistant side of things.

Automatic turning on of the TV if you are pairing to the TV. and the TV will return to the state it was at before pairing started once the pairing process is complete. (2014 +)

A really big thing that I think the people that work on home assistant will appreciate. You are not going to have to work very hard to write the code for the GUI.
There are so many variations in supported features across the models and years.. I threw you guys a bone. one simple property will dump the entire command structure for the TV as a dictionary. in the dictionary will be

function name
the function object

for the parameters and the returned values
param/value name
data type (the actual python data type object, int, float, str, bool....)
choices (if any)
minimum (if any)
maximum (if any)
increment/step (if any)
default value (if any)
This should make it really simple for the GUI controls to be created dynamically.

You can also set up some kind of polling to get events for various things changing on the TV(s)

I also expanded the available key codes. there are now 243. including discrete codes for each source. and they are all nicely organized with descriptions for most of them and another bonus.. the keys are grouped together by function with a group name.
an example of some of the group names
Input
Channel
Volume
Navigation
Media
Aspect Ratio
Picture Mode

If you know how to write python code and you are willing to help. please by all means. I wouldn't mind the help.

Great work @kdschlosser, hope to see this incorporated in HA soon.

Great stuff @kdschlosser - looking forward to the release!

So we have discovered a way to get all kinds of logging information out of the TV. with a whole lot of reading, and filtering through the log files a user gave me I was able to build a bunch of other websocket requests. Like

getting the state of the art mode for Frame TV's
turning on and off the art mode for Frame TV's
getting and setting the motion sensor sensitivity
getting and setting the motion sensor timer
getting and setting the brightness sensor

I am really close to doing a release on Pypi. the original connector made for HomeAssistant is going to need to be revised. If there is a person willing to do this. you can start working on it. the current API is not going to change anymore. I will add new features but those are going to be able to be dynamically added to any kind of a GUI so there should not be the need to update any of the code for the connector as i add new features. it should automatically populate into Home Assistant when the library gets updated.

Who ever is willing to update that connector and we can work on it together. I know nothing about the HomeAssistant API. But I can help with the samsungctl end of things.

I’m aiming to work on it, had a go today but couldn’t get the library doing anything today. Will have a look in a couple of days when I have some time

Hey James,

Thanks a million. I had a go but could not figure out how to expose another
key function to the interface. It would be fantastic if we could have the
"send key" function exposed to HA. That way ightly non-standard tv owners
could write macros to do what they need. Make sense?

On Mon, 4 Feb 2019, 21:23 James Nimmo <[email protected] wrote:

I’m aiming to work on it, had a go today but couldn’t get the library
doing anything today. Will have a look in a couple of days when I have some
time


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/issues/17802#issuecomment-460196326,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABNw5MHWGa4QZ5tmesu9hzWW-T4qW06jks5vKAoZgaJpZM4X7co9
.

OK so i had a go at altering the addon script for Home Assistant. while I am pretty confident it will work.. there are several issues. These issues specifically have to do with the core of Home Assistant. It would be far easier for someone else to make the modifications then I. The largest problem is there are no concessions in Home Assistant for TV's. there is kind of a band-aide approach of the media_player.MediaPlayerDevice component. This works. but severely handicaps the amount of control that can be offered.

There is no way to implement any kind of a GUI interface for the addition and removal of TV's it has to be done hard coded. which is not so much of a problem..

here is a link to a very rudimentary way to get samsungctl working in Home Assistant. please be sure to read all of the directions. the specific parts on the script are at the bottom. please post any problems in the issue thread the link is for and not here.

https://github.com/kdschlosser/samsungctl/issues/36

I do believe that at this point in time there really needs to be a dedicated component class for TV's, having TV's included in a home automation is not an uncommon occurrence. in all reality it is probably the central component of most peoples setups.

This is going to be a pretty large change to Home Assistant. to add this component.
I have written python API's for a number of major TV manufactures. Samsung TV's is not the first and nor will it be the last I am sure. I have a pretty decent handle on what should be available in the component class for TV's

this is just a preliminary list.

This is going to outline some of the basic things that are needed to
implement a TV component it also allows for use of custom
created methods. This whole thing is a suggestion and not necessarily
how it should be done. It does give a good outline of what would be
needed. to cover the majority of a TV's functions and features.

TV

Properties

Name|Get|Set
------|----|---
remote_buttons|X|
power|X|X
source|X|X
sources|X|
channel|X|
channels|X|
application|X|X
applications|X|
adaptive_brightness|X|X
brightness|X|X
contrast|X|X
sharpness|X|X
gamma|X|X
color_temperature|X|X
tone (color)|X|X
dnr (dynamic noise reduction)|X|X
dynamic_contrast|X|X
sound_mode|X|X
speaker_layout|X|X
speaker_levels|X|X
speaker_distances|X|X
sleep_timer|X|X
bass|X|X
treble|X|X
aspect_ratio|X|X
zoom|X|X
picture_mode|X|X
mute|X|X
volume|X|X
year|X|
model|X|
resolution|X|
size|X|
panel_type|X|
panel_technology|X|
id|X|
mac_address|X|
firmwave_version|X|
has_voice_recognition|X|
screen_mirroring|X|X

Methods

open_browser(url)
start_voice_recognition()
stop_voice_recognition()
send_remote_button(button)
custom(*args, **kwargs)*

* an instance of the Custom class

Custom Method

Properties

Name|Get|Set
------|----|---
name|X|
description|X|
params|X|
ret_vals|X|

Methods
__call__ *

* this method should use the parameters of args, *kwargs. it is
going to handle making sure that all of the passed data (if any)
get properly sifted and sorted into the corrct Param class instance.
Those instances aree going to vrify the data type and make any
conversions necessary and return the proper data. once that is done
whatever code that needs to be run in order to get a proper returned
value (if needed) is done.the returned values are then passed to the
RetVal class instance that is for that piece of returned data for it
to do any conversions needed. and then it will return that data.

You can see this whole system in action and working properly in this
library

https://github.com/kdschlosser/UPNP_Device/tree/develop

Custom Param/RetVal

Properties

Name|Get|Set
------|----|---
name|X|
max_val|X|
min_val|X|
default_val|X|
choices|X|
direction*|X|X
data_type**|X|

Methods
__call__ ***

** returns either 'in' or 'out'. this lets us know if it is a
Param or a RetVal. the direction is used in the __call__ method to
determine how to handle the data being passed.

** the data type would be the python data type int, str, bytes, float,
or a Content class

*** this method is the workhorse, it is going to do whatever
needs to be done in determining that the data passed is of correct type.
and make any adjustments as necessary. it will then return the proper
data.

Channel

Properties

Name|Get|Set
------|----|---
is_active|X|
name|X|
osd_label|X|X
major|X|
minor|X|
number|X|
icon|X|
lock_pin (parental lock)|X|X
is_locked|X|
can_edit_label|X|
is_recording|X|

Methods
activate
record

Source

Properties

Name|Get|Set
------|----|---
is_active|X|
name|X|
osd_label|X|X
icon|X|
can_edit_label|X
can_view|X|
state (plugged or unplugged)|X|
content|X|

Methods
activate
__iter__ - iterate over content

Applications

Properties

Name|Get|Set
------|----|---
is_active|X|
name|X|
id|X|
description|X|
icon|X|
version|X|
content (content groups)|X|

Methods
activate
__iter__ - iterate over application to acquire content groups

Application Content Group / Media Folder

Properties

Name|Get|Set
------|----|---
name|X|
id|X|
description|X|
icon|X|

Methods
__iter__ - iterate over group to get content

Application Content / Source Media

Properties

Name|Get|Set
------|----|---
name|X|
id|X|
description|X|
icon|X|
is_playable|X|
duration|X|
position|X|
remaining|X|
track|X|
tracks|X|
track_duration|X|
track_position|X|
track_remaining|X|

Methods
activate

Icon

Properties

Name|Get|Set
------|----|---
format|X|
width|X|
height|X|
url|X|
data*|X|

* returns the icon as a string if download process is not a simple URL

@cnschulz

I am not sure if there is a way to institute the input of a custom control. I didn't do a whole lot of digging but I didn't come across anything that jumped out at me either. because of the above post there could be something that can be used in a different manner then what the name of it describes. basically like what is being done to be able to input a channel. the play_media method is being used to achieve the channel input. I do not know if there is something that can be used in a manner like that.

This is disappointing given that most tvs were working fine before the ssl
change. To some degree I think this has been over complicated. If we can
simply expose the send_key method to HA I feel that most of the users would
be happy with writing their own macros to accomplish things. I made the ssl
changes to the code and wrote my own custom add on a few months ago. It's
great apart from the fact that I can't change the source. All I need is to
send a key combination. I can do that fine wirh samsungctl but not the ha
library.

On Wed, 6 Feb 2019, 07:00 Kevin Schlosser <[email protected] wrote:

OK so i had a go at altering the addon script for Home Assistant. while I
am pretty confident it will work.. there are several issues. These issues
specifically have to do with the core of Home Assistant. It would be far
easier for someone else to make the modifications then I. The largest
problem is there are no concessions in Home Assistant for TV's. there is
kind of a band-aide approach of the media_player.MediaPlayerDevice
component. This works. but severely handicaps the amount of control that
can be offered.

There is no way to implement any kind of a GUI interface for the addition
and removal of TV's it has to be done hard coded. which is not so much of a
problem..

here is a link to a very rudimentary way to get samsungctl working in Home
Assistant. please be sure to read all of the directions. the specific parts
on the script are at the bottom. please post any problems in the issue
thread the link is for and not here.

kdschlosser/samsungctl#36
https://github.com/kdschlosser/samsungctl/issues/36

I do believe that at this point in time there really needs to be a
dedicated component class for TV's, having TV's included in a home
automation is not an uncommon occurrence. in all reality it is probably the
central component of most peoples setups.

This is going to be a pretty large change to Home Assistant. to add this
component.
I have written python API's for a number of major TV manufactures. Samsung
TV's is not the first and nor will it be the last I am sure. I have a
pretty decent handle on what should be available in the component class for
TV's

this is just a preliminary list.

This is going to outline some of the basic things that are needed to
implement a TV component it also allows for use of custom
created methods. This whole thing is a suggestion and not necessarily
how it should be done. It does give a good outline of what would be
needed. to cover the majority of a TV's functions and features.
TV

Properties
Name Get Set
power X X
source X X
sources X
channel X
channels X
application X X
applications X
adaptive_brightness X X
brightness X X
contrast X X
sharpness X X
gamma X X
color_temperature X X
tone (color) X X
dnr (dynamic noise reduction) X X
dynamic_contrast X X
sound_mode X X
speaker_layout X X
speaker_levels X X
speaker_distances X X
sleep_timer X X
bass X X
treble X X
aspect_ratio X X
zoom X X
picture_mode X X
mute X X
volume X X
year X
model X
resolution X
size X
panel_type X
panel_technology X
id X
mac_address X
firmwave_version X
has_voice_recognition X
screen_mirroring X X

Methods

open_browser(url)
start_voice_recognition()
stop_voice_recognition()
custom(args, *kwargs)*

  • an instance of the Custom class
    Custom Method

Properties
Name Get Set
name X
description X
params X
ret_vals X

Methods
__call__ *

  • this method should use the parameters of args, *kwargs. it is
    going to handle making sure that all of the passed data (if any)
    get properly sifted and sorted into the corrct Param class instance.
    Those instances aree going to vrify the data type and make any
    conversions necessary and return the proper data. once that is done
    whatever code that needs to be run in order to get a proper returned
    value (if needed) is done.the returned values are then passed to the
    RetVal class instance that is for that piece of returned data for it
    to do any conversions needed. and then it will return that data.

You can see this whole system in action and working properly in this
library

https://github.com/kdschlosser/UPNP_Device/tree/develop
Custom Param/RetVal

Properties
Name Get Set
name X
max_val X
min_val X
default_val X
choices X
direction* X X
data_type** X

Methods
__call__ *

** returns either 'in' or 'out'. this lets us know if it is a
Param or a RetVal. the direction is used in the __call__ method to
determine how to handle the data being passed.

** the data type would be the python data type int, str, bytes, float,
or a Content class

* this method is the workhorse, it is going to do whatever
needs to be done in determining that the data passed is of correct type.
and make any adjustments as necessary. it will then return the proper
data.
Channel

Properties
Name Get Set
is_active X
name X
osd_label X X
major X
minor X
number X
icon X
lock_pin (parental lock) X X
is_locked X
can_edit_label X
is_recording X

Methods
activate
record
Source

Properties
Name Get Set
is_active X
name X
osd_label X X
icon X
can_edit_label X
can_view X
state (plugged or unplugged) X
content X

Methods
activate
__iter__ - iterate over content
Applications

Properties
Name Get Set
is_active X
name X
id X
description X
icon X
version X
content (content groups) X

Methods
activate
__iter__ - iterate over application to acquire content groups
Application Content Group / Media Folder

Properties
Name Get Set
name X
id X
description X
icon X

Methods
__iter__ - iterate over group to get content
Application Content / Source Media

Properties
Name Get Set
name X
id X
description X
icon X
is_playable X
duration X
position X
remaining X
track X
tracks X
track_duration X
track_position X
track_remaining X

Methods
activate
Icon

Properties
Name Get Set
format X
width X
height X
url X
data* X

  • returns the icon as a string if download process is not a simple URL


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/issues/17802#issuecomment-460781858,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABNw5DDR4hvqHluCtKR3zE9mt46g_QiAks5vKeLxgaJpZM4X7co9
.

I've spent hours this last week trying to get the new library working but not having any luck. It was working at a point in time, but I think it is something to do with getting the token and passing it into the config block; which I'm not sure how to do.

I have added the code to implement a send_key service @cnschulz but as I can't get samsungctl working I can't test it. Creating the samsungctl remote just hangs the script up.
https://gist.github.com/jnimmo/77237a7db2cba37b7663a3ab6f05598a

Select Source will be able to be used to select channels/applications but I haven't done anything on that yet.

Will check out your script @kdschlosser , thanks for that

Cheers. I wasn't meaning custom control, rather single key where the key
name is also paseed. I believe this is called send_key in samsungctl.

Also... Didn't HA just add a "remote" media class? I'll take a look and see
if it could suit.

On Wed, 6 Feb 2019, 07:05 Kevin Schlosser <[email protected] wrote:

@cnschulz https://github.com/cnschulz

I am not sure if there is a way to institute the input of a custom
control. I didn't do a whole lot of digging but I didn't come across
anything that jumped out at me either. because of the above post there
could be something that can be used in a different manner then what the
name of it describes. basically like what is being done to be able to input
a channel. the play_media method is being used to achieve the channel
input. I do not know if there is something that can be used in a manner
like that.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/issues/17802#issuecomment-460783573,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABNw5OpgI15PpsNyTHR-Jse1dmA_PeAQks5vKeQCgaJpZM4X7co9
.

samsungctl is not the issue.

we need find out if there is a mechanism in Home Assistant that would either provide a choice selection of the keys available. or a mechanism to be able to enter the key manually.

or maybe something that would create a button for each individual key.

@jnimmo We can probably use (for now) in the custom component to test (someone please double check the URL)

REQUIREMENTS = ['https://github.com/kdschlosser/samsungctl'
                '/archive/d9dadbd4ec4524d26bce7348a56fc8384dd3d953.zip'
                '#samsungctl==0.8.0b']

Let us create a simple component that works with the new library and then we can add other features.

@cnschulz We will have to register a service to send keys for Samsung TVs. The media player does not have send-key service. There are several platforms that register services, so that should not be an issue.

https://www.home-assistant.io/components/remote.roku/

Does the remote class suit?

On Wed, 6 Feb 2019 at 09:18, Kevin Schlosser notifications@github.com
wrote:

samsungctl is not the issue.

we need fund out if there is a mechanism in Home Assistant that would
either provide a choice selection of the keys available. or a mechanism to
be able to enter the key manually.

or maybe something that would create a button for each individual key.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/issues/17802#issuecomment-460826068,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABNw5AeamQZ3wZ0fBOnFxNMZanQY4Ti3ks5vKgMZgaJpZM4X7co9
.

My gist has the code to register the send key service - just the send key
handler method and then the register statement in the setup handler

@jnimmo I tried adding your component, but could not get it to work. Here's the code that I used. Here are some errors that show up:

Tue Feb 05 2019 22:47:23 GMT-0500 (Eastern Standard Time)
Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity_platform.py", line 352, in _async_add_entity
    await entity.async_update_ha_state()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 239, in async_update_ha_state
    attr = self.state_attributes or {}
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/__init__.py", line 787, in state_attributes
    in ATTR_TO_PROPERTY if getattr(self, attr) is not None
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/__init__.py", line 787, in <dictcomp>
    in ATTR_TO_PROPERTY if getattr(self, attr) is not None
  File "/config/custom_components/media_player/samsungtv.py", line 196, in volume_level
    return self._volume / 100
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

Log Details (ERROR)
Tue Feb 05 2019 22:47:56 GMT-0500 (Eastern Standard Time)
Update for media_player.living_room_tv fails
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 221, in async_update_ha_state
    await self.async_device_update()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 349, in async_device_update
    await self.hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/media_player/samsungtv.py", line 166, in update
    self._muted = self.get_remote().mute
  File "/config/deps/lib/python3.6/site-packages/samsungctl/upnp/__init__.py", line 576, in mute
    if not self.connected:
  File "/config/deps/lib/python3.6/site-packages/samsungctl/upnp/__init__.py", line 30, in connected
    self._connect_upnp()
  File "/config/deps/lib/python3.6/site-packages/samsungctl/upnp/__init__.py", line 37, in _connect_upnp
    if not self._connected and self.power:
  File "/config/deps/lib/python3.6/site-packages/samsungctl/upnp/UPNP_Device/upnp_class.py", line 123, in __getattr__
    if item in self._devices:
  File "/config/deps/lib/python3.6/site-packages/samsungctl/upnp/UPNP_Device/upnp_class.py", line 123, in __getattr__
    if item in self._devices:
  File "/config/deps/lib/python3.6/site-packages/samsungctl/upnp/UPNP_Device/upnp_class.py", line 123, in __getattr__
    if item in self._devices:
  [Previous line repeated 324 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

I feel like we may be better off by getting a simple component working (as a replacement to the current one) before we add more features.

@kdschlosser Can your code be modified to create the config file and save it in the config directory so that it can be used easily...thanks!

You said you were not able to get your component working. I feel like we should start with a simple component that can first replace the current non-working one. Then we can keep adding additional features.

Ok...so I was able to get it sort-of working after editing the return self._volume / 100 to return self._volume (turns our the volume was None in my case, may be because I am using a Sonos Playbase). Here's the updated code. We should try to merge @kdschlosser code so that we can have one solid working version.

I am still getting continuous UPNP errors (not sure how to disable them) and some Update of media_player.living_room_tv is taking over 10 seconds and Updating samsungtv media_player took longer than the scheduled update interval 0:00:10 warnings. Also, when you restart HA with the TV turned off, the logs fill up with Updating samsungtv media_player took longer than the scheduled update interval 0:00:10 warnings and the TV state stays unknown.

Edit: Fixed, the last issue (state unknown) by using:

    @property
    def state(self):
        """Return the state of the device."""
        return STATE_ON if self.get_remote().power else STATE_OFF

Still seeing Updating state for media_player.living_room_tv (<class 'custom_components.media_player.samsungtv.SamsungTVDevice'>) took 3.040 seconds. Please report platform to the developers at https://goo.gl/Nvioub suggesting that I/O is not handled appropriately.

i am not sure as to why it would say that for the state. the power property for samsungctl is simply returning if the socket is None or not. nothing there should be taking 3 seconds to do.

also unless you give me specific errors relating to the UPNP I do not know what is going on with it. stating has errors does not help me at all.

also have you tried running the library without the use of Home Assistant? if so does it throw errors then?

*****EDITED CODE******

also sorry about the volume control and not dividing it by 100. the docstring for the volume does not state that the number needs to be scalar volume - 0.0 being lowest and 1.0 being the highest. it states 0...1 makes me think 1..2..3..4..5. as in so on and so forth. I apologize for that.

I am not sure what the need to do get_remote().power is.. that is the exact same thing as self._remote.power.

since the library now handles it's own power states there is no need to do an "update" or to store things like mute. I forgot that calling any thing if the TV is off will return None. So i am assuming that Home Assistant does a poll on the supported features. so that should be easy to solve without the need to store the states in the variables like that.

Now the config file is really not a big deal to handle. I do not know if a variable gets updated does it get written to the config...

so this would be getting the host from the Home Assistant config file.
host = config.get(CONF_HOST)

can this be done to set the host in the config file and will it get written to the file?
config[CONF_HOST] = host

if so then these are the matching values for what the samsungctl.Config has.

CONF_HOST
CONF_ID
CONF_MAC
CONF_METHOD
CONF_NAME
CONF_PORT
CONF_TOKEN
CONF_TIMEOUT

and here are the settings that have no match to the constants

I am thinking that the config is simply a dictionary like structure and it really does not matter what gets placed in there and we can add anything we want to it.

BTW when usnig samsungctl.Config the only things that are needed to make it work is the name and the host. it will hash everything else out. you do not nd to specify a mac, or a port. or even the method. it dos not matter.

you can give this a try and see if it works properly. You will need to have samsungctl 0.8.0b installed into the same Python that you use to run Home Assistant before running this code.

"""
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 asyncio
from datetime import timedelta
import logging
import socket

import voluptuous as vol

from homeassistant.components.media_player import (
    MEDIA_TYPE_CHANNEL, PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE,
    SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF,
    SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP,
    MediaPlayerDevice)
from homeassistant.const import (
    CONF_HOST, CONF_MAC, CONF_NAME, CONF_PORT, CONF_TIMEOUT, CONF_ID,
    CONF_METHOD, CONF_TOKEN, STATE_OFF, STATE_ON)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import dt as dt_util

REQUIREMENTS = ['samsungctl==0.8.0b']

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Samsung TV Remote'
DEFAULT_PORT = 8001
DEFAULT_TIMEOUT = 0
DEFAULT_PAIRED = False
DEFAULT_UPNP_LOCATIONS = None
DEFAULT_METHOD = None
DEFAULT_TOKEN = None
DEFAULT_MAC = None
DEFAULT_ID = None
DEFAULT_DESCRIPTION = socket.gethostname()

def string(value):
    if value is None:
        return value
    else:
        return cv.string(value)

def ensure_list(value):
    if value is None:
        return value
    else:
        return cv.ensure_list(value)


KEY_PRESS_TIMEOUT = 1.2
KNOWN_DEVICES_KEY = 'samsungtv_known_devices'

SUPPORT_SAMSUNGTV = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
    SUPPORT_VOLUME_MUTE | SUPPORT_PREVIOUS_TRACK | \
    SUPPORT_NEXT_TRACK | SUPPORT_TURN_OFF | SUPPORT_PLAY | SUPPORT_PLAY_MEDIA

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_ID, default=DEFAULT_ID): string,
    vol.Optional(CONF_METHOD, default=DEFAULT_METHOD): string,
    vol.Optional(CONF_TOKEN, default=DEFAULT_TOKEN): string,
    vol.Optional(CONF_MAC, default=DEFAULT_MAC): string,
    vol.Optional('paired', default=DEFAULT_PAIRED): cv.boolean,
    vol.Optional('description', default=DEFAULT_DESCRIPTION): cv.string,
    vol.Optional('upnp_locations', default=DEFAULT_UPNP_LOCATIONS): ensure_list,
})

def setup_platform(hass, config, add_entities, 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

    uuid = None
    # Is this a manual configuration?
    if config.get(CONF_HOST) is not None:
        host = config.get(CONF_HOST)

    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
        udn = discovery_info.get('udn')
        if udn and udn.startswith('uuid:'):
            uuid = udn[len('uuid:'):]

        config.update(
            {
                CONF_HOST: host,
                CONF_PORT: port,
                CONF_TIMEOUT: timeout,
                CONF_NAME: name,
                CONF_MAC: mac,
            }
        )
    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_entities([SamsungTVDevice(config, uuid)])
        _LOGGER.info("Samsung TV %s added as '%s'", host, config.get(CONF_NAME))
    else:
        _LOGGER.info("Ignoring duplicate Samsung TV %s", host)


class SamsungTVDevice(MediaPlayerDevice):
    """Representation of a Samsung TV."""

    def __init__(self, config, uuid):
        """Initialize the Samsung device."""
        from samsungctl import exceptions
        from samsungctl import Remote
        # Save a reference to the imported classes
        self._exceptions_class = exceptions
        self._remote_class = Remote
        self._samsung_config = samsungctl.Config(**config)
        self._config = config

        self._name = self._samsung_config.name
        self._mac = self._samsung_config.mac
        self._uuid = uuid
        # 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

    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._samsung_config)
            self._config.update(dict(iter(self._samsung_config)))


        return self._remote

    def send_key(self, key):
        """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)
                    break
                except (self._exceptions_class.ConnectionClosed,
                        BrokenPipeError):
                    # BrokenPipe can occur when the commands is sent to fast
                    self._remote = None
            self._state = STATE_ON
        except (self._exceptions_class.UnhandledResponse,
                self._exceptions_class.AccessDenied):
            # We got a response so it's on.
            self._state = STATE_ON
            self._remote = None
            _LOGGER.debug("Failed sending command %s", key, exc_info=True)
            return
        except OSError:
            self._state = STATE_OFF
            self._remote = None
        if self._power_off_in_progress():
            self._state = STATE_OFF

    def _power_off_in_progress(self):
        return self._end_of_power_off is not None and \
               self._end_of_power_off > dt_util.utcnow()

    @property
    def unique_id(self) -> str:
        """Return the unique ID of the device."""
        return self._uuid

    @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 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._samsung_config.method != 'legacy':
            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.get_remote().power = False

    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')

    async def async_play_media(self, media_type, media_id, **kwargs):
        """Support changing a channel."""
        if media_type != MEDIA_TYPE_CHANNEL:
            _LOGGER.error('Unsupported media type')
            return

        # media_id should only be a channel number
        try:
            cv.positive_int(media_id)
        except vol.Invalid:
            _LOGGER.error('Media ID must be positive integer')
            return

        for digit in media_id:
            await self.hass.async_add_job(self.send_key, 'KEY_' + digit)
            await asyncio.sleep(KEY_PRESS_TIMEOUT, self.hass.loop)

    def turn_on(self):
        """Turn the media player on."""
        self.get_remote().power = True

@arsaboo

first to answer the question on the config save path.. yes you can specify anywhere you like to save the config data to. I do believe the above code modification may save the information right into the yaml for Home Assistant tho.

next thing.. the errors you are getting are because there is a flaw in the master branch. clone and install the develop branch. I believe i have fixed those issues.

so with the code above. you need to clone and install the develop branch of samsungctl form my fork. the develop branch has the most recent code changes in it.

@kdschlosser Tried your code (after adding the requirement and adding a missing import in __init__) and was able to get it working (haven't tested it extensively yet).

Couple of issues though. After I turned off the TV from inside HA, the status stayed as on even though the TV was turned off. Also, it asks me to Allow every time I restart HA even though I have set it up to ask for permissions only first time. Here's the code.

tho whole section with the defaults for the SCHEMA is different. I think this is what gets used when saving the information to the yaml file. I think that because the "token" parameter and the "paired" parameter in the samsungctl.Config class are not getting stored is the reason why.

if you look at the code i posted above it contains the addition of all of the parameters being set into the schema. your code does not have this getting done. the code block blow shows you what I am talking about. I think that the schema tells the config what to write.

import asyncio
from datetime import timedelta
import logging
import socket

import voluptuous as vol

from homeassistant.components.media_player import (
    MEDIA_TYPE_CHANNEL, PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE,
    SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF,
    SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP,
    MediaPlayerDevice)
from homeassistant.const import (
    CONF_HOST, CONF_MAC, CONF_NAME, CONF_PORT, CONF_TIMEOUT, CONF_ID,
    CONF_METHOD, CONF_TOKEN, STATE_OFF, STATE_ON)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import dt as dt_util


REQUIREMENTS = [
    'https://github.com/kdschlosser/'
    'samsungctl/archive/develop.zip#samsungctl==0.8.0b'
]


_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Samsung TV Remote'
DEFAULT_PORT = 8001
DEFAULT_TIMEOUT = 0
DEFAULT_PAIRED = False
DEFAULT_UPNP_LOCATIONS = None
DEFAULT_METHOD = None
DEFAULT_TOKEN = None
DEFAULT_MAC = None
DEFAULT_ID = None
DEFAULT_DESCRIPTION = socket.gethostname()

def string(value):
    if value is None:
        return value
    else:
        return cv.string(value)

def ensure_list(value):
    if value is None:
        return value
    else:
        return cv.ensure_list(value)


KEY_PRESS_TIMEOUT = 1.2
KNOWN_DEVICES_KEY = 'samsungtv_known_devices'

SUPPORT_SAMSUNGTV = SUPPORT_PAUSE | SUPPORT_VOLUME_STEP | \
    SUPPORT_VOLUME_MUTE | SUPPORT_PREVIOUS_TRACK | \
    SUPPORT_NEXT_TRACK | SUPPORT_TURN_OFF | SUPPORT_PLAY | SUPPORT_PLAY_MEDIA

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_ID, default=DEFAULT_ID): string,
    vol.Optional(CONF_METHOD, default=DEFAULT_METHOD): string,
    vol.Optional(CONF_TOKEN, default=DEFAULT_TOKEN): string,
    vol.Optional(CONF_MAC, default=DEFAULT_MAC): string,
    vol.Optional('paired', default=DEFAULT_PAIRED): cv.boolean,
    vol.Optional('description', default=DEFAULT_DESCRIPTION): cv.string,
    vol.Optional('upnp_locations', default=DEFAULT_UPNP_LOCATIONS): ensure_list,
})

I would also change the requirements to this as I have done in the code block above.

REQUIREMENTS = ['https://github.com/kdschlosser/samsungctl/archive/develop.zip#samsungctl==0.8.0b']

makes visually identifiable that the develop branch is being used.

so here is an updated version of

/homeassistant/components/media_player/samsungtv.py
"""
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 asyncio
from datetime import timedelta
import logging
import socket
import threading

import voluptuous as vol

from homeassistant.components.media_player import (
    MEDIA_TYPE_CHANNEL, PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE,
    SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF,
    SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP, 
    SUPPORT_VOLUME_SET, SUPPORT_SELECT_SOURCE, MediaPlayerDevice)
from homeassistant.const import (
    CONF_HOST, CONF_MAC, CONF_NAME, CONF_PORT, CONF_TIMEOUT, CONF_ID,
    CONF_METHOD, CONF_TOKEN, STATE_OFF, STATE_ON)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import dt as dt_util


REQUIREMENTS = [
    'https://github.com/kdschlosser/'
    'samsungctl/archive/develop.zip#samsungctl==0.8.0b'
]


_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Samsung TV Remote'
DEFAULT_PORT = 8001
DEFAULT_TIMEOUT = 0
DEFAULT_PAIRED = False
DEFAULT_UPNP_LOCATIONS = None
DEFAULT_METHOD = None
DEFAULT_TOKEN = None
DEFAULT_MAC = None
DEFAULT_ID = None
DEFAULT_DESCRIPTION = socket.gethostname()

def string(value):
    if value is None:
        return value
    else:
        return cv.string(value)

def ensure_list(value):
    if value is None:
        return value
    else:
        return cv.ensure_list(value)


KEY_PRESS_TIMEOUT = 1.2
KNOWN_DEVICES_KEY = 'samsungtv_known_devices'

SUPPORT_SAMSUNGTV = (
    SUPPORT_PAUSE |
    SUPPORT_VOLUME_STEP | 
    SUPPORT_VOLUME_MUTE | 
    SUPPORT_PREVIOUS_TRACK | 
    SUPPORT_NEXT_TRACK | 
    SUPPORT_TURN_OFF | 
    SUPPORT_PLAY | 
    SUPPORT_PLAY_MEDIA |
    SUPPORT_VOLUME_SET
)

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_ID, default=DEFAULT_ID): string,
    vol.Optional(CONF_METHOD, default=DEFAULT_METHOD): string,
    vol.Optional(CONF_TOKEN, default=DEFAULT_TOKEN): string,
    vol.Optional(CONF_MAC, default=DEFAULT_MAC): string,
    vol.Optional('paired', default=DEFAULT_PAIRED): cv.boolean,
    vol.Optional('description', default=DEFAULT_DESCRIPTION): cv.string,
    vol.Optional('upnp_locations', default=DEFAULT_UPNP_LOCATIONS): ensure_list,
})

def setup_platform(hass, config, add_entities, 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

    uuid = None
    # Is this a manual configuration?
    if config.get(CONF_HOST) is not None:
        host = config.get(CONF_HOST)

    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
        udn = discovery_info.get('udn')
        if udn and udn.startswith('uuid:'):
            uuid = udn[len('uuid:'):]

        config.update(
            {
                CONF_HOST: host,
                CONF_PORT: port,
                CONF_TIMEOUT: timeout,
                CONF_NAME: name,
                CONF_MAC: mac,
            }
        )
    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_entities([SamsungTVDevice(config, uuid)])
        _LOGGER.info("Samsung TV %s added as '%s'", host, config.get(CONF_NAME))
    else:
        _LOGGER.info("Ignoring duplicate Samsung TV %s", host)


class SamsungTVDevice(MediaPlayerDevice):
    """Representation of a Samsung TV."""

    def __init__(self, config, uuid):
        """Initialize the Samsung device."""
        import samsungctl
        from samsungctl import exceptions
        from samsungctl import Remote

        # Save a reference to the imported classes
        self._exceptions_class = exceptions
        self._remote_class = Remote
        self._samsung_config = samsungctl.Config(**config)
        self._config = config

        self._name = self._samsung_config.name
        self._mac = self._samsung_config.mac
        self._uuid = uuid
        # 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

        # Mark the end of the TV powering on.need to wait 20 seconds before
        # sending any commands.
        self._end_of_power_on = None
        # Generate a configuration for the Samsung library

    def update(self):
        """Update state of device."""

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

        elif self._power_on_in_progress():
            self._state = STATE_ON

        else:
            power = self.get_remote().power
            if power is True:
                self._state = STATE_ON
            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._samsung_config)
            self._config.update(dict(iter(self._samsung_config)))

        return self._remote

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

        elif self._power_on_in_progress():
            _LOGGER.info("TV is powering on, not sending command: %s", key)
            return

        if self._state == STATE_OFF and key not in ('KEY_POWER', 'KEY_POWERON'):
            _LOGGER.info("TV is powered off, not sending command: %s", key)
            return

        self.get_remote().control(key)

    def _power_on_in_progress(self):
        return (
            self._end_of_power_on is not None and
            self._end_of_power_on > dt_util.utcnow()
        )

    def _power_off_in_progress(self):
        return (
            self._end_of_power_off is not None and
            self._end_of_power_off > dt_util.utcnow()
        )

    @property
    def unique_id(self) -> str:
        """Return the unique ID of the device."""
        return self._uuid

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def state(self):
        """Return the state of the device."""
        power = self.get_remote().power
        if power is True:
            self._state = STATE_ON
        else:
            self._state = STATE_OFF

        return self._state

    @property
    def supported_features(self):
        """Flag media player features that are supported."""
        features = SUPPORT_SAMSUNGTV
        if self._samsung_config.method != 'legacy':
            features |= SUPPORT_TURN_ON

        if self._samsung_config.method != 'websocket':
            features |= SUPPORT_SELECT_SOURCE

        return features

    def turn_off(self):
        """Turn off media player."""
        self._end_of_power_off = dt_util.utcnow() + timedelta(seconds=15)
        def do():
            self.get_remote().power = False

        t = threading.Thread(target=do)
        t.daemon = True
        t.start()

    def select_source(self, source):
        """Select input source."""
        self.get_remote().source = source

    @property
    def source(self):
        """Name of the current input source."""
        source = self.get_remote().source
        if source is None:
            source = ''
        else:
            label = source.label
            name = source.name

            if name != label:
                name = label + ':' + name

            source = name
        return source

    @property
    def source_list(self):
        """List of available input sources."""
        sources = self.get_remote().sources

        if sources is None:
            return []
        else:
            result = []
            for source in sources:
                label = source.label
                name = source.name

                if label != name:
                    name = label + ':' + name

                result += [name]

            return result

    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')

    @property
    def volume_level(self):
        """Volume level of the media player scalar volume. 0.0-1.0."""
        volume = self.get_remote().volume
        if volume is None:
            volume = 0.0
        else:
            volume /= 100.0

        return volume

    def set_volume_level(self, volume):
        """Set volume level, convert scalar volume. 0.0-1.0 to percent 0-100"""
        self.get_remote().volume = int(volume * 100)

    def mute_volume(self, mute):
        """Send mute command."""
        self.get_remote().mute = mute

    @property
    def is_volume_muted(self):
        """Boolean if volume is currently muted."""
        return False if not self.get_remote().mute else True

    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')

    async def async_play_media(self, media_type, media_id, **kwargs):
        """Support changing a channel."""
        if media_type != MEDIA_TYPE_CHANNEL:
            _LOGGER.error('Unsupported media type')
            return

        # media_id should only be a channel number
        try:
            cv.positive_int(media_id)
        except vol.Invalid:
            _LOGGER.error('Media ID must be positive integer')
            return

        for digit in media_id:
            await self.hass.async_add_job(self.send_key, 'KEY_' + digit)
            await asyncio.sleep(KEY_PRESS_TIMEOUT, self.hass.loop)

    def turn_on(self):
        """Turn the media player on."""

        if self._samsung_config.mac:
            self._end_of_power_on = dt_util.utcnow() + timedelta(seconds=20)

            def do():
                self.get_remote().power = True

            t = threading.Thread(target=do)
            t.daemon = True
            t.start()
        elif self._samsung_config.method != 'legacy':
            _LOGGER.info(
                "There was a problem detecting the TV's MAC address, "
                "you will have to update the MAC address in the Home "
                "Assistant config file manually."
            )

        else:
            _LOGGER.info(
                "Legacy TV's (2008 - 2013) do not support "
                "being powered on remotely."
            )

I am not running testing any of this as of yet on Home Assistant. I am working off of assumptions from reading the code. so sorry for the repeated testing.

I will also fix the TV state.. give me a few minutes. I will updatee the code above to reflect those changes

I updated the code above. it should fix the issue with the power state.

I also added
direct volume input
direct mute input
source list (if supported by the TV).
getting and setting the source (if supported by the TV).

the above does proper detection of None being returned (TV is off) and handles it properly.
with the volume I am also doing the scalar conversions before setting or returning the volume.

I changed the code so it will handle powering on a little better with logging information if the mac address was not detected properly.

I changed the update routine and removed the constant checking of power state very time a key gets sent. I do not know how often an update cycle is performed. but if the TV is off the key shouldn't get sent anyway so there is no need to do a reduntant check before sending the key.

Sorry if i'm being a total noob/idiot here but tried replacing your code above here with the code in my samsungtv.py file within my hassio installation - custom_components folder but no the card for my tv isn't even showing up and I get a invalid config message.

Shouldn't that work? :)

@kdschlosser I will test the code out in some time (I am out right now and it requires me to Allow on my TV), but if we have to save a config file, we should use the approach used in other components, e.g., Abode. There are other similar components Plex, Ring, Spotify, etc.

@fillilutten here's my config:

  - platform: samsungtv
    host: 192.168.2.252
    name: Living Room TV
    mac: MAC_ADDRESS
    port: 8002
    timeout: 5

@fillilutten here's my config:

  - platform: samsungtv
    host: 192.168.2.252
    name: Living Room TV
    mac: MAC_ADDRESS
    port: 8002
    timeout: 5

Thanks I have the same but 8001 as my port (having a US ks9005 EU 8005) it stated in the docs that I should use port 8001. Hm. Strange. Because it should work just to replace all text/code right?

ok sweet. now I have an example of how to save and load a Samsung specific config file.

I just have to think of a mechanism to be able to specify what TV's to add. The only thing that I guess would be needed is to add an entry into the yaml file for Home Assistant that would have an IP, name and description of the TV.

OK so here is the skinny.. No one seems to be getting this single thing.

the only thing needed for you to get a TV added is the host.. that is all nothing else. let samsungctl do what i coded it to do, figure out all of the rest of the stuff for you. this way there is no confusion to what year TV needs what settings.

this

(having a US ks9005 EU 8005)
means nothing to me. I need FULL model numbers.
example: UN55D8000

I can make an assumption on the US ks9005 one.
UN??KS9005 the ?? is the size of the TV. if it is a K series TV then the connection is going to be a NON SSL websocket connection on port 8001.

- platform: samsungtv
    host: 192.168.2.252
    name: Living Room TV

that is what your yaml settings should look like. DO NOT add anything else it will get done for you automatically. Give me a little bit of time to modify the code again to write the config file for samsungctl instead of trying to alter the yaml file.

@fillilutten I've lost track of how @kdschlosser's code is working currently, but when I was testing earlier versions i had path problems with Hassio. Basically the Hassio version of HA is more locked down and write access is restricted to most folders. I had to modify the new library so the token file was written to the custom_components directory.

Not sure if this is your problem, but something to check out

@Murph24 The config directory is available for components to save the config files (several components do that already).

@kdschlosser once you get the save config done, I can test it out again. Thanks!

DO THIS FIRST

you are going to need to uninstall samsungctl. you can do this from a command prompt (shell)

pip uninstall samsungctl

I have updated some code for samsungctl and the new cod needs to be downloaded. and installed. I really would prefer if you also installed it from the command line using

pip install --no-cache-dir "https://github.com/kdschlosser/samsungctl/archive/develop.zip#samsungctl==0.8.0b"

this will make sure it gets installed without using a cached copy of it that may be on your system

ok here is an updated version of the code. this is going to write the config information to a directory called samsung_tv that is located in the Home Assistant config folder. the config files for the TVs are going to be named using the ip address you supply in the Home Assistant config yaml file.

when using this code this is what you need to have in the Home Assistant config file

- platform: samsungtv
    host: 192.168.2.252
    name: Living Room TV

optionally

- platform: samsungtv
    host: 192.168.2.252
    name: Living Room TV
    description: description of TV

you will ONLY WANT TO USE THIS if there is a detection problem for the connection type

- platform: samsungtv
    host: 192.168.2.252
    name: Living Room TV
    method: websocket

if you have to specify the connection method this is how they break down.

TV model number example: UN55D8000
[U] = panel type
[N] = region
[55] = size
[D] = model year
[8000] = series or "trim"

it is the model year we care about,

H and J model years you need to enter encrypted for the method.
K and above you need to enter websocket
all others enter legacy

YOU WILL ONLY DO THE ABOVE IF THERE IS AN ISSUE DETECTING THE TV CONNECTION.

Here is the updated code. If you state anything about "custom-componnts" or if i see that in any of the errors I am not going to answer you. this is because you have modified the code. and it is a pretty good chance that your modification is what is causing the problem.

This is a replacement for the /homeassistant/components/media_player/samsungtv.py file
please do not edit the code and then report an issue. only report problems relating to this code. also do not provide vague errors. like it says config error.. I am willing to bet the rror stats more then "config error". I need a copy of the error message in it's entirety. not little bits and pieces. because of the nature of Home Assistant you may need to scroll back in the logs and read for a bit to make sure that you have grabbed all of the relevant log messages.

If you do not do the above then I have no way of helping to solve any issues.

"""
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 asyncio
from datetime import timedelta
import logging
import socket
import threading
import os

import voluptuous as vol

from homeassistant.components.media_player import (
    MEDIA_TYPE_CHANNEL, PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE,
    SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF,
    SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_STEP,
    SUPPORT_VOLUME_SET, SUPPORT_SELECT_SOURCE, MediaPlayerDevice)
from homeassistant.const import (
    CONF_HOST, 
    CONF_NAME,
    CONF_METHOD, 
    STATE_OFF, 
    STATE_ON
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import dt as dt_util


REQUIREMENTS = [
    'https://github.com/kdschlosser/'
    'samsungctl/archive/develop.zip#samsungctl==0.8.0b'
]

SAMSUNG_CONFIG_PATH = 'samsung_tv'


_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Samsung TV Remote'
DEFAULT_DESCRIPTION = socket.gethostname()

CONF_DESCRIPTION =  'description'

KEY_PRESS_TIMEOUT = 1.2
KNOWN_DEVICES_KEY = 'samsungtv_known_devices'

SUPPORT_SAMSUNGTV = (
    SUPPORT_PAUSE |
    SUPPORT_VOLUME_STEP |
    SUPPORT_VOLUME_MUTE |
    SUPPORT_PREVIOUS_TRACK |
    SUPPORT_NEXT_TRACK |
    SUPPORT_TURN_OFF |
    SUPPORT_PLAY |
    SUPPORT_PLAY_MEDIA |
    SUPPORT_VOLUME_SET
)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST): cv.string,
    vol.Optional(CONF_METHOD): cv.string
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_DESCRIPTION, default=DEFAULT_DESCRIPTION): cv.string,
})

def setup_platform(hass, config, add_entities, 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

    config_path = hass.config.path(SAMSUNG_CONFIG_PATH)

    if not os.path.exists(config_path):
        os.mkdir(config_path)

    uuid = None
    # Is this a manual configuration?
    if config.get(CONF_HOST) is not None:
        host = config.get(CONF_HOST)
        name = config.get(CONF_NAME)
        description = config.get(CONF_DESCRIPTION)
        method = config.get(CONF_METHOD)

    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)
        description = DEFAULT_DESCRIPTION
        method = None
        udn = discovery_info.get('udn')
        if udn and udn.startswith('uuid:'):
            uuid = udn[len('uuid:'):]
    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_entities(
            [SamsungTVDevice(host, name, description, method, uuid, config_path)]
        )
        _LOGGER.info("Samsung TV %s added as '%s'", host, config.get(CONF_NAME))
    else:
        _LOGGER.info("Ignoring duplicate Samsung TV %s", host)


class SamsungTVDevice(MediaPlayerDevice):
    """Representation of a Samsung TV."""

    def __init__(self, host, name, description, method, uuid, config_path):
        """Initialize the Samsung device."""
        import samsungctl
        from samsungctl import exceptions
        from samsungctl import Remote

        # Save a reference to the imported classes
        self._exceptions_class = exceptions
        self._remote_class = Remote

        self._config = samsungctl.Config.load(config_path)(
            host=host,
            name=name,
            description=description,
            method=method,
        )

        self._config = samsungctl.Config()

        self._name = self._config.name
        self._mac = self._config.mac
        self._uuid = uuid
        # 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

        # Mark the end of the TV powering on.need to wait 20 seconds before
        # sending any commands.
        self._end_of_power_on = None
        # Generate a configuration for the Samsung library

    def update(self):
        """Update state of device."""

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

        elif self._power_on_in_progress():
            self._state = STATE_ON

        else:
            power = self.get_remote().power
            if power is True:
                self._state = STATE_ON
            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)
            self._remote.open()
            self._config.save()

        return self._remote

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

        elif self._power_on_in_progress():
            _LOGGER.info("TV is powering on, not sending command: %s", key)
            return

        if self._state == STATE_OFF and key not in ('KEY_POWER', 'KEY_POWERON'):
            _LOGGER.info("TV is powered off, not sending command: %s", key)
            return

        self.get_remote().control(key)

    def _power_on_in_progress(self):
        return (
            self._end_of_power_on is not None and
            self._end_of_power_on > dt_util.utcnow()
        )

    def _power_off_in_progress(self):
        return (
            self._end_of_power_off is not None and
            self._end_of_power_off > dt_util.utcnow()
        )

    @property
    def unique_id(self) -> str:
        """Return the unique ID of the device."""
        return self._uuid

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def state(self):
        """Return the state of the device."""
        power = self.get_remote().power
        if power is True:
            self._state = STATE_ON
        else:
            self._state = STATE_OFF

        return self._state

    @property
    def supported_features(self):
        """Flag media player features that are supported."""
        features = SUPPORT_SAMSUNGTV
        if self._config.method != 'legacy':
            features |= SUPPORT_TURN_ON

        if self._config.method != 'websocket':
            features |= SUPPORT_SELECT_SOURCE

        return features

    def turn_off(self):
        """Turn off media player."""
        self._end_of_power_off = dt_util.utcnow() + timedelta(seconds=15)
        def do():
            self.get_remote().power = False

        t = threading.Thread(target=do)
        t.daemon = True
        t.start()

    def select_source(self, source):
        """Select input source."""
        self.get_remote().source = source

    @property
    def source(self):
        """Name of the current input source."""
        source = self.get_remote().source
        if source is None:
            source = ''
        else:
            label = source.label
            name = source.name

            if name != label:
                name = label + ':' + name

            source = name
        return source

    @property
    def source_list(self):
        """List of available input sources."""
        sources = self.get_remote().sources

        if sources is None:
            return []
        else:
            result = []
            for source in sources:
                label = source.label
                name = source.name

                if label != name:
                    name = label + ':' + name

                result += [name]

            return result

    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')

    @property
    def volume_level(self):
        """Volume level of the media player scalar volume. 0.0-1.0."""
        volume = self.get_remote().volume
        if volume is None:
            volume = 0.0
        else:
            volume /= 100.0

        return volume

    def set_volume_level(self, volume):
        """Set volume level, convert scalar volume. 0.0-1.0 to percent 0-100"""
        self.get_remote().volume = int(volume * 100)

    def mute_volume(self, mute):
        """Send mute command."""
        self.get_remote().mute = mute

    @property
    def is_volume_muted(self):
        """Boolean if volume is currently muted."""
        return False if not self.get_remote().mute else True

    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')

    async def async_play_media(self, media_type, media_id, **kwargs):
        """Support changing a channel."""
        if media_type != MEDIA_TYPE_CHANNEL:
            _LOGGER.error('Unsupported media type')
            return

        # media_id should only be a channel number
        try:
            cv.positive_int(media_id)
        except vol.Invalid:
            _LOGGER.error('Media ID must be positive integer')
            return

        for digit in media_id:
            await self.hass.async_add_job(self.send_key, 'KEY_' + digit)
            await asyncio.sleep(KEY_PRESS_TIMEOUT, self.hass.loop)

    def turn_on(self):
        """Turn the media player on."""

        if self._config.mac:
            self._end_of_power_on = dt_util.utcnow() + timedelta(seconds=20)

            def do():
                self.get_remote().power = True

            t = threading.Thread(target=do)
            t.daemon = True
            t.start()
        elif self._config.method != 'legacy':
            _LOGGER.info(
                "There was a problem detecting the TV's MAC address, "
                "you will have to update the MAC address in the Home "
                "Assistant config file manually."
            )

        else:
            _LOGGER.info(
                "Legacy TV's (2008 - 2013) do not support "
                "being powered on remotely."
            )

please move all chatter about testing the replacement for samsungtv.py to #20795. w are kind of off topic using this issue to discuss this. and there also seems to be quite a but of confusion as to what is going on.

Hi, I just have a quick question. I installed the samsungctl library using terminal, and just want to know how do I actually use that code you wrote. Where do I save it, how do I use it etc. Thanks in advance.

Hi, I just have a quick question. I installed the samsungctl library using terminal, and just want to know how do I actually use that code you wrote. Where do I save it, how do I use it etc. Thanks in advance.

Did you do this with a hass.io install?

I tried to install samsungctl on raspbian (without home assistant) but doesn't works...
My TV is J5500, @pablolassalle youcan use samsunctl without HA?

I obtain different errors:

samsungctl --host 192.168.1.81 --name myremote KEY_VOLDOWN

  • Unable to pair with TV.. Is the TV on?!?
    samsungctl --host 192.168.1.81 --name myremote KEY_VOLDOWN --method encrypted
  • Unable to power on the TV, check network connectivity

I have samsungctl 0.8.0b

If I don't make a mistake, exists a problem with the integration between HA and samsungctl, but for linux directly samsungctl shoult works fine, right?

What is the full command (with flags) to pais with TV J5500 ?

Thank you.

Failed to call service media_player/turn_off. {'event': 'ms.channel.unauthorized'}

I got this as well when pressing the on/off.

Samsung Tv Nu8000 (2018)

media_player:
  - platform: samsungtv
    host: xxx.xxx.xxx.xxx
    port: 8001
    name: Samsung TV
    timeout: 30
    mac: 64:1c:ae:11:14:d5

Failed to call service media_player/turn_off. {'event': 'ms.channel.unauthorized'}

I got this as well when pressing the on/off.

Samsung Tv Nu8000 (2018)

media_player:
  - platform: samsungtv
    host: xxx.xxx.xxx.xxx
    port: 8001
    name: Samsung TV
    timeout: 30
    mac: 64:1c:ae:11:14:d5

I get the same error. My configuration is:

 media_player:
   - platform: samsungtv
    name: Samsung UE65NU7402UXXH
    host: XXX.XXX.XXX.XXX

I am running hass.io 0.90.1 on a HassOs VDI VM.

I tried what @kdschlosser said and ran:
pip install --no-cache-dir "https://github.com/kdschlosser/samsungctl/archive/develop.zip#samsungctl==0.8.0b"
But I got the errors below:

    gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Os -fomit-frame-pointer -g -Os -fomit-frame-pointer -g -Os -fomit-frame-pointer -g -DTHREAD_STACK_SIZE=0x100000 -fPIC -DCYTHON_CLINE_I
N_TRACEBACK=0 -Isrc -Isrc/lxml/includes -I/usr/include/python3.6m -c src/lxml/etree.c -o build/temp.linux-x86_64-3.6/src/lxml/etree.o -w
    unable to execute 'gcc': No such file or directory
    Compile failed: command 'gcc' failed with exit status 1
    creating tmp
    cc -I/usr/include/libxml2 -c /tmp/xmlXPathInitmq54ywst.c -o tmp/xmlXPathInitmq54ywst.o
    unable to execute 'cc': No such file or directory
    *********************************************************************************
    Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
    *********************************************************************************
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-vfa_ezp9/lxml/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exe
c(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-1i2skgu6/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-vfa_ezp9/lxml/

Next I tried installing libxml2 and libxslt with sudo apt-get install libxml2-dev libxslt1-dev but then noticed apt-get isn't available on HassOs.
I tried getting the libs and doing a manual install but make also seems to be unavailable.

So the end result is that I can see the TV ON and OFF states without a problem but everything else (mute, unmute, current mute state, , volume up/down, channel up/down) fails.

Try changing the port to 8002 as I think your model is probably using websockets which is on port 8002. @arsaboo I'm double checking the version of the code I grabed. I think i grabed the master branch when I set this up. I am also running hassio, are you running with hassio or just running homeassistant? I am in the process of spinning up a dev environment of homeassistant so I can make modifications to the component.

Yes, I am testing this on Hassio. I am using 8002. Let me try with the master branch.

I just got some errors apparently I hadn't updated my code in a month on my home assistant :( on/off is all that works on mine also with the latest master branch.

Yeah, with the current master branch, I can see the state.

Edit: It is not turning the tv off for me.
Edit 2: The state is also not correctly being reported. I guess we need to make the develop branch work. That has a lot of additional fixes.

Hi,

I've been out of the loop for a while now. Coming back to see how progress
is going. Are we being asked to use development or master for a potentially
fully working solution? Also can someone confirm what component need to be
installed for an rpi hassio home assistant integration. Cheers.

On Thu, 28 Mar 2019, 10:18 Alok Saboo, notifications@github.com wrote:

Yeah, with the current master branch, I can see the state.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/issues/17802#issuecomment-477383241,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABNw5D3jzMrJcfsXCAXuvq-sAQY6fuJUks5va_xVgaJpZM4X7co9
.

I have a ES8000 from 2012 and this is also affecting my deployment of 0.90.2. Mine always reports when the TV turns on OK, but if I use Samsung's SmartHub then HA reports the TV has switched off!

I have a ES8000 from 2012 and this is also affecting my deployment of 0.90.2. Mine always reports when the TV turns on OK, but if I use Samsung's SmartHub then HA reports the TV has switched off!

@gr4z I also have an ES8000 but I do not have a Samsung's SmartHub. I've had trouble getting the TV into HA. Would you mind sharing your config?

+1 No controls working for me. UE50F6670 (2014 model I think?). Tried port 5001, 5000, 8001, 8002.
Open ports on the TV are [80,443,4443,6000,7676,52345,55000,55001]
Error logs have a bunch of "Access Denied". I've looked in the TV settings and I can''t see anything to help get the TV connected.

You should be using a legacy connection on port 55000. TV's from 2011 to 2013 (C to F)
2014 & 2015 (H and J) use port 8001 with a websocket connection. the data send over the wensocket connection is encrypted using the Rijndael cypher.
2016 (M) TV's use port 8001 with just a plain ol websocket connection.
2017 to present depending on the installed firmware the connection can either be a pain websocket connection or it can be a token based encrypted websocket connection.

The reason why you are probably not able to connect is because the TV has reached the maximum number of devices it can pair with. You need to clean the list out. It is in one of the menus. It is going to have a name that makes no sense. So be sure to check everything. once you find the list delete the pairing that are no longer being used.

The other thing that can cause a connection issue is a special character in either the name or in the description that the TV does not like.

The 2 things above will not cause a typical connection failure of the library. the TV simply does not respond. so there is no real way to rais an exception when the TV is acting like everything is good.

@zlatkosh

this can be corrected by getting a copy of lxml from someone that is not running HASS's OS image. so if someone that is running on a Raspberry Pi (I thnk this is what the OS image is made for) could do a favor and locate the copy of lxml that has been installed and zip it up and post it here. all you need do is decompress it into the HASS site-packages folder.

lxml uses C code. because of the large amounts of data that gets sent/received from the TV that is in XML format I thought it would be wise to use lxml instead of the builtin xml.etree. The only downfall of using lxml is it has to be compiled for the OS and the device,. so my copy of lxml would not work for you (Windows).

@kdschlosser I can now get my 2012 ES8000 to show up in Home Assistant. I can turn it off, but I can't turn it back on. Any thoughts?

I am still working on the library. My suggestion is to use the develop branch of my repo. It has the most up to date code. I usually make 2-3 changes a day sometimes more,

I am still trying to hammer out the power portion of the program.

I seem to have broke the portion of the program that handles the encrypted TV's (H and J - 2014 & 2015) I am not sure when I broke it. I am going to have to have someone with one of those TV's to go back in the commit history and try each and every one until it works again. then I will be able to compare the code. So until that time the H and J TV's are not going to work correctly.

I have a ES8000 from 2012 and this is also affecting my deployment of 0.90.2. Mine always reports when the TV turns on OK, but if I use Samsung's SmartHub then HA reports the TV has switched off!

@gr4z I also have an ES8000 but I do not have a Samsung's SmartHub. I've had trouble getting the TV into HA. Would you mind sharing your config?

Not much to it really. Give the TV a static IP and then use the samsungtv plugin for HA. I don't set a MAC address. It has been working well for 2 years but now I am suffering this issue when using SmartHub. I dont tend to use it very often as I have a AppleTV but when I do, HA reports the TV has switched off.

@kdschlosser I can now get my 2012 ES8000 to show up in Home Assistant. I can turn it off, but I can't turn it back on. Any thoughts?

I have never been able to turn the TV on with HA, only turn it off.

2012 TV's do not support being powered on over the network.

if you are using a Raspberry Pi i did build into the library CEC power controls. this will power the TV back on. so long as the Pi you have has a CEC chip built into it

hello to all
i have a samsung TV and i can turn it off and change volume. i am on port 8001 and with mac adress assigned. what can i do for making possible to turn it on also?

Hey guys, what's the latest development on this?

I have a 2018 mu8000 and all I can get is the status of the TV but no controls work.

I have scanned with NMAP and ports 8001, 8002, 8080, 9080, 9110, 9999, 32768, 32769 are all open. I've tried ports 8001 and 8002 but no luck

All I need is for HA to detect when media is playing on the TV. The rest I have my Broadlink that can send IR

What was funny is the NMAP software wrote TCP Sequence Prediction: Difficulty=260 (Good luck!) lol

Thank you

Hi guys, i have a samsung UE40NU7180U connected to the network via wifi and with a static ip. I am using the 8001 port and i can only turn it on with hassio. Tried with 8002 port’s but nothing. Any suggestion?

Solution proposed by @kdschlosser in Ape/samsungctl#93 works for me with MU6199 but it requires modification of samsungtv component, specifically where websocket method is only used if you specify 8001 port but reverts to legacy for any other value.

Solution proposed by @kdschlosser in Ape/samsungctl#93 works for me with MU6199 but it requires modification of samsungtv component, specifically where websocket method is only used if you specify 8001 port but reverts to legacy for any other value.

Thank you, how do I install the modified library if I'm running Hass.io?

Thank you, how do I install the modified library if I'm running Hass.io?

I'm not running HASS.IO but I got that working using custom_components:

  1. Copy the samsungctl folder from the modified version of the library under your /config/custom_components/ path
  2. Do the same for samsungtv component with my patch above.
  3. Change samsungtv/media_player.py file's import statement for samsungctl library to use custom_components' version:
    """Initialize the Samsung device.""" from custom_components.samsungctl import exceptions from custom_components.samsungctl import Remote
    A side note for those wishing to do the same: I run HA dockerized under a non-root user and @eclair4151's code depends on token.txt file created in library's folder - if your user lacks write permissions, you'll be continuously prompted by your TV to allow pairing. Solution for me was to run samsungctl command under root manually once to generate the file and afterwards it all just works. Not sure if this file will need to be updated later down the road but we shall see.

hi there. what is this mod solving? thanks a lot

@2sheds Which samsungctl branch are you using? The latest develop branch is not working for me.

So I finally got it working now with @2sheds solution, thanks!

Is there a way HA can know when media starts playing? For example Plex or Netflix?
I'd like to automate light dimming etc

@sirs2k can you indicate which samsungctl branch (and commit) are you using?

@sirs2k can you indicate which samsungctl branch (and commit) are you using?

Hi @arsaboo to be honest I fiddled around with the settings a lot till I got it working!
So the best I can do is to share with you what I have and you can use it.
I also had to change if config["timeout"] == x to if config["timeout"] == 5 in remote_websocket.py
Extract these 2 folders to your custom_components folder via WinSCP
https://mega.nz/#!Np01iAgT!DCl9pvl7sZ1odxrsh68R7Dcd2UN9uxScVXBuCNBdyJ8

Include this in your configuration.yaml

media_player:

  - platform: samsungtv
    name: Cinema TV
    host: 192.168.1.118
    mac: xx:xx:xx:xx:xx
    port: 8002

Now have your TV ON when you restart HA and the TV should ask you to Allow HomeAssistant.
Press Allow. If it doesn't ask, try to press any button on HA's frontend to control the TV

You'll know if it's working by looking at the token.txt inside samsungctl folder. There will be an 8 digit token number in there.

This working for my NU8000 (2018) model on latest FW
Though it's not showing HA if it is playing anything or it's idle which is my next problem

Hope you get this working my friend

@sirs2k I have the same TV, so I am hoping I get it working. When I try to download the folder, it asks for a Decryption Key. Can you upload the files elsewhere...thanks!

Does anyone has a H or J model? I can't get it to work.

@arsaboo sorry I've updated the post with the right link now

@sirs2k So, it works, but for some reason, the TV keeps turning on. I turn it off and it turns on by itself.

@sirs2k I confirm it work on my QE65Q8FAMT 2018.
Volume controls work, along with power on/off and source selection.

I have a J model Samsung TV and I'm having issues with 'error: connection refused'. In researching this issue I came across this thread, but it's hard to follow the 140+ comments to figure out what the answer is.

Could someone summarize the solution here? I'm just trying to test out samsungctl - I don't use HomeAssistant right now.

Thanks @sirs2k, it works exacly as described :)

Cheers @sirs2k, working on a 2018 65" Frame. Still have trouble with art mode, but will have a play around.

So, just a side-node... this works... kinda. Having the token saved to token.txt has one big issue: If you have multiple Samsung TVs, the whole thing breaks down.

So, just a side-node... this works... kinda. Having the token saved to token.txt has one big issue: If you have multiple Samsung TVs, the whole thing breaks down.

Yep, my other (older) samsung's communication is now broken.
It's really interesting how there hasn't been much traction from the developers regarding this issue although it's up to 146 comments!

I would like to add some from my investigation.
I'm running 0.95.4 and using an older 2012 Samsung TV.

The only issue I have is that the when the TV is turned ON with the Media Player also showing ON, only after a few minutes the Media Player's power state goes from ON to OFF even though the TV is still powered ON.

What seems to be the problem for me is the periodic sending of the remote code "KEY" to test for connectivity. When the TV is ON, sending "KEY" will sometimes fail with a socket timeout waiting to receive and this in turn causes the state to change to OFF. If I change to some other remote code that does nothing, specifically I'm testing with remote code "KEY_CUSTOM", then my problem seems to be solved. I've only been running it this way for a couple of days on and off, but it seems to work fine.

@sirs2k Thanks for so much posting that. I am able to turn off my TV, change volume, and play/pause. The only thing I don't have is power on. This in on a 2019 Q70RAFXZA. Still better than I was before though.

with 0.96.4 TV stop working :( no status and ext. with last version (0.96.3) everything word TV 2018 year

Wed Jul 24 2019 14:11:36 GMT+0300 (Москва, стандартное время)
Update for media_player.samsung_tv_remote fails
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/websocket/_socket.py", line 81, in recv
    bytes_ = sock.recv(bufsize)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 221, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 380, in async_device_update
    await self.hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/components/samsungtv/media_player.py", line 130, in update
    self.send_key("KEY")
  File "/usr/src/homeassistant/homeassistant/components/samsungtv/media_player.py", line 151, in send_key
    self.get_remote().control(key)
  File "/usr/src/homeassistant/homeassistant/components/samsungtv/media_player.py", line 136, in get_remote
    self._remote = self._remote_class(self._config)
  File "/usr/local/lib/python3.7/site-packages/samsungctl/remote.py", line 11, in __init__
    self.remote = RemoteWebsocket(config)
  File "/usr/local/lib/python3.7/site-packages/samsungctl/remote_websocket.py", line 28, in __init__
    self.connection = websocket.create_connection(url, config["timeout"])
  File "/usr/local/lib/python3.7/site-packages/websocket/_core.py", line 511, in create_connection
    websock.connect(url, **options)
  File "/usr/local/lib/python3.7/site-packages/websocket/_core.py", line 223, in connect
    self.handshake_response = handshake(self.sock, *addrs, **options)
  File "/usr/local/lib/python3.7/site-packages/websocket/_handshake.py", line 79, in handshake
    status, resp = _get_resp_headers(sock)
  File "/usr/local/lib/python3.7/site-packages/websocket/_handshake.py", line 150, in _get_resp_headers
    status, resp_headers, status_message = read_headers(sock)
  File "/usr/local/lib/python3.7/site-packages/websocket/_http.py", line 298, in read_headers
    line = recv_line(sock)
  File "/usr/local/lib/python3.7/site-packages/websocket/_socket.py", line 102, in recv_line
    c = recv(sock, 1)
  File "/usr/local/lib/python3.7/site-packages/websocket/_socket.py", line 84, in recv
    raise WebSocketTimeoutException(message)
websocket._exceptions.WebSocketTimeoutException: timed out

@sandteufel Have you tried applying the files from sirs2k's post? I have a 2019 and out worked after the update. May be worth a shot if you haven't tried that already.

I'm also having issues since 0.96.x ...the files/fix from @sirs2k worked for me 👍

Me too, the solution proposed from @sirs2k is actually working !

@sirs2k any suggestions on this error?

websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.

Does anyone know, when this changes will be included to the home-assistant master ?

The solution proposed from @sirs2k is working except I still get the warning:
WARNING (MainThread) [homeassistant.helpers.entity] Update of media_player.samsungtv is taking over 10 seconds. I see some earlier threads - [https://github.com/home-assistant/home-assistant/issues/6383] that propose a fix for this, but it does not appear to included in @sirs2k code.

Also on a NU8000, @sirs2k's solution doesn't seem to be working for me. The token.txt doesn't seem to be populated. I copied the YAML exactly as shown and changed MAC and IP. Anything before or after the media_player section which may be relevant?

I'm running HA using docker-compose, it doesn't seem to be a write permissions issue.

Can I run samsungctl manually and then copy a working token into token.txt? If so, how?

Also, I'm seeing the same errors as @slomanl1.

EDIT: Somehow after a reboot of the host machine, it suddenly started working. Thanks to all the helpful comments.

@ sirs2k puoi indicare quale samsungctlramo (e commit) stai usando?

Ciao @arsaboo, a dire il vero, ho armeggiato un sacco con le impostazioni fino a quando non ho funzionato!
Quindi il meglio che posso fare è condividere con te ciò che ho e puoi usarlo.
Ho anche dovuto cambiare if config["timeout"] == xa if config["timeout"] == 5in remote_websocket.py
estratto queste 2 cartelle alla custom_componentscartella tramite WinSCP
https://mega.nz/#!Np01iAgT!DCl9pvl7sZ1odxrsh68R7Dcd2UN9uxScVXBuCNBdyJ8

Includilo nel tuo configuration.yaml

media_player:

  - platform: samsungtv
    name: Cinema TV
    host: 192.168.1.118
    mac: xx:xx:xx:xx:xx
    port: 8002

Ora accendi la TV quando riavvii HA e la TV dovrebbe chiederti di consentire HomeAssistant.
Premi Consenti. Se non viene richiesto, prova a premere un pulsante qualsiasi sul frontend di HA per controllare la TV

Saprai se funziona guardando la cartella token.txtinterna samsungctl. Ci sarà un numero di token di 8 cifre lì dentro.

Questo funziona per il mio modello NU8000 (2018) sull'ultimo FW
Anche se non mostra HA se sta giocando qualcosa o è inattivo che è il mio prossimo problema

Spero che questo funzioni, amico mio

**Thank you! Almost everything works on the UE40MU6400 model. but .. Channel change does not work. Is that so with you too?
it works if I call the service media_player.play_media:
{
"entity_id": "media_player.tv_samsung"
"media_content_id": "5",
"media_content_type": "channel"
}

every time I call the service it changes me on channel 5 so it works. but I would like to integrate a "back and forth" channel change in overview with a script. but I failed.**

I've tested the mega.nz package and it works as expected. It doesn't scale after one TV set.

@sirs2k can you indicate which samsungctl branch (and commit) are you using?

Hi @arsaboo to be honest I fiddled around with the settings a lot till I got it working!
So the best I can do is to share with you what I have and you can use it.
I also had to change if config["timeout"] == x to if config["timeout"] == 5 in remote_websocket.py
Extract these 2 folders to your custom_components folder via WinSCP
https://mega.nz/#!Np01iAgT!DCl9pvl7sZ1odxrsh68R7Dcd2UN9uxScVXBuCNBdyJ8

Include this in your configuration.yaml

media_player:

  - platform: samsungtv
    name: Cinema TV
    host: 192.168.1.118
    mac: xx:xx:xx:xx:xx
    port: 8002

This is Working for my Samsung UN65NU7200 on port 8002. Thank you @sirs2k!!!
HomeAssistant 0.96.5 installed in Python Virtual Environment.

I can confirm that it is working with a Q9FN TV (firmware 1260) and HomeAssistant 0.97.2

I hope someone could merge this with the official component!

Thanks for your effort @sirs2k <3

@FireAcidAP What tv features are you able to control through hassio?

Downloaded the custom component above but I don't get any notifications on either of my Samsung TVs. UE55NU7100. HA can detect the TV see that it's on, but when I do anything i get an unauthorized error through home assistant yet nothing pops up on the TV itself to allow the connection.

@FireAcidAP What tv features are you able to control through hassio?

@nmsoares I can control Power On/Off, Mute, Volume UP/Down, Rewind/FastForward, Play/Pause and Channel selection by calling media_player.play_media service with the following JASON:

{
  "entity_id": "media_player.samsung_smart_tv",
  "media_content_id": "26",
  "media_content_type": "channel"
}

My Configuration:

media_player:
  - platform: samsungtv
    name: 'Samsung Smart TV'
    host: [IP ADDRESS]
    port: 8002
    mac: [MAC ADDRESS]

The only thing i can't figure out, is how to change channel with sub channel (ex. 4-1, 26-2) as I have digital over-the-air antena.

@pegatron89 On your TV, see if the _Settings > General > External Devices > Device Connection Manager > Access Notification_ is NOT set to OFF and _Settings > General > External Devices > Device Connection Manager > Device List > HomeAssitant (if exists)_ is NOT set to DENY. Hope that helps.

Checked that @FireAcidAP thanks, all looks ok - I can see the tv in home assistant (It knows when its on or off), As soon as i press power or volume i get an unauthorised error on HA but nothing on my TV to allow or deny.

On my other samsung TV i get the following error:
websocket._exceptions.WebSocketProtocolException: Invalid close opcode.
and the pop-up keeps asking me to allow or deny every few seconds

@sirs2k can you indicate which samsungctl branch (and commit) are you using?

Hi @arsaboo to be honest I fiddled around with the settings a lot till I got it working!
So the best I can do is to share with you what I have and you can use it.
I also had to change if config["timeout"] == x to if config["timeout"] == 5 in remote_websocket.py
Extract these 2 folders to your custom_components folder via WinSCP
https://mega.nz/#!Np01iAgT!DCl9pvl7sZ1odxrsh68R7Dcd2UN9uxScVXBuCNBdyJ8
Include this in your configuration.yaml

media_player:

  - platform: samsungtv
    name: Cinema TV
    host: 192.168.1.118
    mac: xx:xx:xx:xx:xx
    port: 8002

This is Working for my Samsung UN65NU7200 on port 8002. Thank you @sirs2k!!!
HomeAssistant 0.96.5 installed in Python Virtual Environment.

I can also confirm this working for UE55NU8009 on port 8002. On/Off state is a little fussy if you toggle the power state in a very rapid succession. But it's better than nothing :)

Checked that @FireAcidAP thanks, all looks ok - I can see the tv in home assistant (It knows when its on or off), As soon as i press power or volume i get an unauthorised error on HA but nothing on my TV to allow or deny.

On my other samsung TV i get the following error:
websocket._exceptions.WebSocketProtocolException: Invalid close opcode.
and the pop-up keeps asking me to allow or deny every few seconds

Remember to grant proper rights to folders and files in custom_components. I had simillar issue (pop-up keeps asking me on tv to grant permission) and I had to change owner/group to homeassistant of this folders and files.

@tomasz8w thank you! Cannot believe i didn't check my permissions. Both TV's are working now

HA can set the volume / mute on both, Can also turn off both TVs but cant bring them back on again. They are on WiFi though.. Would that matter? Can also change the source as well. Source only has TV and HDMI. But it can cycle through them.

Weird thing, My ue55nu7100 has not asked for permission.. yet HA can still control the volume, Nothing in the list of allowed devices at all.

@tomasz8w thank you! Cannot believe i didn't check my permissions. Both TV's are working now

HA can set the volume / mute on both, Can also turn off both TVs but cant bring them back on again. They are on WiFi though.. Would that matter? Can also change the source as well. Source only has TV and HDMI. But it can cycle through them.

Weird thing, My ue55nu7100 has not asked for permission.. yet HA can still control the volume, Nothing in the list of allowed devices at all.

Did you provide mac address in your configuration file? Otherwise you can't turn it on.

I noticed when tv is turned on, power status in HA seems to be OK, but when it's off, it's a mess when using this solution. @tommyjlong changing KEY to KEY_CUSTOM resolved your issue with power status?

HA can set the volume / mute on both, Can also turn off both TVs but cant bring them back on again. They are on WiFi though.. Would that matter?

Yes, that's the culprit. The integration uses Wake on LAN which is not supported via WiFi because the TV doesn't maintain a WiFi link when off.

Working great on my qled q9f 2018 model.

How can I use two tv’s with this? Can I rename something for a second custom component?

changing KEY to KEY_CUSTOM resolved your issue with power status?

@tomasz8w My solution helps a lot when the TV is ON. Using KEY_CUSTOM (or KEY_anything) prevents the component from getting connection errors when the TV is turned ON. When my Samsung TV is turned off, its like the TV's LAN port is disabled and connection errors occur as a normal OFF process.

When my Samsung TV is turned off, its like the TV's LAN port is disabled and connection errors occur as a normal OFF process.

Well, it's look like that my TV is not disabling itself completely. I am able to ping and turn it on with HA.

When my Samsung TV is turned off, its like the TV's LAN port is disabled and connection errors occur as a normal OFF process.

Well, it's look like that my TV is not disabling itself completely. I am able to ping and turn it on with HA.

I've observed this behavior with my TV (NU8009) as well, but only for a certain period of time after it has been turned off.
I supsect the TV's UI is schowing it's off, but in reality the services are still running. After approximately 10 minutes, pinging tunring on via sending a key fails. I can then only wake it up via WoL.

Power state detection with newer Samsung TVs is a pain. It is perfectly implemented in SmartThings (works fine via the app), but I can't get my hands on the source code...

Unfortunately I can't get my UE40EH5300 to work with the custom component :( Tried both port 8001 & 8002. Keeps showing the state is off :(
It seems everytime I restart Hass it comes up as unknwon and then goes to off.

What seems to be the problem for me is the periodic sending of the remote code "KEY" to test for connectivity. When the TV is ON, sending "KEY" will sometimes fail with a socket timeout waiting to receive and this in turn causes the state to change to OFF. If I change to some other remote code that does nothing, specifically I'm testing with remote code "KEY_CUSTOM", then my problem seems to be solved. I've only been running it this way for a couple of days on and off, but it seems to work fine.

Is that line 130 in media_player.py?
Should that KEY_CUSTOM also be somewhere in the mappings? I can't find it mentioned in any of the files of @sirs2k's custom component

Unfortunately I can't get my UE40EH5300 to work with the custom component :( Tried both port 8001 & 8002. Keeps showing the state is off :(
It seems everytime I restart Hass it comes up as unknwon and then goes to off.

@spudje Did you try it with the default component from home assistant? The EH5300 is a 2012 model and not using any of the new websocket protocols. I had an ES5700 from the same year which is basically the same on the software side and it used to work with the default component. You won't be able to turn the TV on through the component though, because these eraly models do not support Wake-on-LAN.
I worked around this by attaching the TV to a smart plug and setting it to turn when power returns after a power loss through the service menu. You use the smart plug to cut power to the TV when you want to turn it off. When you turn the plug on and power is returned, the TV will then turn itself on (when the service menu setting is enabled).
This way you won't be able to turn the TV on with the remote though...

Mmmm, OK, good to know. Thanks!

However I switched to this custom component since I had issues with the default component. In hindsight it may have been a different issue. I might need to re-authorise Home Assistant. I'll first do that and try again with the default component.

Good suggestion using a smart plug BTW! Thx.

@spudje Using KEY_CUSTOM (or KEY_anything) applies to the existing HA (default) component. It works for my 2012 Samsung, which as mentioned is not using the websocket.

BTW, I can't seem to find the location of this custom component everyone is referring to. Where is it?

@tommyjlong OK, so that might help me too. Where/how do I change this KEY to KEY_CUSTOM/KEY_anything when using the default component.

The custom component is here (as far as I understood) https://mega.nz/#!Np01iAgT!DCl9pvl7sZ1odxrsh68R7Dcd2UN9uxScVXBuCNBdyJ8

@spudje You need to change line 130 in samsungtv/media_player.py:

def update(self):
        """Update state of device."""
        self.send_key("KEY")

becomes

def update(self):
        """Update state of device."""
        self.send_key("KEY_CUSTOM")

Thanks! In the custom component I could find that. But where is this in the default samsungtv component a docker image of Hass? And I guess this will be updated everytime I update Hass then? Or should I (some)how copy the default component to the custom component folder to keep it persistent between updates?

Within the docker container the file is located at /usr/src/app/homeassistant/components/samsungtv/media_player.py.
You can copy the component files to a location on your host, modify them and mount the host directory with -v "/path/on/host/samsungtv:/usr/src/app/homeassistant/components/samsungtv". This way, the modified files will persist between updates. You need to monitor the home assistant repo for larger changes to the files though, or things might break.

Running on the modified default component makes it work properly until now. Thanks!! Something to actually add to a next release? Or does it break newer models?

I have a Samsung Q70 and the custom component is working mostly fine to me. I only have a few issues:

  1. samsungctl is spamming "[root] Sending control command: KEY" in Home Assistant's logs when the TV is on;
  2. the component is spamming "[homeassistant.components.media_player] Updating samsungtv media_player took longer than the scheduled update interval 0:00:10" when the TV is off;
  3. Wake on LAN doesn't work, even though the TV supports it and has it enabled (running wakeonlan -i <IP> -p 7 <MAC> wakes it successfully).

For 1) I can just comment out the relevant log line, so it's not that much of an issue, and 2) is also something I can live with. Not being able to turn the TV on is definitely the most annoying one, and I'm not sure why the component isn't sending the WoL packet (as I see there is code for it there). Has anyone managed to get it working?

@ruippeixotog Is the Tv in the same subnet as your home assistant instance? Magic packets are not routed and your home assistant instance needs at least one network interface within the same subnet as the TV for it to work.

@caphm yes, both home assistant and the TV are on the same LAN. Previously I had an LG TV and I was able to wake it using https://www.home-assistant.io/components/webostv/#turn_on_action, so I'm confident it's not a network or a OS configuration issue 🙂

Did it work using wake_on_lan.send_magic_packet as a turn on action with your WebOS TV? If so, maybe try using https://www.home-assistant.io/components/universal/ with your Samsung TV as its only child and override only the turn_on action.

Good trick, did not know about that component. Thank you!

Still looking forward to understand why it doesn't work on the custom component, out of curiosity. This action in particular has nothing to do with Samsung firmwares and libs, so it's probably a bug with the custom component.

I have a Samsung Q70 and the custom component is working mostly fine to me. I only have a few issues:

1. `samsungctl` is spamming "[root] Sending control command: KEY" in Home Assistant's logs when the TV is on;

2. the component is spamming "[homeassistant.components.media_player] Updating samsungtv media_player took longer than the scheduled update interval 0:00:10" when the TV is off;

3. Wake on LAN doesn't work, even though the TV supports it and has it enabled (running `wakeonlan -i <IP> -p 7 <MAC>` wakes it successfully).

For 1) I can just comment out the relevant log line, so it's not that much of an issue, and 2) is also something I can live with. Not being able to turn the TV on is definitely the most annoying one, and I'm not sure why the component isn't sending the WoL packet (as I see there is code for it there). Has anyone managed to get it working?

For my Samsung Q60 WOL is working --- after I added the MAC address to configuration.yaml (silly me!).

Sorta complex here. Someone a list of sources to load and a patch file to apply maybe? Changing this and that spanned over 180 posts is dangerous IMO

Nah, it's either going to work or not. Working great on mine. I just wish they based it on Remote and not media-player. Kinda sucks only having 6 or so actions to remap.

Get Outlook for Androidhttps://aka.ms/ghei36


From: Daniel Reimer notifications@github.com
Sent: Wednesday, October 2, 2019 5:18:09 PM
To: home-assistant/home-assistant home-assistant@noreply.github.com
Cc: Chris Schulz cnschulz@gmail.com; Mention mention@noreply.github.com
Subject: Re: [home-assistant/home-assistant] [0.81.0] Samsung TV not working (#17802)

Sorta complex here. Someone a list of sources to load and a patch file to apply maybe? Changing this and that spanned over 180 posts is dangerous IMO


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHubhttps://github.com/home-assistant/home-assistant/issues/17802?email_source=notifications&email_token=AAJXBZE6XW766TQRMWSSENDQMRDLDA5CNFSM4F7NZI62YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEADZPEQ#issuecomment-537368466, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AAJXBZCDRX2JB6BNEQFQ46LQMRDLDANCNFSM4F7NZI6Q.

I just recently bought a new Samsung UA65RU7100W and was really hoping to get lucky with this integration.
Unfortunately it didn't come up in any auto-discovery so I then went to manually enter the info in configuration.yaml
What I found works was

  • WOL
  • power state (if using port 8001.)

I changed the port to 8002 but that broke the power state and there was no other bits working either.

I am using Home-assistant Docker container and it didn't even give me the authorization message on the TV so I did a wget from my docker host wget http://xxx.xxx.xxx.xxx:8001 and then found that this gave me the authorization message on the TV. I accepted this but still no luck. the media controls come up with error {'event': 'ms.channel.unauthorized'} each time.

If I browse to http://xxx.xxx.xxx.xxx:8001 with an approved IP it now gives me a 401 error. Googling hasn't helped but I am guessing that I need to have some sort of username and password for the TV?
I believe this could be the missing bit to make this module work but I can't be certain. hopefully this helps someone else in troubleshooting and resolving this issue.

I have a Samsung MU8000 and I couldn't get it to work (I'm using Docker, not HASS).

I hope it gets fixed soon.

Working great on my qled q9f 2018 model.

How can I use two tv’s with this? Can I rename something for a second custom component?

I have the same TV but this don't work
Can you helpme? @pDekker

Custom component from mega is mostly working from what i've seen so far on my UN55MU6290 TV using the suggested config.

@Answer-1 Which custom component are you referring to (there are so many now)?

@arsaboo The one hosted on Mega (https://mega.nz/#!Np01iAgT!DCl9pvl7sZ1odxrsh68R7Dcd2UN9uxScVXBuCNBdyJ8)

I just recently bought a new Samsung UA65RU7100W and was really hoping to get lucky with this integration.
Unfortunately it didn't come up in any auto-discovery so I then went to manually enter the info in configuration.yaml
What I found works was

  • WOL
  • power state (if using port 8001.)

I changed the port to 8002 but that broke the power state and there was no other bits working either.

I am using Home-assistant Docker container and it didn't even give me the authorization message on the TV so I did a wget from my docker host wget http://xxx.xxx.xxx.xxx:8001 and then found that this gave me the authorization message on the TV. I accepted this but still no luck. the media controls come up with error {'event': 'ms.channel.unauthorized'} each time.

If I browse to http://xxx.xxx.xxx.xxx:8001 with an approved IP it now gives me a 401 error. Googling hasn't helped but I am guessing that I need to have some sort of username and password for the TV?
I believe this could be the missing bit to make this module work but I can't be certain. hopefully this helps someone else in troubleshooting and resolving this issue.

Hi,

I have exactly same on Samsung The Frame 2019

Hello!
I use this fork https://github.com/xchwarze/ha-samsungtv-custom/releases in 2016+ tv
All TizenOS tv should work

Have the same issues with 2017 UE49MU9000 TV.
Using this fork [https://github.com/xchwarze/ha-samsungtv-custom/releases] : I can only turn the TV on from HA, but after that the status of device remains "Off" and nothing more working. I even can't turn the TV off.

Tried to add the TV through SmartThings. In this case I get a switch, that only allows me to turn the TV off.

So using these both methods I can only turn the TV on and off through 2 different entities...

@AlexeyUkolov Sorry i dont upload all files
try this https://github.com/xchwarze/ha-samsungtv-custom/releases/tag/v1.1.1
tested OK in HA 0.100.1 in Samsung MU6300

@xchwarze thank you! Now it works, with the port 8002. Excellent work, thank you again!

thanks @AlexeyUkolov !

@xchwarze I tried using your custom component.
it recognised the TV was on but that was about as far as I could get. the TV kept popping up an authorize message which I kept accepting but changing channels and other actions didn't seem to do anything.

@laywah2016 Restarting HA took care of the issue for me.

@xchwarze thank you for the new release, all looks excellent (especially the source list). The only issue for me now is that "TV" as a source does not work. I also tried KEY_DTV and KEY_ANTENNA - all without any effect. All the orhers sources are switching. Have you any idea?

thanks @AlexeyUkolov !
I am working on it but without the documentation of samsung.remote.control it is very difficult to achieve.
Maybe if I got the binary of samsung.remote.control (tizen binary from tv) I could add several improvements

Hi,
I can check status of my tv, but i am not authorized to any changes (volume change, power off).
I recived below info:
Failed to call service media_player/volume_mute. {'event': 'ms.channel.unauthorized'}

Regards
Łukasz

I can also power on TV, but others are unauthorized, power off also

Unfortunately still no luck. I tried rebooting HASS, I also stopped and started my docker container.

For me only open(on). I have try ports 8001 and 8002 but no luck.Is there any help or is total cuted from samsung last update the remote?

I make this version for tizen tvs https://github.com/xchwarze/ha-samsungtv-custom/releases
Tested on mu6300 and others 2017+ models

I make this version for tizen tvs https://github.com/xchwarze/ha-samsungtv-custom/releases
Tested on mu6300 and others 2017+ models

I have test it at my ue58mu6199 but still have the same problem.Only on.

I make this version for tizen tvs https://github.com/xchwarze/ha-samsungtv-custom/releases
Tested on mu6300 and others 2017+ models

Can you show me the settings? (configuration.yaml)

I have mu6300 too.

@hjm79
Not sure that is usefull, but this works for my MU9000 (LAN connected)

media_player:
      - platform: samsungtv_custom
        host: 192.168.1.2xx
        port: 8002
        mac: "84:c0:ef:ec:86:xx"

@hjm79
Not sure that is usefull, but this works for my MU9000 (LAN connected)

media_player:
      - platform: samsungtv_custom
        host: 192.168.1.2xx
        port: 8002
        mac: "84:c0:ef:ec:86:xx"

Doesn't it work with wifi?

I haven't checked.

Wifi doest support WakeOverLan.
I think there is one option to activate the fire via WS. If they activate it and do not complete the mac address it should work

@escoand and @MartinHjelmare shouldn't we close this one as well?

Obvious yes. Wasn't aware of it.

Closing this for now. Please open new issue if you are having trouble with Samsung TVs.

does anyone can tell me from where I can get complete service manual for samsung smart tv ue55nu8009?
thank you in advance

Was this page helpful?
0 / 5 - 0 ratings