PlexDevices - Custom Media Player Component

Looks like the clients URL above always returns nothing. However, using http://<plex_server_hostname>:32400/status/sessions provides full information on currently playing streams.

Is the existing component actually working for anyone on current Plex versions? I’m on 1.7.5.4035.

Try to see if this works for you:

https://community.home-assistant.io/t/status-of-a-plex-client-useful-to-trigger-automation/18540?source_topic_id=20341

Since I switched from a local to a remote server I’m having exactly the same problem.

Will this work and tell me the status of a RasPlex Plex client on my LAN that connects to a friend’s Plex Server?

Not sure, But I’m running the latest LibreElec with PlexKodiConnect plugin and then it works also via the normal Kodi Component.

Is this project dead? Links to the OP’s github for this result in a 404 now.

This component has been merged into HA itself for a while now, I’m not sure if he made any additional changes, but in any case, the actual HA Plex Media player is now this updated one.

1 Like

Bummer… I was hoping this project would solve the issue popping up in my error log…

2017-08-24 06:59:55 ERROR (MainThread) [homeassistant.components.sensor] Error while setting up platform plex
Traceback (most recent call last):
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/connection.py", line 141, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/util/connection.py", line 83, in create_connection
    raise err
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/util/connection.py", line 73, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 345, in _make_request
    self._validate_conn(conn)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 844, in _validate_conn
    conn.connect()
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/connection.py", line 284, in connect
    conn = self._new_conn()
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/connection.py", line 150, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
requests.packages.urllib3.exceptions.NewConnectionError: <requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x68648ef0>: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/adapters.py", line 438, in send
    timeout=timeout
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 649, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/packages/urllib3/util/retry.py", line 388, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
requests.packages.urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='my.plexapp.com', port=443): Max retries exceeded with url: /users/sign_in.xml (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x68648ef0>: Failed to establish a new connection: [Errno 111] Connection refused',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/homeassistant/helpers/entity_component.py", line 164, in _async_setup_platform
    SLOW_SETUP_MAX_WAIT, loop=self.hass.loop)
  File "/usr/lib/python3.5/asyncio/tasks.py", line 400, in wait_for
    return fut.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 293, in result
    raise self._exception
  File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/homeassistant/components/sensor/plex.py", line 52, in setup_platform
    name, plex_url, plex_user, plex_password, plex_server)], True)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/homeassistant/components/sensor/plex.py", line 70, in __init__
    user = MyPlexAccount.signin(plex_user, plex_password)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/plexapi/myplex.py", line 76, in signin
    response = requests.post(cls.SIGNIN, headers=plexapi.BASE_HEADERS, auth=auth, timeout=TIMEOUT)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/sessions.py", line 518, in request
    resp = self.send(prep, **send_kwargs)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/sessions.py", line 639, in send
    r = adapter.send(request, **kwargs)
  File "/srv/homeassistant/homeassistant_venv/lib/python3.5/site-packages/requests/adapters.py", line 502, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='my.plexapp.com', port=443): Max retries exceeded with url: /users/sign_in.xml (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x68648ef0>: Failed to establish a new connection: [Errno 111] Connection refused',))

I created a feature request but this thread seems to have more activity… would it be possible to add the video height and width to the info it pulls of the movie playing… I want to be able to trigger my projector screen masking system based on the videos dimensions of the black bars that go on the top and bottom of the screen.

So i have tried to edit the plex.py file in homeassistant to get the media height. But its not working… the script seems to still be running fine im not getting any errors in the logs, but im not seeing the data in the attributes of home assistant.

image

Can we pull height and width attribute information?.. Ive been asking this question all over the forum but it seems like its fallen on deaf ears… ive been trying to modify this script myself but everything i try doesnt work. There isnt any kind of documentation to understand how its pulling the data into homeassistant.

I am trying to make a view/tab with all of my Plex media players. At times I have up to 10 showing. I have read that dynamic groups are created but I am not able to see them. Any help would be much appreciated. The issue is new ones are added when someone access from a new player example 2 different computers. Where can I find this dynamic group so I can make it a view?

@JesseWebDotCom

Hi,

I’m trying to play movies from PMS to Chromecast. TV switches to Cc, Cc loads the HA player (not Plex) then turns to idle.

I assume Plex needs to be streamed on the Cc however I didn’t find the relevant part where it loads the Plex component.

I have set the following script (there are no errors in the HA log; video name corresponds to the one in Plex).

Thanks

test:
  sequence:
    - service: media_player.play_media
      entity_id: media_player.chromecast2
      data:
        media_content_id: '{ \"library_name\" : \"Movies\", \"video_name\" : \"Videoname1\", \"shuffle\": \"0\"}'
        media_content_type: VIDEO

Just a note, https://github.com/home-assistant/home-assistant/pull/9664 has some fixes, but not the dupes yet.

Maybe I have the syntax wrong but I am having no luck with this. I am trying to make a sript to play a specific media, in this case avatar. Below is my script:

test:
  sequence:
    - service: media_player.play_media
      entity_id: media_player.shield_lr
      data:
        media_type: VIDEO
        media_content_id: '{ "library" : "Movies", "title" : "Avatar" }'

I get no errors. Nothing happens. The script triggers but the movie never plays. Any help is much appreciated.

check your media_content_id syntax conforms to this:

FWIW i spent a few hours on this over the weekend and failed. interestingly, the data in the attributes section of the media player is different if i use a script or call media from the services page in the gui , than it is if i just, say, cast a song or movie to the same media player from an andorid device (app) or from the plex web client.

Thanks @danpow. I thought I looked at all that but apparently not close enough. I’m getting a json decoder error. I assume this is what you were referring too?

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

it seems it’s expecting something different form the results in json.loads(media_id). Have to jump on a work call but will dig deeper when I have more time.

ok actually resolved the error above: It was my config file still. The media_content_id needs double quotes around it like:

media_content_id: "{ \"library_name\": \"Movies\", \"video_name\": \"Avatar\", \"shuffle\" : \"0\" }"

Now I am getting a different Error that I will start troubleshooting:

Nov 15 13:33:43 HAServer hass[27256]: 2017-11-15 13:33:43 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Nov 15 13:33:43 HAServer hass[27256]: Traceback (most recent call last):
Nov 15 13:33:43 HAServer hass[27256]:   File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
Nov 15 13:33:43 HAServer hass[27256]:     result = coro.throw(exc)
Nov 15 13:33:43 HAServer hass[27256]:   File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/core.py", line 1038, in _event_to_service_call
Nov 15 13:33:43 HAServer hass[27256]:     yield from service_handler.func(service_call)
Nov 15 13:33:43 HAServer hass[27256]:   File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/components/media_player/__init__.py", line 408, in async_service_handler
Nov 15 13:33:43 HAServer hass[27256]:     yield from getattr(player, method['method'])(**params)
Nov 15 13:33:43 HAServer hass[27256]:   File "/usr/lib/python3.5/asyncio/futures.py", line 380, in __iter__
Nov 15 13:33:43 HAServer hass[27256]:     yield self  # This tells Task to wait for completion.
Nov 15 13:33:43 HAServer hass[27256]:   File "/usr/lib/python3.5/asyncio/tasks.py", line 304, in _wakeup
Nov 15 13:33:43 HAServer hass[27256]:     future.result()
Nov 15 13:33:43 HAServer hass[27256]:   File "/usr/lib/python3.5/asyncio/futures.py", line 293, in result
Nov 15 13:33:43 HAServer hass[27256]:     raise self._exception
Nov 15 13:33:43 HAServer hass[27256]:   File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in run
Nov 15 13:33:43 HAServer hass[27256]:     result = self.fn(*self.args, **self.kwargs)
Nov 15 13:33:43 HAServer hass[27256]:   File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/components/media_player/plex.py", line 710, in play_media
Nov 15 13:33:43 HAServer hass[27256]:     media = self.device.server.library.section(
Nov 15 13:33:43 HAServer hass[27256]: AttributeError: 'PlexClient' object has no attribute 'server'

I have it working, at least tested and working to the shield TV. Still have a few errors in the log but the functionality is working and playing the movie I put in the script. There were some itm property issue in the client_play_media funtion.

Anywhere where it is “self.device.server” should be "self.device._server

Also, where it assigns self.device._server.url to the variable server_url it needs to be encapsulated in str to make it a string so it can be properly split.

Here is the updated Client_play_media code and once I have the rest of the errors fixed I can push it to git to get included in the official build, hopefully. Also, added a try to catch any exception and the log just prints out variable information which I am using to troubleshoot at the moment. despite the exception it’s throwing it is still playing the movie. You will also see some added unused variables which will be sorted out once the errors are fixed.

def _client_play_media(self, media, delete=False, **params):
    """Instruct Plex client to play a piece of media."""
    if not (self.device and
            'playback' in self._device_protocol_capabilities):
        _LOGGER.error("Client cannot play media: %s", self.entity_id)
        return

    import plexapi.playqueue
    playqueue = plexapi.playqueue.PlayQueue.create(
        self.device._server, media, **params)

    # Delete dynamic playlists used to build playqueue (ex. play tv season)
    if delete:
        media.delete()

    server_url = str(self.device._server.url)
    server_url = server_url.strip(':')
    server_address = server_url[1].strip('/')
    server_port = server_url[-1]

    try:
        self.device.sendCommand('playback/playMedia', **dict({
            'machineIdentifier': self.device._server.machineIdentifier,
            'address': server_url[1].strip('/'),
            'port': server_url[-1],
            'key': media.key,
            'containerKey':
                '/playQueues/{}?window=100&own=1'.format(
                    playqueue.playQueueID),
        }, **params))
    except:
        _LOGGER.error("Device Server URL: %s, Server URL: %s, Server IP: %s, Server Port: %s",
                       str(self.device._server.url), server_url, server_address, server_port)

Did you manage to fix this? I’m struggling with the same issue.