[ create a new paste ] login | about

Link: http://codepad.org/52oDG5ES    [ raw code | fork ]

meigrafd - Python, pasted on May 23:
from __future__ import print_function
import os.path
import bottle
import json
from datetime import timedelta
from random import randrange

DEBUG = 1

bottle.debug(True) #sollte spaeter ausgeschaltet werden!
bottle.TEMPLATE_PATH.insert(0, os.path.join(os.path.dirname(__file__), 'templates'))

def printD(message):
    if DEBUG:
        print(message)

def getPiRAM():
    with open('/proc/meminfo', 'r') as mem:
        tmp = 0
        for i in mem:
            sline = i.split()
            if str(sline[0]) == 'MemTotal:':
                total = int(sline[1])
            elif str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'): 
                tmp += int(sline[1])
        free = tmp
        used = int(total) - int(free)
        usedPerc = (used * 100) / total
        return free

def getPiTemperature():
    with open("/sys/class/thermal/thermal_zone0/temp", 'r') as f:
        content = f.read().splitlines()
        return float(content[0]) / 1000.0

@bottle.route('/')
def MainHandler():
    values = {
        'test': randrange(1, 1000),
        'debug': DEBUG,
    }
    return bottle.template('index.html', values)

@bottle.route('/static/<filename>')
def StaticHandler(filename):
    if filename.endswith(".css"):
        bottle.response.content_type = 'text/css'
    elif filename.endswith(".js"):
        bottle.response.content_type = 'text/javascript'
    elif filename.endswith(".png"):
        bottle.response.content_type = 'image/png'   
    return bottle.static_file(filename, root=os.path.join(os.path.dirname(__file__), 'static'))

@bottle.route('/data/')
def TelemetryHandler():
    printD("Telemetry Request.")
    bottle.response.content_type = 'application/json'
    data = {}
    data["PiTEMP"] = getPiTemperature()
    data["PiRAM"] = getPiRAM()
    return json.dumps(data)

@bottle.route('/cmd/<command>')
def CommandHandler(command):
    response = ''
    printD("Command Request: {}".format(command))
    if command == 'PiTEMP':
        response = getPiTemperature()
    elif command == 'PiRAM':
        response = getPiRAM()
    printD("response: %s"% response)
    return str(response)

@bottle.error(404)
def error404(error):
    return 'Error 404: Nothing here, sorry.'

try:
    bottle.run(host='0.0.0.0', port=8080, quiet=True)
except (KeyboardInterrupt, SystemExit):
    print('\nQuit\n')


Create a new paste based on this one


Comments: