I have gotten into the habit of playing re-runs of familiar comedies on my bedroom TV while trying to fall asleep. I am not alone in this somewhat peculiar habit as others have discussed here of Reddit. I am sure other people have similar comfort shows, but there is an actual documented community of this for Futurama.
Up till now this has required a several step process every night involving turning on the TV, launching Plex, and going through several menus in order to shuffle whatever series I want that day. With a power monitoring smart plug I can detect the TV being turned on so automating the process seemed like a good idea that wouldn't take that much effort. I was wrong about the level of effort, but was ultimately successful in automating the process.
The automation to trigger this is very simple. I have used a helper to ensure this is only triggered once per day as power readings can sometimes be inconsistent. A chron entry resets it every morning so it is ready each night.
I thought the rest would be simple since the Plex integration supports systematically playing a playlist you have configured on your plex server. like below. But this service call only works well in one very specific scenario. Plex already has to be open and not have a title currently playing or you get some odd behavior like the audio playing from the playlist with the plex menu still open.
To ensure that the play_media commands behaves optimally, I had to add another integration for Android TV. Using the Android TV integration I am able to force Plex to close then force it to open again after a delay. That combination of commands seemed to work as I was debugging/testing the process.
The next day when I was excited to save a few seconds based on my 1+ hour(s) of effort, but it didn't work. I tried to manually call the play_media service after rebooting my Android TV device. The last thing needed to make the basic script work as expected another call to a plex service to ensure the client was active after restarting Plex on the device.
The one relatively simple addition to this script I also implemented was allowing for a variety of different shows be selected as eventually a single show gets a bit monotonous. I first attempted to use a dropdown to inject the playlist name in the service call, but could not figure out the correct syntax if it is even possible. Instead I decided to implement what is effectively a checkbox using multiple Toggle input helpers. Each of the shows toggles also has an automation that when they go from off to on, turn off all the other show toggles in the set. This allowed me to create a relatively user friendly card I can add to any dashboard.