Major cleanup, added all old files (python2) to 'old_v0.1' folder

This commit is contained in:
2017-02-08 20:03:36 +01:00
parent 94e5389e44
commit c17ab40f6a
1507 changed files with 0 additions and 9841 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 MiB

Binary file not shown.

21
old_v0.1/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Kevin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

33
old_v0.1/README.md Normal file
View File

@@ -0,0 +1,33 @@
# Node Communication Handler
> A python application for communication with and through a centralized server.
### Core goals
Property | Status
---------|--------
Build status | this |
Test coverage | [![Coverage Status](https://coveralls.io/repos/bitbucket/trondaal/it2810-21-oppgave-3/badge.svg?branch=master)](https://coveralls.io/bitbucket/trondaal/it2810-21-oppgave-3?branch=master)
Deployment | [![](https://img.shields.io/badge/it2810%E1%A0%8621.idi.ntnu.no-running-green.svg)](http://it2810-21.idi.ntnu.no)
[![Status working](https://img.shields.io/badge/Status%20-working-brightgreen.svg?style=flat)](http://www.ted.com/talks/simon_sinek_how_great_leaders_inspire_action)
## Why? [![Status under dev](https://img.shields.io/badge/Status%20-under%20dev-47b2f6.svg?style=flat)](http://www.ted.com/talks/simon_sinek_how_great_leaders_inspire_action)
## Why? [![Status upgrade needed](https://img.shields.io/badge/Status%20-upgrade%20needed-f69e5a.svg?style=flat)](http://www.ted.com/talks/simon_sinek_how_great_leaders_inspire_action)
## Why? [![Status failing](https://img.shields.io/badge/Status%20-failing-red.svg?style=flat)](http://www.ted.com/talks/simon_sinek_how_great_leaders_inspire_action)
# statusHandler
- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [ ] Jupiter
- [ ] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley

View 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)

View File

@@ -0,0 +1,31 @@
## This is the header for this code snippet
This is more text on new line and more and more and more. And if there are anyone else that need help with their mental help.
Please contact me imideatly.
```py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Question
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
```

View File

@@ -0,0 +1,121 @@
"""
Django settings for apolloActivity project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'rsajp8un605qm00!vb9)5y025yel=hj45rd($#_g74ymt17z09'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'plex.apps.PlexConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'apolloActivity.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'apolloActivity.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'

View File

@@ -0,0 +1,23 @@
"""apolloActivity URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^plex/', include('plex.urls')),
url(r'^ip/', include('ip.urls')),
url(r'^admin/', include(admin.site.urls)),
]

View File

@@ -0,0 +1,16 @@
"""
WSGI config for apolloActivity project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apolloActivity.settings")
application = get_wsgi_application()

Binary file not shown.

View File

View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,5 @@
from django.apps import AppConfig
class IpConfig(AppConfig):
name = 'ip'

View File

@@ -0,0 +1,10 @@
from django.db import models
# Create your models here.
class Address(models.Model):
ip_address = models.CharField(max_length=50)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,14 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: KevinMidboe
# @Date: 2016-11-23 20:43:37
# @Last Modified by: KevinMidboe
# @Last Modified time: 2016-11-23 20:43:50
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]

View File

@@ -0,0 +1,7 @@
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the ip index.")

View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apolloActivity.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)

View File

View File

@@ -0,0 +1,6 @@
from django.contrib import admin
# Register your models here.
from .models import Address
admin.site.register(Address)

View File

@@ -0,0 +1,5 @@
from django.apps import AppConfig
class PlexConfig(AppConfig):
name = 'plex'

View File

@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-23 20:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Address',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ip_address', models.CharField(max_length=200)),
('first_connect', models.DateTimeField(verbose_name='date first accessed on address')),
],
),
migrations.CreateModel(
name='Location',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ip_version', models.CharField(max_length=1)),
('country', models.CharField(max_length=100)),
('city', models.CharField(max_length=100)),
('region', models.CharField(max_length=100)),
('postal_code', models.IntegerField(max_length=6)),
('address', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='plex.Address')),
],
),
]

View File

@@ -0,0 +1,25 @@
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Address(models.Model):
ip_address = models.CharField(max_length=200)
first_connect = models.DateTimeField('date first accessed on address')
def created_recently(self):
return self.first_connect >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
return self.ip_address
class Location(models.Model):
address = models.ForeignKey(Address, on_delete=models.CASCADE)
ip_version = models.IntegerField(default=4)
country = models.CharField(max_length=100)
city = models.CharField(max_length=100)
region = models.CharField(max_length=100)
postal_code = models.IntegerField(default=0)
def __str__(self):
return str([self.country, self.city, self.region])

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@@ -0,0 +1,14 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: KevinMidboe
# @Date: 2016-11-23 20:43:37
# @Last Modified by: KevinMidboe
# @Last Modified time: 2016-11-23 20:43:50
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]

View File

@@ -0,0 +1,7 @@
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the plex index.")

8
old_v0.1/foo.xml Normal file
View 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
old_v0.1/getPlaying.py Normal file
View 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()

39
old_v0.1/ipLookup.py Normal file
View File

@@ -0,0 +1,39 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: KevinMidboe
# @Date: 2016-11-22 12:07:08
# @Last Modified by: KevinMidboe
# @Last Modified time: 2016-11-28 08:14:35
import geoip2.database
import ipaddress, os
class ipLookup(object):
"""docstring for ipLookup"""
def __init__(self, address):
super(ipLookup, self).__init__()
self.databaseLocation = 'GeoLiteDatabases/city.mmdb'
self.address = ipaddress.ip_address(address)
self.version = self.address.version
self.getLocation()
def getLocation(self):
reader = geoip2.database.Reader(self.databaseLocation)
response = reader.city(self.address)
self.country = response.country.name
self.city = response.city.name
self.region = response.subdivisions.most_specific.name
self.postcode = response.postal.code
def changeDatabase(self, database):
newDatabaseLocation = 'GeoLiteDatabases/'+database+'.mmdb'
if os.path.isfile(newDatabaseLocation):
self.databaseLocation = newDatabaseLocation
else:
raise NameError('File '+newDatabaseLocation+' does not exist')
def getDatabaseLocation(self):
return self.databaseLocation
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)

82
old_v0.1/jsonPlex.py Normal file
View 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
old_v0.1/jsonTest.py Normal file
View 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
old_v0.1/lcd_i2c.py Normal file
View 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)

12
old_v0.1/old_testUptime.py Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: KevinMidboe
# @Date: 2016-11-22 16:08:17
# @Last Modified by: KevinMidboe
# @Last Modified time: 2016-11-22 17:07:52
import uptime
if __name__ == '__main__':
uptimeClass = uptime.uptime()
print(uptimeClass)

34
old_v0.1/old_uptime.py Normal file
View File

@@ -0,0 +1,34 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: KevinMidboe
# @Date: 2016-11-22 16:05:18
# @Last Modified by: KevinMidboe
# @Last Modified time: 2016-11-22 17:07:41
import subprocess, re
class uptime(object):
"""docstring for uptime"""
def __init__(self):
super(uptime, self).__init__()
raw = subprocess.Popen('uptime', stdout=subprocess.PIPE)
output, error = raw.communicate()
uptimeList = output.decode('utf-8').split(', ')
self.duration(uptimeList[0])
self.users(uptimeList[2])
self.load(uptimeList[3])
def duration(self, outputString):
self.duration = re.sub(r'.*up ', '', outputString)
def users(self, outputString):
self.users = outputString
def load(self, outputString):
loadValues = re.sub(r'.*load averages: ', '', outputString)
self.load = re.sub(r'\n', '', loadValues)
self.load_minute, self.load_fiveminute, self.load_fiftenminute = self.load.split(' ')
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)

14
old_v0.1/plexLoop.py Normal file
View 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()

212
old_v0.1/statusHandler.py Executable file
View File

@@ -0,0 +1,212 @@
#!/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 *
# from uptime import timeSinceBoot
# 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 10.0.0.41: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 10.0.0.41: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
def pirate(message):
# TODO handle output from call, and better magnet parse
magnet = message.replace('pirate ', '')
print(magnet)
raw = call(['transmission-remote', '-a', magnet])
return 'Added magnet'
# 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'
elif ('pirate' in message):
return_message = pirate(message)
else:
return_message = 'none'
# Returns message to return address.
serverSocket.sendto(return_message, address)

8
old_v0.1/test.py Normal file
View 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())

18
old_v0.1/testIpLookup.py Executable file
View File

@@ -0,0 +1,18 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: KevinMidboe
# @Date: 2016-11-22 12:18:17
# @Last Modified by: KevinMidboe
# @Last Modified time: 2016-12-01 20:12:48
import ipLookup
if __name__ == '__main__':
ipList = {}
ip = '91.22.128.66'
ip = '85.164.178.87'
if ip not in ipList:
ipList.update({ip:ipLookup.ipLookup(ip)})
address = ipList[ip]
print(address)

1
old_v0.1/testXml.xml Normal file
View File

@@ -0,0 +1 @@
<html><head><title>Unauthorized</title></head><body><h1>401 Unauthorized</h1></body></html>