[ create a new paste ] login | about

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

meigrafd - Python, pasted on May 7:
from __future__ import print_function
import os.path
import bottle
from threading import Thread, Timer as threadTimer
from wsgiref.simple_server import make_server
from ws4py.websocket import WebSocket
from ws4py.server.wsgirefserver import WSGIServer, WebSocketWSGIRequestHandler
from ws4py.server.wsgiutils import WebSocketWSGIApplication
from random import randrange

DEBUG = 1
httpPort = 8080
websocketPort = 7070

#-------------------------------------------------------------------

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

def getUptime():
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        uptime = str(timedelta(seconds = uptime_seconds))
        return uptime

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 usedPerc

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

#-------------------------------------------------------------------

### Parse request from webif
#required format-> command:value
def WebRequestHandler(requestlist):
    returnlist = ""
    for request in requestlist:
        request =  request.strip()
        requestsplit = request.split(':')
        requestsplit.append("dummy")
        command = requestsplit[0]
        value = requestsplit[1]
        if value == "dummy":
            value = "0"

        if command == "localping":
            returnlist += "\n localping:ok"
        elif command == "LoadAVRnum":
            returnlist += "\n LoadAVRnum:"+open("/proc/loadavg").readline().split(" ")[:3][0]
        elif command == "Uptime":
            returnlist += "\n Uptime:"+str(getUptime()).split(".")[0]
        elif command == "RAMperc":
            returnlist += "\n RAMperc:"+str(getPiRAM())
            #returnlist += "\n RAMperc:"+str(psutil.phymem_usage().percent)
        elif command == "PiTEMP":
            returnlist += "\n PiTEMP:"+str(getPiTemperature())
        elif command == "System.Power":
            if value == "off":
                subprocess.Popen(["shutdown","-h","now"])
                return "System.Power:ok"
            elif value == "reboot":
                subprocess.Popen(["shutdown","-r","now"])
                return "System.Power:ok"
    return returnlist

def pushDataTimed(clients, what, when):
    what = str(what)
    when = float(when)
    for index, client in enumerate(clients):
        if client:
            client.send( WebRequestHandler(what.splitlines()) )
            timed = threadTimer( when, pushDataTimed, [clients, what, when] )
            timed.start()
            timers.append(timed)

class myWebSocketHandler(WebSocket):
    connections = []
    def opened(self):
        printD("New WebSocket client connected")
        self.send("You are connected")
        self.connections.append(self)
        timed = threadTimer( 2.0, pushDataTimed, [self.connections, "PiTEMP", "2.0"] )
        timed.start()
        timers.append(timed)
    def received_message(self, message):
        msg = message.data.decode()
        printD("Message from WebIf: >>>"+msg+"<<<")
        requestlist = msg.splitlines() 
        self.send(WebRequestHandler(requestlist))
    def closed(self, code, reason):
        printD("WebSocket closed %s %s" % (code, reason))
        self.connections.remove(self)

#-------------------------------------------------------------------

@bottle.route('/')
def MainHandler():
    values = {
                'test': randrange(1, 1000),
                'debug': 1,
             }
    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'))


try:
    timers = list()
    websocket_server = make_server(
        '', websocketPort,
        server_class=WSGIServer,
        handler_class=WebSocketWSGIRequestHandler,
        app=WebSocketWSGIApplication(handler_cls=myWebSocketHandler)
    )
    websocket_server.initialize_websockets_manager()
    # Start Child Thread for WebSocket
    print('Starting Child Thread for WebSocket_Server')
    ws = Thread(target=websocket_server.serve_forever)
    ws.setDaemon(True)
    ws.start()

    bottle.debug(True) #sollte spaeter ausgeschaltet werden!
    bottle.TEMPLATE_PATH.insert(0, os.path.join(os.path.dirname(__file__), 'templates'))
    bottle.run(host='0.0.0.0', port=httpPort, debug=True, quiet=False)
except KeyboardInterrupt:
    pass
finally:
    for index, timer in enumerate(timers):
        if timer:
            timer.cancel()
    print('Shutting down Servers')
    ws.join(1)
    try:
        ws.shutdown()
    except:
        pass


Create a new paste based on this one


Comments: