ESP8266 & Current Plays

ESP8266 & Current Plays

the above picture is of the esp8266 running the code below in post #2

Since its my first forum post i gotta start this off by saying that i $%^* love plex. has completly changed the entertainment experience for me and some close friends over the last few years. so grateful damn grateful to the devs that i purchased plexpass just to support them (more on this later) & wanted to give back in any way that i can!

I use plexpy quite often to monitor the plex server stats. its conveniant to check it on the phone via a browser but i just felt like it was such a hassle to constantly have to pull out my fone all the time, when really the only thing im wanting to know is see how current plays there are at any given moment.

Ended up creating this and wanted to post the code and steps required incase anyone else wanted to do the same, build on it, or whatever else you wish. Most of the code is just a hacked up version of BasicHttpClient.ino Once I realized I was going to share this, i wanted to make sure all the code used was free to share under the appropriate licenses. (and it is! whoo!!)

After some googling of different IoT devices (crazy huge selection by the way), i came across an system on a chip (SoC) called the esp8266. It’s basically a small module, has its own dedicated memory, processor, wifi (2.4Ghz b/g/n), and even some analog and digital inputs/outputs for reading/sending data! You can buy just the esp8266 module for cheap, like $4. Thing is, to program the device it’d be convenient to use USB & the esp8266 is very specific about the voltage level going into it (you don’t want to fry the circuitry with too much voltage - though they are super cheap!) So the esp8266 variant im am using has built in usb-to-serial, as well as an SH1106 OLED screen module. I don’t want to say the specific brand or model that i got, but your options to acquire one are vast… from china to the states, there are tons of vendors. Just make sure to check your vendors review for good plenty of good feedback, and check for documentation online before making your purchase.

prerequisites

  • ESP8266 w/ built in OLED ( $12)
  • plex server w/ plexpy
  • Arduino IDE Software
  • USB Power Supply Source
  • USB Cable

Install the Arduino IDE. This is what we’ll be using to communicate with the board. You may want to do some web searches on ‘esp8266 arduino’ as you will need to install some libraries that are listed in the header area of the following code. To install these: within the arduino program; in the menu bar goto Sketch, => Include Library
You can install the library .zip’s you find on github this way by selecting ‘Add .Zip Library’, or goto ‘Manage Libraries…’ and take advantage of the search box in the top right =)

code:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Wire.h>  // Only needed for Arduino 1.6.5 and earlier
#include <ESP8266HTTPClient.h>
#include "SH1106.h"

ESP8266WiFiMulti WiFiMulti;
SH1106 display(0x3c, 5, 4); // address, SDA, SCL inputs D1, D2

void setup() {
display.init();
//display.invertDisplay();
display.flipScreenVertically();
display.setFont(ArialMT_Plain_10);
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.drawString(0, 0, "Initializing ...");
display.display();
    for(uint8_t t = 5; t > 0; t--) {
        delay(1000);
    }

WiFiMulti.addAP("WIFINAME", "WIFIPASSWORD");
delay(500);
display.clear();
}

void loop() {
    display.clear();
    // wait for WiFi connection
    if((WiFiMulti.run() == WL_CONNECTED)) {   
      display.drawString(0, 20, "connected.");      
        HTTPClient http;
        http.begin("PLEXPYIP", PLEXPYPORT, "/api/v2?apikey=PASTEYOURAPIKEYHERE&cmd=get_activity"); //HTTP
        //  PLEXPYIP   - ip address or dns hostname of the server plexpy is running on
        //  PLEXPYPORT  - port number plexpy is running on. uncommented. 
        //  the next entry is the GET request, the example used is if plex is in the root directory
        //  example: 
        //  http.begin("259.32.23.12", 60061, "/api/v2?apikey=01234567890123456789&cmd=get_activity");
        int httpCode = http.GET();
        if(httpCode) {
               if(httpCode == 200) {
               String payload = http.getString();
                display.setFont(ArialMT_Plain_10);
                display.clear();
                display.drawStringMaxWidth(0, 0, 124, String(payload));
                display.display();
            }
        } else {
        }
    }
    delay(5000);
}

notes

copy paste that into the arduino sketch, select the correct COM port (com1, com2, etc.) and upload the code. make note to change the PLEXPYIP & PLEXPYPORT settings to match that of your setup, and to update the WIFINAME & WIFIPASSWORD to match that of your wifi settings.

This this is totally portable, as long as your within range of your home wifi it will display the first few rows of the plexpy api json results. due to sheer luck and awesomness, the stream_count field just happens to be right smack on the middle line of the oled display, with the variable immediately afterwards being the number of current plays.

i plan to parse the json when i have time, and have the oled just display 'current plays: X".

My first choice here was to use the official plex api. Instead of responding in the JSON format like plexpy uses, the official plex api responds back in gloriously formatted XML with tons of metadata goodies. next time i have time i plan on implementing the plex api right away as it’s very well documented.


a necessary update

A good friend reached out and offered a way (and the php code!) to display the data in a much cleaner format on the OLEd - instead of the raw JSON.

I ran into issues getting the esp8266 to process json data using ArduinoJson.h, compile errors but most likely a user error on my end. But thanks to some php code running on the same server as the plex server (or any server with internet access), the php script can query the plexpy api and parse the json using json_decode() and give us either the reply i show in the above pic using /plex8266.php?val=all or individual variable by changing the ‘all’ input to either: total, direct & trans

plex8266.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$URL = "http://PLEXPYIP:PLEXPYPORT/api/v2?apikey=PASTEYOURAPIKEYHERE&cmd=get_activity";
$data = json_decode(file_get_contents($URL),true);
$stream_count = $data['response']['data']['stream_count'];
$transcdoe_stream_count =0;
if($stream_count > 0){
        $sessions = $data['response']['data']['sessions'];
        for ($c=0;$c<count($sessions);$c++)
                if($sessions[$c]['transcode_key']!="")
                        $transcdoe_stream_count ++;
}
if (isset($_GET['val']))
        $val =$_GET['val'];
else
        $val = "all";
if($val=="all")
        echo "Direct Play: ".($stream_count-$transcdoe_stream_count)."
 Transcodes: ".$transcdoe_stream_count."
 Total ".$stream_count;
elseif($val=="direct")
        echo ($stream_count-$transcdoe_stream_count);
elseif($val=="trans")
        echo $transcdoe_stream_count;
elseif($val=="total")
        echo $stream_count;

//echo "<br /> <br />";
//print_r($data);
?>

make sure to replace again replace PLEXPYIP, PLEXPYPORT & PASTEYOURAPIKEYHERE with your relevant info.

php input php output
esp8266.php?=all returns formatted response of current transcodes, direct plays & total plays
esp8266?val=trans returns only a number of current transcodes
esp8266?val=direct returns only a number of current direct plays
esp8266?val=total returns only a number of total combines direct play and transcodes

updated code

/**
 * ESP8266 & PLEXPY API
 * PLAY COUNT VIEWER
 */

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Wire.h>  // Only needed for Arduino 1.6.5 and earlier
#include <ESP8266HTTPClient.h>
#include "SH1106.h"

ESP8266WiFiMulti WiFiMulti;
SH1106 display(0x3c, 5, 4);

void setup() {
    display.init();
    display.flipScreenVertically();
    display.setTextAlignment(TEXT_ALIGN_CENTER_BOTH);
    display.drawString(DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 - 20, "Initializing
 device");
    display.drawString(DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2 - 10, "device");
    display.display();

    for(uint8_t t = 5; t > 0; t--) {

   display.clear();
        delay(1000);
    }

WiFiMulti.addAP("WIFINAME", "WIFIPASSWORD");
delay(500);
}

void loop() {
    if((WiFiMulti.run() == WL_CONNECTED)) {        
        HTTPClient http;
        http.begin("PHPSERVER", 80, "/plex8266.php?val=all"); //HTTP
        int httpCode = http.GET();
        if(httpCode) {
            if(httpCode == 200) {

               String total = http.getString();
               display.clear();
               display.setTextAlignment(TEXT_ALIGN_LEFT);    
               display.setFont(ArialMT_Plain_16);
               display.drawString(0, 0, "plexpy stats");
               display.setFont(ArialMT_Plain_10);
               display.drawString(0, 18,  String(total));
               display.display();
            }
        } else {

        }
    }

    delay(5000);
}

Note that none of the code queries the php’s other capabilities for the direct, trans & total data. it simply requests ‘all’ (/plex8266.php?val=all) and spits out the parsed data exactly as outputted by the php script.

Only posting this here so that others can either get ideas or if someone wants to put this together themselves. No longer having to pull my fone out of the pocket on plex server intensive sundays! Glance over at this on my desk, and the important info i wanted is there.

The esp8266 is awesome. with the exception of a power supply, it can be completly self contained. an esp8266 or esp32 is also great for PUT and GET requests, and with how extensive the plex api, making a call to refresh your media library can be as easy as pushing a button which tells the esp to send a request to the plex API.

http://[PMS_IP_ADDRESS]:32400/library/sections/29/refresh?force=1&X-Plex-Token=YourTokenGoesHere

heres a basic listing with more plex api calls to control your media server (also where the above example is from)
https://support.plex.tv/hc/en-us/articles/201638786-Plex-Media-Server-URL-Commands

few more images


Wow, so cool! Thanks for putting this up, mate. Can’t wait to try it out.
Is this the plexpy you mention?

One day I was banging my head with C++ and then it hit me “You can make all that complex stuff on PHP and just feed the results to the board”. That was a good day :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.