PlexDevices - Custom Media Player Component

@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.

Hi,

Unfortunately no (actually I haven’t actively tried to resolve the issue). From the posts above I understand the component is broken, however I’m not a software developer to be able to make any of it.

My post was in regard of video files but what I wanted to do was to send songs from a specific playlist to Chromecast and, having all of these in HA, to automate based on moments of the day/days of the weeks.

If only playing audio files from a playlist is suitable for you, as an alternative (for sending songs to Chromecast Audio/Chromecast Audio Groups) you could try this:

I have both components mentioned in the topic (Google Music Playlists and Google Music Radio).

It works on HA with AiO (Python 3.4) and on Hassbian (Python 3.5 - I updated to Hassbian since AiO doesn’t support at the moment Python 3.5). I couldn’t install the gmusic component on Hassio (I’m unsure about the other installation methods).

Any luck getting this checked in and added to an official push to next release?

Where is documentation now ? as links on first post are dead now :frowning: Found the python script in your config directory but missing documentation to be sure to setup it correctly !
Thanks

Update: oki forget my message, realised it’s same component as the buggy official one for Plex in HA that is dead since ages :frowning:

Not sure what you mean by dead because the Plex component has been working fine for me for over a year.

Hi,

Could you post your config for Plex? Did you set it as a custom component?

With the default component it gets the errors mentioned by @salphonso but after making the modifications above, it still doesn’t work and no error thrown in the log.

Thanks

The official Plex component has some serious problems since a while unhappy and I’m not alone (you should check on HA github), and it looks like programmer working on it is pretty busy :frowning:

Can anyone help me out with this one?

I’m trying to play a playlist in plex and getting this error:

2018-05-12 15:26:57 ERROR (MainThread) [homeassistant.core] Error executing service <ServiceCall media_player.play_media: entity_id=['media_player.plex_television'], media_content_id={ "playlist_name": "Inoka", "shuffle": "1" }, media_content_type=PLAYLIST>
Traceback (most recent call last):
  File "/usr/share/homeassistant/lib/python3.6/site-packages/homeassistant/core.py", line 1002, in _event_to_service_call
    await service_handler.func(service_call)
  File "/usr/share/homeassistant/lib/python3.6/site-packages/homeassistant/components/media_player/__init__.py", line 415, in async_service_handler
    await getattr(player, method['method'])(**params)
  File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/share/homeassistant/config/custom_components/media_player/plex.py", line 769, in play_media
    media = self.device.server.playlist(src['playlist_name'])
AttributeError: 'PlexClient' object has no attribute 'server'

How to set the attribute server in the PlexClient? or where is it defined?

The Plex Client is a raspberry pi with RasPlex on it.

Best Regards,
Donald.

Has anyone ever managed to get a Plex client with Plex DVR to launch a specific live tv channel (e.g. BBC NEWS HD) from a Home Assistant script or automation?

anyone who has it working could you post your code?

I’m getting this error in the log over and over:

Sun Jun 10 2018 15:17:31 GMT-0700 (Pacific Daylight Time)

    Error doing job: Future exception was never retrieved
    Traceback (most recent call last):
      File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
        result = self.fn(*self.args, **self.kwargs)
      File "/usr/lib/python3.6/site-packages/homeassistant/components/media_player/plex.py", line 149, in <lambda>
        track_utc_time_change(hass, lambda now: update_devices(), second=30)
      File "/usr/lib/python3.6/site-packages/homeassistant/util/__init__.py", line 319, in wrapper
        result = method(*args, **kwargs)
      File "/usr/lib/python3.6/site-packages/homeassistant/util/__init__.py", line 319, in wrapper
        result = method(*args, **kwargs)
      File "/usr/lib/python3.6/site-packages/homeassistant/components/media_player/plex.py", line 189, in update_devices
        update_sessions)
      File "/usr/lib/python3.6/site-packages/homeassistant/components/media_player/plex.py", line 328, in __init__
        self.refresh(device, session)
      File "/usr/lib/python3.6/site-packages/homeassistant/components/media_player/plex.py", line 394, in refresh
        if self._device.machineIdentifier is not None and \
    AttributeError: 'NoneType' object has no attribute 'machineIdentifier'

Is this still a custom compenent or built into HA now?

Merged into HA a while back now

1 Like

FYI - I created a new custom component that properly combines HA’s included Apple TV and Plex media players into a single, rich player. You can check that out here.