mirror of
https://github.com/KevinMidboe/Node-Com-Handler.git
synced 2025-10-29 09:40:27 +00:00
Init commit, lots of stuff already made, and need to clean up
This commit is contained in:
160
UDPStatusHandler.py
Normal file
160
UDPStatusHandler.py
Normal file
@@ -0,0 +1,160 @@
|
||||
# March 6, 2016 Kevin Midboe Utleirvegen Trondheim
|
||||
# Python program that uses UDP to get and return info of server
|
||||
|
||||
# TODO
|
||||
# Have everything sent as JSON objects.
|
||||
# Threading for multiple accesses
|
||||
# Only have valid inputs, guess if slightly off.
|
||||
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from commands import *
|
||||
from socket import *
|
||||
|
||||
# Define the socket communicating will transfered
|
||||
serverSocket = socket(AF_INET, SOCK_DGRAM)
|
||||
serverSocket.bind(('', 12000))
|
||||
|
||||
# TODO error handling
|
||||
# Function to get the temp of the cpu by getting ouput of unix command
|
||||
def temp():
|
||||
p = getstatusoutput("sensors -u | awk '/temp2_input/ {print $2}' | sed -n 2p")[1]
|
||||
return str(p[:p.index('.')])
|
||||
|
||||
|
||||
# Function that returns uptime time by getting unix command output
|
||||
def uptime():
|
||||
p = getstatusoutput("uptime")
|
||||
return str(p[1])
|
||||
|
||||
|
||||
# Get's info from session XML file by plex
|
||||
def plex():
|
||||
# Every call saves the info of session.xml to a file named plexPlaying
|
||||
os.system('curl --silent localhost:32400/status/sessions > ~/plexPy/plexPlaying.xml')
|
||||
|
||||
# XML parsing, creates a tree and saves the root node as root
|
||||
tree = ET.parse('plexPy/plexPlaying.xml')
|
||||
root = tree.getroot()
|
||||
|
||||
# The root node named MediaContainer has a size variable that holds number of active processes.
|
||||
# If this is '0' then there are none playing, no need to compute.
|
||||
if (root.get('size') != '0'):
|
||||
|
||||
# Get load of CPU and I/O
|
||||
return_text = '\n\t' + str(os.popen('cat /proc/loadavg').read())
|
||||
return_text += str('\tCur: \t' + root.get('size') + '\n')
|
||||
|
||||
# Goes through all the 'video' elements in MediaContainer
|
||||
for video in root.findall('Video'):
|
||||
if (video.get('type') == 'movie'):
|
||||
name = video.get('title')
|
||||
return_text += '\n\tTitle: \t' + name
|
||||
|
||||
elif (video.get('type') == 'episode'):
|
||||
parentName = video.get('grandparentTitle')
|
||||
name = video.get('title')
|
||||
return_text += '\n\tTitle: \t' + name + \
|
||||
'\n\tSeries: ' + parentName
|
||||
|
||||
progress = "{0:0.1f}".format(float(video.find('TranscodeSession').get('progress')))
|
||||
state = video.find('Player').get('state')
|
||||
player = video.find('Player').get('platform')
|
||||
user = video.find('User').get('title')
|
||||
|
||||
return_text += str('\n\tProg : \t' + str(progress) + '\n\tPlayer: ' + player + \
|
||||
'\n\tState: \t' + state + '\n\tUser: \t' + user + '\n')
|
||||
|
||||
return return_text
|
||||
else:
|
||||
return 'Null playing'
|
||||
|
||||
|
||||
# TODO more logic in formatting the return string
|
||||
# Similar function as above, but formates the return string to better fit on I2C display
|
||||
def i2c_uptime():
|
||||
p = getstatusoutput("uptime") # Get's the output of unix command 'uptime'
|
||||
upOutput = p[1] # Saves the ending part of stirng to variable
|
||||
|
||||
# Under the handling and formatting of the output is put together and saved to string upOutput
|
||||
try:
|
||||
upOutput = upOutput[upOutput.index('up') + 2:upOutput.index('days') + 4]
|
||||
except ValueError:
|
||||
try:
|
||||
upOutput = upOutput[upOutput.index('up') + 2:upOutput.index('min') + 3]
|
||||
except ValueError:
|
||||
upOutput = upOutput[upOutput.index('up') + 3:upOutput.index(',')]
|
||||
|
||||
if (len(upOutput) > 5):
|
||||
return upOutput
|
||||
else:
|
||||
return ' ' + str(upOutput)
|
||||
|
||||
# TODO don't rely on nums, but logicaly pick out needed info
|
||||
# This function is costumized for I2C display and formates the output of unix command
|
||||
# 'uptime' to get the load of first and third value of the load
|
||||
def i2c_load():
|
||||
p = getstatusoutput("uptime")
|
||||
upOutput = p[1]
|
||||
loadIndex = upOutput.index('load average: ') + 14
|
||||
upOutput = upOutput[loadIndex:loadIndex + 2] + upOutput[loadIndex + 8:]
|
||||
return upOutput.replace(', ', ' ')
|
||||
|
||||
def get_space(text):
|
||||
try:
|
||||
text = text.split()
|
||||
key_index = text.index('space')
|
||||
dirName = '/media/' + text[key_index + 1]
|
||||
st = os.statvfs(dirName)
|
||||
|
||||
disk_free = st.f_frsize * st.f_bavail
|
||||
disk_total = st.f_frsize * st.f_blocks
|
||||
|
||||
space_output = space_format(disk_free)
|
||||
space_output += '/' + space_format(disk_total)
|
||||
|
||||
except OSError:
|
||||
space_output = dirName + ' is not a valid dir'
|
||||
|
||||
return space_output
|
||||
|
||||
def space_format(size):
|
||||
if len(str(size)) > 12:
|
||||
formated = float(size) / (1024)**4
|
||||
formated = "{0:0.1f}".format(formated) + 'T'
|
||||
else:
|
||||
formated = float(size) / (1024)**3
|
||||
formated = "{0:0.0f}".format(formated) + 'G'
|
||||
|
||||
return formated
|
||||
|
||||
|
||||
# This is a repeting loop that runs everytime a message is recv in socket
|
||||
while True:
|
||||
# Save the message and return address to variables.
|
||||
message, address = serverSocket.recvfrom(1024)
|
||||
|
||||
print(message, address) # Debug print
|
||||
|
||||
# This should prob be cases and not if's, but works to get the right info user requests.
|
||||
if (message == 'temp'):
|
||||
return_message = temp()
|
||||
elif (message == 'up'):
|
||||
return_message = uptime()[1:]
|
||||
elif (message == 'plex'):
|
||||
return_message = plex()
|
||||
elif (message.find('space') != -1):
|
||||
return_message = get_space(message)
|
||||
elif (message == 'i2c'):
|
||||
return_message = 'Uptime: ' + i2c_uptime() + '!' + \
|
||||
'Load: ' + i2c_load() + '!' + \
|
||||
'Temp: ' + temp() + ' celcius!' + \
|
||||
'Space: ' + get_space('space hdd1')
|
||||
elif (message == '--help'):
|
||||
return_message = 'temp\nup\nspace {option}\n'
|
||||
else:
|
||||
return_message = 'none'
|
||||
|
||||
# Returns message to return address.
|
||||
serverSocket.sendto(return_message, address)
|
||||
8
foo.xml
Normal file
8
foo.xml
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" ?>
|
||||
<root>
|
||||
<Status load="0.05 0.05 0.05 1/262 15997"/>
|
||||
<PlexMedia size="2"/>
|
||||
<Video Device="iPhone" Playing="Interstellar" Prog="58.6" State="Playing" User="KevinMidboe"/>
|
||||
<Video Device="Samsung TV" Playing="Home Alone" Prog="32.9" State="Stopped" User="MajElg"/>
|
||||
<child Name="Kevin" age="10"/>
|
||||
</root>
|
||||
24
getPlaying.py
Normal file
24
getPlaying.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import xml.etree.ElementTree as ET
|
||||
import os
|
||||
|
||||
def getXML_file():
|
||||
os.system('curl --silent midboe.ddns.net:32400/status/sessions > testXml.xml')
|
||||
|
||||
def main():
|
||||
getXML_file()
|
||||
|
||||
tree = ET.parse('testXml.xml')
|
||||
root = tree.getroot()
|
||||
|
||||
print('\tCur: \t', root.get('size'), '\n')
|
||||
|
||||
for video in root.findall('Video'):
|
||||
parentName = video.get('grandparentTitle')
|
||||
name = video.get('title')
|
||||
user = video.find('User').get('title')
|
||||
state = video.find('Player').get('state')
|
||||
|
||||
print('\tTitle: \t', name, '\n\tSeries: ', parentName, '\n\tState: \t', state, '\n\tUser: \t', user, '\n')
|
||||
|
||||
|
||||
main()
|
||||
82
jsonPlex.py
Normal file
82
jsonPlex.py
Normal file
@@ -0,0 +1,82 @@
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections import OrderedDict
|
||||
|
||||
|
||||
def plex():
|
||||
# XML parsing, creates a tree and saves the root node as root
|
||||
tree = ET.parse('plex.xml')
|
||||
root = tree.getroot()
|
||||
|
||||
plex_dict = OrderedDict()
|
||||
i = 0
|
||||
# The root node named MediaContainer has a size variable that holds number of active processes.
|
||||
# If this is '0' then there are none playing, no need to compute.
|
||||
if (root.get('size') != '0'):
|
||||
|
||||
# Get load of CPU and I/O
|
||||
plex_dict['load'] = '0.05 0.05 0.05 1/262 15997'
|
||||
plex_dict['cur'] = root.get('size')
|
||||
|
||||
# Goes through all the 'video' elements in MediaContainer
|
||||
for video in root.findall('Video'):
|
||||
playing_dict = OrderedDict()
|
||||
if (video.get('type') == 'movie'):
|
||||
playing_dict['title'] = video.get('title')
|
||||
|
||||
elif (video.get('type') == 'episode'):
|
||||
playing_dict['title'] = video.get('title')
|
||||
playing_dict['series'] = video.get('grandparentTitle')
|
||||
|
||||
playing_dict['progress'] = "{0:0.1f}".format(float(video.find('TranscodeSession').get('progress')))
|
||||
playing_dict['state'] = video.find('Player').get('state')
|
||||
playing_dict['player'] = video.find('Player').get('platform')
|
||||
playing_dict['user'] = video.find('User').get('title')
|
||||
|
||||
plex_dict[i] = playing_dict
|
||||
i+=1
|
||||
|
||||
return plex_dict
|
||||
else:
|
||||
return 'Null playing'
|
||||
|
||||
plex_dict = plex()
|
||||
|
||||
|
||||
# plex_dict = {
|
||||
# "Load": '0.05 0.05 0.05 1/262 15997',
|
||||
# "Cur": '2',
|
||||
# }
|
||||
|
||||
# playing_1 = {'Playing': 'Interstellar',
|
||||
# 'State': 'Playing', 'Prog': '58.6',
|
||||
# 'Device': 'iPhone', 'User': 'KevinMidboe'}
|
||||
|
||||
# playing_2 = {'Playing': 'Home Alone',
|
||||
# 'State': 'Stopped', 'Prog': '32.9',
|
||||
# 'Device': 'Samsung TV', 'User': 'MajElg'}
|
||||
|
||||
# # print(playing_1, playing_2)
|
||||
|
||||
# i = 5
|
||||
|
||||
# plex_dict[i] = playing_1
|
||||
# plex_dict.update(playing_2)
|
||||
|
||||
# print(plex_dict)
|
||||
|
||||
# plex_dict["Playing"][0].update({'State' : 'Playing'})
|
||||
print(plex_dict)
|
||||
json_plex = json.loads(json.dumps(plex_dict))
|
||||
print(json_plex)
|
||||
# print(json_plex['Playing'][0])
|
||||
|
||||
for key, item in plex_dict.items():
|
||||
print(str(key) + '\t', str(item) + '\n')
|
||||
try:
|
||||
key = int(key)
|
||||
# print(item)
|
||||
except ValueError:
|
||||
pass # it was a string, not an int.
|
||||
|
||||
|
||||
86
jsonTest.py
Normal file
86
jsonTest.py
Normal file
@@ -0,0 +1,86 @@
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
|
||||
json_string = '{"movie_title": "Interstellar", "progress": "82.3", "state": "Playing", "player": "Safari"}'
|
||||
|
||||
parsed_json = json.loads(json_string)
|
||||
|
||||
print(parsed_json)
|
||||
# {'state': 'Playing', 'movie_title': 'Interstellar', 'player': 'Safari', 'progress': '82.3'}
|
||||
|
||||
print(parsed_json['movie_title'], parsed_json['state'])
|
||||
# {'progress': '82.3', 'player': 'Safari', 'movie_title': 'Interstellar', 'state': 'Playing'}
|
||||
d = {
|
||||
'Title': 'Interstellar',
|
||||
'Prog': '82.23',
|
||||
'State': 'Playing',
|
||||
'Player': 'Safari',
|
||||
'User': 'KevinMidboe'
|
||||
}
|
||||
|
||||
d['Device'] = 'iPhone'
|
||||
|
||||
packed_json = json.dumps(d, sort_keys=True)
|
||||
|
||||
print(packed_json)
|
||||
# {"Device": "iPhone", "Player": "Safari", "Prog": "82.23", "State": "Playing", "Title": "Interstellar", "User": "KevinMidboe"}
|
||||
|
||||
parsed_json = json.loads(packed_json, object_pairs_hook=OrderedDict)
|
||||
|
||||
print(parsed_json)
|
||||
# OrderedDict([('Device', 'iPhone'), ('Player', 'Safari'), ('Prog', '82.23'), ('State', 'Playing'), ('Title', 'Interstellar'), ('User', 'KevinMidboe')])
|
||||
|
||||
print(parsed_json['Title'], parsed_json['Device'])
|
||||
# OrderedDict([('Device', 'iPhone'), ('Player', 'Safari'), ('Prog', '82.23'), ('State', 'Playing'), ('Title', 'Interstellar'), ('User', 'KevinMidboe')])
|
||||
|
||||
for a, b in parsed_json.items():
|
||||
print(a + '\t', b)
|
||||
True
|
||||
# Device iPhone
|
||||
# Player Safari
|
||||
# Prog 82.23
|
||||
# State Playing
|
||||
# Title Interstellar
|
||||
# User KevinMidboe
|
||||
|
||||
plex_dict = {"plex" : {}}
|
||||
plex_dict["plex"] = {"plex_info": {}, "plex_playing": {}}
|
||||
|
||||
print(plex_dict)
|
||||
|
||||
plex_dict["plex"]["plex_info"] = {'Cur': '2', 'Load': '0.05 0.05 0.05 1/262 15997'}
|
||||
|
||||
print(plex_dict)
|
||||
|
||||
plex_dict['plex']['plex_playing'].update(
|
||||
{'Title' : 'Interstellar',
|
||||
'Prog' : '82.2%',
|
||||
'State': 'Playing',
|
||||
'Player': 'Safari',
|
||||
'User': 'KevinMidboe'}
|
||||
)
|
||||
|
||||
plex_dict['plex']["plex_playing"].update(
|
||||
{'Title' : 'Robo Cop 2',
|
||||
'Prog' : '34.8%',
|
||||
'State': 'Paused',
|
||||
'Player': 'LG TV',
|
||||
'User': 'MajElg'}
|
||||
)
|
||||
|
||||
print('\n' + str(plex_dict))
|
||||
# {'plex': {'Prog': '82.2%', 'State': 'Playing', 'User': 'KevinMidboe', 'Title': 'Interstellar', 'Player': 'Safari'}}
|
||||
|
||||
# plex_json = json.loads(json.dumps(plex_dict))
|
||||
|
||||
# print(plex_json['plex'].get('Title'))
|
||||
# # Interstellar
|
||||
|
||||
# for key, value in plex_json['plex'].items():
|
||||
# True
|
||||
# print(key + '\t', value)
|
||||
# # Title Interstellar
|
||||
# # Prog 82.2%
|
||||
# # State Playing
|
||||
# # Player Safari
|
||||
# # User KevinMidboe
|
||||
169
lcd_i2c.py
Normal file
169
lcd_i2c.py
Normal file
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/python
|
||||
#--------------------------------------
|
||||
# ___ ___ _ ____
|
||||
# / _ \/ _ \(_) __/__ __ __
|
||||
# / , _/ ___/ /\ \/ _ \/ // /
|
||||
# /_/|_/_/ /_/___/ .__/\_, /
|
||||
# /_/ /___/
|
||||
#
|
||||
# lcd_i2c.py
|
||||
# LCD test script using I2C backpack.
|
||||
# Supports 16x2 and 20x4 screens.
|
||||
#
|
||||
# Author : Matt Hawkins
|
||||
# Date : 20/09/2015
|
||||
#
|
||||
# http://www.raspberrypi-spy.co.uk/
|
||||
#
|
||||
# Copyright 2015 Matt Hawkins
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
#--------------------------------------
|
||||
import smbus
|
||||
import time
|
||||
from socket import *
|
||||
|
||||
host = '10.0.0.41'
|
||||
port = 12000
|
||||
|
||||
clientSocket = socket(AF_INET, SOCK_DGRAM)
|
||||
|
||||
# Define some device parameters
|
||||
I2C_ADDR = 0x27 # I2C device address
|
||||
LCD_WIDTH = 20 # Maximum characters per line
|
||||
|
||||
# Define some device constants
|
||||
LCD_CHR = 1 # Mode - Sending data
|
||||
LCD_CMD = 0 # Mode - Sending command
|
||||
|
||||
LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line
|
||||
LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line
|
||||
LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line
|
||||
LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line
|
||||
|
||||
LCD_BACKLIGHT = 0x08 # On
|
||||
#LCD_BACKLIGHT = 0x00 # Off
|
||||
|
||||
ENABLE = 0b00000100 # Enable bit
|
||||
|
||||
# Timing constants
|
||||
E_PULSE = 0.0005
|
||||
E_DELAY = 0.0005
|
||||
|
||||
#Open I2C interface
|
||||
#bus = smbus.SMBus(0) # Rev 1 Pi uses 0
|
||||
bus = smbus.SMBus(1) # Rev 2 Pi uses 1
|
||||
|
||||
def lcd_init():
|
||||
# Initialise display
|
||||
lcd_byte(0x33,LCD_CMD) # 110011 Initialise
|
||||
lcd_byte(0x32,LCD_CMD) # 110010 Initialise
|
||||
lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction
|
||||
lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off
|
||||
lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size
|
||||
lcd_byte(0x01,LCD_CMD) # 000001 Clear display
|
||||
time.sleep(E_DELAY)
|
||||
|
||||
def lcd_byte(bits, mode):
|
||||
# Send byte to data pins
|
||||
# bits = the data
|
||||
# mode = 1 for data
|
||||
# 0 for command
|
||||
|
||||
bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT
|
||||
bits_low = mode | ((bits<<4) & 0xF0) | LCD_BACKLIGHT
|
||||
|
||||
# High bits
|
||||
bus.write_byte(I2C_ADDR, bits_high)
|
||||
lcd_toggle_enable(bits_high)
|
||||
|
||||
# Low bits
|
||||
bus.write_byte(I2C_ADDR, bits_low)
|
||||
lcd_toggle_enable(bits_low)
|
||||
|
||||
def lcd_toggle_enable(bits):
|
||||
# Toggle enable
|
||||
time.sleep(E_DELAY)
|
||||
bus.write_byte(I2C_ADDR, (bits | ENABLE))
|
||||
time.sleep(E_PULSE)
|
||||
bus.write_byte(I2C_ADDR,(bits & ~ENABLE))
|
||||
time.sleep(E_DELAY)
|
||||
|
||||
def lcd_string(message,line):
|
||||
# Send string to display
|
||||
|
||||
message = message.ljust(LCD_WIDTH," ")
|
||||
|
||||
lcd_byte(line, LCD_CMD)
|
||||
|
||||
for i in range(LCD_WIDTH):
|
||||
lcd_byte(ord(message[i]),LCD_CHR)
|
||||
|
||||
def callApollo():
|
||||
clientSocket.sendto('i2c', (host, port))
|
||||
clientSocket.settimeout(5.0)
|
||||
message, address = clientSocket.recvfrom(1024)
|
||||
message = message.split('$')
|
||||
message.reverse()
|
||||
return message
|
||||
|
||||
def main():
|
||||
# Main program block
|
||||
|
||||
# Initialise display
|
||||
lcd_init()
|
||||
|
||||
while True:
|
||||
|
||||
# Send some test
|
||||
message = callApollo()
|
||||
lcd_string(message.pop(), LCD_LINE_1)
|
||||
lcd_string(message.pop(), LCD_LINE_2)
|
||||
lcd_string(message.pop(), LCD_LINE_3)
|
||||
lcd_string(message.pop(), LCD_LINE_4)
|
||||
|
||||
time.sleep(9)
|
||||
|
||||
lcd_string('', LCD_LINE_1)
|
||||
lcd_string('', LCD_LINE_2)
|
||||
lcd_string('', LCD_LINE_3)
|
||||
lcd_string('', LCD_LINE_4)
|
||||
try:
|
||||
lcd_string(message.pop(), LCD_LINE_1)
|
||||
lcd_string(message.pop(), LCD_LINE_2)
|
||||
lcd_string(message.pop(), LCD_LINE_3)
|
||||
lcd_string(message.pop(), LCD_LINE_4)
|
||||
except:
|
||||
pass
|
||||
|
||||
time.sleep(9)
|
||||
|
||||
# Send some more text
|
||||
lcd_string("PU 27/05 Eksamen",LCD_LINE_1)
|
||||
lcd_string("MMI 01/06 Eksamen",LCD_LINE_2)
|
||||
lcd_string("DB 04/06 Eksamen", LCD_LINE_3)
|
||||
lcd_string("KTN 08/06 Eksamen",LCD_LINE_4)
|
||||
|
||||
time.sleep(9)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
lcd_byte(0x01, LCD_CMD)
|
||||
|
||||
14
plexLoop.py
Normal file
14
plexLoop.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from socket import *
|
||||
from time import sleep
|
||||
|
||||
host = '10.0.0.41'
|
||||
port = 12000
|
||||
|
||||
clientSocket = socket(AF_INET, SOCK_DGRAM)
|
||||
|
||||
clientSocket.sendto('plex', (host, port))
|
||||
message, address = clientSocket.recvfrom(1024)
|
||||
print message
|
||||
|
||||
|
||||
clientSocket.close()
|
||||
1
statusHandler
Submodule
1
statusHandler
Submodule
Submodule statusHandler added at fad4d2f7e2
202
statusHandler.py
Normal file
202
statusHandler.py
Normal file
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# March 6, 2016 Kevin Midboe Utleirvegen Trondheim
|
||||
# Python program that uses UDP to get and return info of server
|
||||
|
||||
# TODO
|
||||
# Have everything sent as JSON objects.
|
||||
# Threading for multiple accesses
|
||||
# Only have valid inputs, guess if slightly off.
|
||||
|
||||
import os
|
||||
from commands import getstatusoutput
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from unicodedata import normalize
|
||||
from subprocess import *
|
||||
from socket import *
|
||||
|
||||
# Define the socket communicating will transfered
|
||||
serverSocket = socket(AF_INET, SOCK_DGRAM)
|
||||
serverSocket.bind(('', 12000))
|
||||
|
||||
# TODO error handling
|
||||
# Function to get the temp of the cpu by getting ouput of unix command
|
||||
def temp():
|
||||
p = getstatusoutput("sensors -u | awk 'Core 0 {print $2} ' | sed -n 4p")[1]
|
||||
return str(p[:p.index('.')])
|
||||
|
||||
# Function that returns uptime time by getting unix command output
|
||||
def uptime():
|
||||
p = getstatusoutput("uptime")[1]
|
||||
return str(p)
|
||||
|
||||
# Get's info from session XML file by plex
|
||||
def plex():
|
||||
# Every call saves the info of session.xml to a file named plexPlaying
|
||||
os.system('curl --silent localhost:32400/status/sessions > ~/plexPy/plexPlaying.xml')
|
||||
|
||||
# XML parsing, creates a tree and saves the root node as root
|
||||
tree = ET.parse('plexPy/plexPlaying.xml')
|
||||
root = tree.getroot()
|
||||
|
||||
# The root node named MediaContainer has a size variable that holds number of active processes.
|
||||
# If this is '0' then there are none playing, no need to compute.
|
||||
if (root.get('size') != '0'):
|
||||
|
||||
# Get load of CPU and I/O
|
||||
return_text = '\n\t' + str(os.popen('cat /proc/loadavg').read())
|
||||
return_text += '\tCur: \t' + str(root.get('size')) + '\n'
|
||||
|
||||
# Goes through all the 'video' elements in MediaContainer
|
||||
for video in root.findall('Video'):
|
||||
if (video.get('type') == 'movie'):
|
||||
name = video.get('title')
|
||||
return_text += '\n\tTitle: \t' + name
|
||||
|
||||
elif (video.get('type') == 'episode'):
|
||||
parentName = video.get('grandparentTitle')
|
||||
name = video.get('title')
|
||||
return_text += '\n\tTitle: \t' + name + \
|
||||
'\n\tSeries: ' + parentName
|
||||
|
||||
progress = "{0:0.1f}".format(float(video.find('TranscodeSession').get('progress')))
|
||||
state = video.find('Player').get('state')
|
||||
player = video.find('Player').get('platform')
|
||||
user = video.find('User').get('title')
|
||||
|
||||
return_text += str('\n\tProg : \t' + str(progress) + '\n\tPlayer: ' + player + \
|
||||
'\n\tState: \t' + state + '\n\tUser: \t' + user + '\n')
|
||||
|
||||
try:
|
||||
return normalize('NFKD', return_text).encode('ascii', 'ignore')
|
||||
except TypeError:
|
||||
return return_text
|
||||
else:
|
||||
return 'Null playing'
|
||||
|
||||
|
||||
def i2c_plex():
|
||||
os.system('curl --silent localhost:32400/status/sessions > ~/plexPy/plexPlaying.xml')
|
||||
|
||||
# XML parsing, creates a tree and saves the root node as root
|
||||
tree = ET.parse('plexPy/plexPlaying.xml')
|
||||
root = tree.getroot()
|
||||
|
||||
# The root node named MediaContainer has a size variable that holds number of active processes.
|
||||
# If this is '0' then there are none playing, no need to compute.
|
||||
if (root.get('size') != '0'):
|
||||
# Get load of CPU and I/O
|
||||
return_text = str('$Playing: ' + str(root.get('size')))
|
||||
|
||||
# Goes through all the 'video' elements in MediaContainer
|
||||
for video in root.findall('Video'):
|
||||
if (video.get('type') == 'movie'):
|
||||
name = video.get('title') # Movie name
|
||||
|
||||
elif (video.get('type') == 'episode'):
|
||||
name = video.get('grandparentTitle') # Series name
|
||||
|
||||
user = video.find('User').get('title')
|
||||
|
||||
return_text += str('$' + user[:5] + ': ' + name).encode('utf8', 'ignore')
|
||||
|
||||
try:
|
||||
return normalize('NFKD', return_text).encode('utf8', 'ignore')
|
||||
except TypeError:
|
||||
return return_text
|
||||
else:
|
||||
return '$Null playing'
|
||||
|
||||
# TODO more logic in formatting the return string
|
||||
# Similar function as above, but formates the return string to better fit on I2C display
|
||||
def i2c_uptime():
|
||||
p = getstatusoutput("uptime") # Get's the output of unix command 'uptime'
|
||||
upOutput = p[1] # Saves the ending part of stirng to variable
|
||||
|
||||
# Under the handling and formatting of the output is put together and saved to string upOutput
|
||||
try:
|
||||
upOutput = upOutput[upOutput.index('up') + 2:upOutput.index('days') + 4]
|
||||
except ValueError:
|
||||
try:
|
||||
upOutput = upOutput[upOutput.index('up') + 2:upOutput.index('min') + 3]
|
||||
except ValueError:
|
||||
upOutput = upOutput[upOutput.index('up') + 3:upOutput.index(',')]
|
||||
|
||||
if (len(upOutput) > 5):
|
||||
return upOutput
|
||||
else:
|
||||
return ' ' + str(upOutput)
|
||||
|
||||
# TODO don't rely on nums, but logicaly pick out needed info
|
||||
# This function is costumized for I2C display and formates the output of unix command
|
||||
# 'uptime' to get the load of first and third value of the load
|
||||
def i2c_load():
|
||||
p = getstatusoutput("uptime")
|
||||
upOutput = p[1]
|
||||
loadIndex = upOutput.index('load average: ') + 14
|
||||
upOutput = upOutput[loadIndex:loadIndex + 2] + upOutput[loadIndex + 8:]
|
||||
return upOutput.replace(', ', ' ')
|
||||
|
||||
def get_space(text):
|
||||
try:
|
||||
text = text.split()
|
||||
key_index = text.index('space')
|
||||
dirName = '/media/' + text[key_index + 1]
|
||||
st = os.statvfs(dirName)
|
||||
|
||||
disk_free = st.f_frsize * st.f_bavail
|
||||
disk_total = st.f_frsize * st.f_blocks
|
||||
|
||||
space_output = space_format(disk_free)
|
||||
space_output += '/' + space_format(disk_total)
|
||||
|
||||
except OSError:
|
||||
space_output = dirName + ' is not a valid dir'
|
||||
|
||||
return space_output
|
||||
|
||||
def space_format(size):
|
||||
if len(str(size)) > 12:
|
||||
formated = float(size) / (1024)**4
|
||||
formated = "{0:0.1f}".format(formated) + 'T'
|
||||
else:
|
||||
formated = float(size) / (1024)**3
|
||||
formated = "{0:0.0f}".format(formated) + 'G'
|
||||
|
||||
return formated
|
||||
|
||||
|
||||
# This is a repeting loop that runs everytime a message is recv in socket
|
||||
while True:
|
||||
# Save the message and return address to variables.
|
||||
message, address = serverSocket.recvfrom(1024)
|
||||
|
||||
print(message, address) # Debug print
|
||||
|
||||
# This should prob be cases and not if's, but works to get the right info user requests.
|
||||
if (message == 'temp'):
|
||||
return_message = temp()
|
||||
elif (message == 'up'):
|
||||
return_message = uptime()
|
||||
elif (message == 'plex'):
|
||||
return_message = plex()
|
||||
elif (message.find('space') != -1):
|
||||
return_message = get_space(message)
|
||||
elif (message == 'i2c'):
|
||||
return_message = 'Uptime: ' + i2c_uptime() + '$' + \
|
||||
'Load: ' + i2c_load() + '$' + \
|
||||
'Temp: ' + temp() + ' celcius$' + \
|
||||
'Space: ' + get_space('space hdd1')
|
||||
return_message += i2c_plex()
|
||||
elif (message == 'i2c_plex'):
|
||||
return_message = i2c_plex()
|
||||
elif (message == '--help'):
|
||||
return_message = 'temp\nup\nspace {option}\n'
|
||||
else:
|
||||
return_message = 'none'
|
||||
|
||||
# Returns message to return address.
|
||||
serverSocket.sendto(return_message, address)
|
||||
|
||||
|
||||
8
test.py
Normal file
8
test.py
Normal file
@@ -0,0 +1,8 @@
|
||||
message = ['Uptime: 8 days', 'Load: 0.09 0.06', 'Temp: 29 celcius', 'Space: 0.9T/7.2T', 'Cur playing: 1', 'KevinMidboe:Angie Tribeca']
|
||||
|
||||
print(message)
|
||||
message.reverse()
|
||||
print(message)
|
||||
|
||||
for i in range(len(message)):
|
||||
print(message.pop())
|
||||
1
testXml.xml
Normal file
1
testXml.xml
Normal file
@@ -0,0 +1 @@
|
||||
<html><head><title>Unauthorized</title></head><body><h1>401 Unauthorized</h1></body></html>
|
||||
Reference in New Issue
Block a user