Page 2 of 2

Re: Plex Status

Posted: Monday 02 October 2017 12:45
by Goldwing1973
I'm assuming commenting out these lines will stop the IDLE totally
url = ("http://" + domoticz_host + ":" + domoticz_port + "/" + domoticz_url+ "?type=command&param=udevice&idx=" + domoticz_PlexStatus + "&nvalue=0&svalue=IDLE")
urllib.urlopen(url)

Isn't it possible to add "variable=1" when IDLE is send for the first time and let the lines only be executed when "variable=0"
and when something starts playing that the "variable=0" is set?

Re: Plex Status

Posted: Monday 02 October 2017 12:57
by matteos1
if domoticz have a password?

galadril wrote: Wednesday 09 September 2015 14:36 But with these script, you get the status of your Plex Media Server

Prepare Domoticz
If you don't know how to create a virtual sensor chances are you have never done this before.
- Go to "Hardware"
- Fill in the name field with a desired name (like "Virtual")
- Choose for type the "Dummy, does nothing, use for virtual switches only"
- Click on "Add"
- The added hardware is now added to the hardware list. In the same row there is a "Create virtual sensor" button shown. Click on it.


Hardware
Now you are ready to create virtual devices.
- Go to "Hardware"
- Press "Create virtual sensor".
- Fill in the name field with a name like 'Plex'


Devices
Now you are ready to create a virtual device.
- Go to "Hardware"
- Press "Create virtual sensor".
- Fill in the name field with a name like 'Plex'


Plex script
Config the parameters in the Plex script:

Code: Select all

#config plex url
plexURL 			= '<plex ip>:<plex port>' #base url (default port = 32400)
	
#domoticz settings
domoticz_host      	= ''
domoticz_port      	= ''
domoticz_url       	= 'json.htm'

#domoticz idx
domoticz_PlexStatus = '' #idx of device

Put the script under /domoticz/scripts and make the script executable:
"sudo chmod +x /home/pi/domoticz/scripts/plex.py"


Test
Run the script by calling:
"sudo python /home/pi/domoticz/scripts/plex.py"

Image

If Plex Server is not playing anything, this is the result:

Image


Create the Cronjob
Now all ingredients are available to read the data from the portal and insert them into Domoticz.
- execute "sudo crontab -e"
- add the following line "*/10 * * * * /home/pi/domoticz/scripts/plex.py"
- exit crontab. Now everything should be working for you.

Scripts
plex.py

Code: Select all


#!/usr/bin/python

import urllib, urllib2, hashlib
from xml.etree import ElementTree as ET

#config plex url
plexURL 			= '<plex ip>:<plex port>' #base url (default port = 32400)
	
#domoticz settings
domoticz_host      	= ''
domoticz_port      	= ''
domoticz_url       	= 'json.htm'

#domoticz idx
domoticz_PlexStatus = '' #idx of device

#building url
requestURL = 'http://'+plexURL+'/status/sessions'
print requestURL


try:
  #call session url
  test = urllib.urlopen(requestURL).read()
  print test

  root = ET.XML(test)
  print root.tag

  videotitle = root.find('Video').attrib['title']
	
  print 'Video Playing: ' + videotitle
  urllib.urlopen("http://" + domoticz_host + ":" + domoticz_port + "/" + domoticz_url+ "?type=command&param=addlogmessage&message=Video Playing: " + videotitle)
	
  #uploading values to domoticz
  url = ("http://" + domoticz_host + ":" + domoticz_port + "/" + domoticz_url+ "?type=command&param=udevice&idx=" + domoticz_PlexStatus + "&nvalue=0&svalue=Playing: " + videotitle)
  urllib.urlopen(url)
	
except Exception: 
  print 'IDLE'
  #uploading values to domoticz
  url = ("http://" + domoticz_host + ":" + domoticz_port + "/" + domoticz_url+ "?type=command&param=udevice&idx=" + domoticz_PlexStatus + "&nvalue=0&svalue=IDLE")
  urllib.urlopen(url)
  pass


Re: Plex Status

Posted: Monday 11 December 2017 15:18
by PeterFroberg
Hi
For you who still have intrest in plex status for home users.
I have made a script in python that do the following
1. Check status on plexserver - current streams
2. Check a domoticz variable if the State for home users is changed
3. If variables is changed it updates domoticz switch and Variable with new state
4. Sends info of the change to influxDB to track usage history

Code: Select all

#!/usr/bin/python

import requests
import json
import urllib
import urllib2
import hashlib

from xml.etree import ElementTree as ET

#config plex url
plexURL                         = '192.168.15.23:32400' #base url (default port = 32400)

#domoticz settings
domoticz_user           = 'user' 		#Ange den användare i domoticz som ska användas
domoticz_pwd            = 'password'	 	#Lösenordet för ovan användare
domoticz_host           = '192.168.15.25'
domoticz_port           = '8080'
domoticz_url            = "http://" + domoticz_user + ":" + domoticz_pwd + "@" + domoticz_host + ":" + domoticz_port + "/json.htm"
influxDB_host		= "192.168.15.21:8086"

#domoticz idx

#building url
requestURL = 'http://'+plexURL+'/status/sessions'
print requestURL


def skickaData(videotitle, playinguser, playingstate):
  #Check plex_usernamne
  if playinguser == "Plexuser1":
        domoticz_SwitchIDX = 313   		#domoticz SwitchIDX för Plexuser1
        domoticzvariableIDX  = 1   		#VariableIDX för user 1
        domoticzvariablename = "variable1"	#Domoticz Variable Namn user 1
  elif  playinguser == "Plexuser2":  		
        domoticz_SwitchIDX = 325		
        domoticzvariableIDX = 2			
        domoticzvariablename = "variable2"
  elif  playinguser ==  "Plexuser1": 	
        domoticz_SwitchIDX = 326	
        domoticzvariableIDX = 3
        domoticzvariablename = "variable3"
  elif playinguser == "Plexuser1":
        domoticz_SwitchIDX = 327
        domoticzvariableIDX = 4
        domoticzvariablename = "variable4"
  else:
        result = -1

  #Check variable for specific user in domoticz and parse the json result
  varurl = (domoticz_url+ "?type=command&param=getuservariable&idx=" + str(domoticzvariableIDX))
  variablestaterequest=urllib.urlopen(varurl).read()
  #Parse Json result
  variable_json_object = json.loads(variablestaterequest)
  print "variablState for:",playinguser ,": ", variable_json_object["result"][0]["Value"]
  #Check if playing state has changed according to variable in domoticz
  if playingstate != variable_json_object["result"][0]["Value"]: 
    #Update variable in domoticz
    print "Update domoticz with new state for user", playinguser
    updateVarUrl = (domoticz_url + "?type=command&param=updateuservariable&vname=" + domoticzvariablename + "&vtype=2&vvalue=" + playingstate)
    urllib.urlopen(updateVarUrl).read()
    #Update log in domoticz
    urllib.urlopen(domoticz_url+ "?type=command&param=addlogmessage&message=User: " + playinguser + " Changed Plex Status -- Film: " + videotitle + "-- State: " + playingstate)
    #Update switch in Domoticz
    switchurl = (domoticz_url+ "?type=command&param=udevice&idx=" + str(domoticz_SwitchIDX) + "&nvalue=0&svalue=Film: " + videotitle + "-- State: " + playingstate)
    urllib.urlopen(switchurl)
    #Update influxDB
    if (playingstate == "playing") or  (playingstate == "paused"):
      statusnumber = 1
    else:
      statusnumber = 0
    influxurl = "http://" + influxDB_host + "/write?db=domoticzDB" # --data-binary plexStatus" + playinguser + ",host=plexserver value=" + statusnumber)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = "plexStatus" + playinguser + ",host=plexserver,region=us-west value=" + str(statusnumber)
    r = requests.post(influxurl, data=payload, headers=headers)
    print "Updated state for", playinguser, "to influxdb"
  return


try:
  activeUserArray=["a"]
  #call session url
  test = urllib.urlopen(requestURL).read()
  #Parse XML response from Plexsession
  root = ET.XML(test)
  print "Root size is: ",root.get('size')
  if root.get('size') != "0":
    #"XML Parsing"
    for element in root:
      title = element.get('title')
      for item in element.iterfind('User'):
        plexuser = item.get('title')
        activeUserArray.append(plexuser)
        print plexuser, "is playing:", title
      for item in element.iterfind('Player'):
        state = item.get('state')
        #print "The state is:", state
    skickaData(title, plexuser, state) 
  print "Check Idle users"
  if not ("plexuser1" in activeUserArray):
    skickaData(" ", "plexuser1", "Idle")
  if not ("plexuser2" in activeUserArray):
    skickaData(" ", "plexuser2", "Idle")
  if not ("plexuser3" in activeUserArray):
    skickaData(" ", "plexuser3", "Idle")
  if not ("plexuser4" in activeUserArray):
    skickaData(" ", "plexuser4", "Idle")


except Exception:
  print 'Error'
  raise 

Re: Plex Status

Posted: Sunday 31 December 2017 16:26
by Rodio
Hi Peter,

Can you make an HowToInstall your script?
Especially the Plexusername part.
And the influxDB, do I need it?

Im not a very experienced user :oops: :lol:

Thx for the effort

Cheers
R

Re: Plex Status

Posted: Monday 12 February 2018 12:08
by PeterFroberg
Hi
I can try to explain it in more detail.
In plex you can set the server to be a "home server" see https://support.plex.tv/articles/204234 ... ome-setup/ for how to set it up if you havn't done that yet.

Plexuser:
In my script you just replace "Plexuser1" with the name (username in plex, that you have set up according to the link above)
What this does is that when the script checks the status of your plexserver it will match the name of the plexuser and see if that user is currently streaming from the server.

In domotics:
You need to setup 2 things
1. setup a virtual switch, then you need to set "domoticz_SwitchIDX = " to the IDX number of that switch. This switch should be of the type "text"
2. setup a User Variable, the Variables IDX need to be set to "domoticzvariableIDX =", And "domoticzvariablename =" needs to be set to the name of the varable in domoticz

You don't need the influx part unless you want to send the data to a influx database. I use it to create graphs for usage

I run this script on a Raspberry pi 3 and then schedule it to run every 5 minutes with crontab (I dont need the info more frequently)

I hope this might make it a little bit easier ;)

Get back to me if you have any maore questions :)

/Peter