#!/usr/bin/env python3

from bottle import Bottle, request, response, template, static_file
import serial
import json
import time

app = application = Bottle()

serial_in_use = False

@app.route('/')
@app.route('/index.html')
def index():
    return template('index')

@app.route('/websocket')
def handle_websocket():
    global serial_in_use

    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')

    if serial_in_use:
        abort(503, 'Serial connection already in use.')

    with serial.Serial('/dev/ttyUSB0', 38400, timeout=10) as ser:
    #with open('/dev/null') as ser:
        serial_in_use = True
        print("Serial locked.")
        while True:
            try:
                line = ser.readline()
                #line = '{"vin": 1240, "vout": 15300, "iout": 817, "pout": 12345, "energy": 9387, "pwm": 314}\r\n'
                time.sleep(1)
                if line[0] != '{':
                    # print all lines that are probably not JSON
                    print(line)
                    continue

                data = json.loads(line)
                wsock.send(json.dumps(data))
            except json.JSONDecodeError:
                print(f"Failed to decode line as JSON: »{line}«.")
            except WebSocketError:
                break
        serial_in_use = False
        print("Serial unlocked.")


@app.route('/static/<filename:path>')
def send_static(filename):
    return static_file(filename, root='./static')

if __name__ == "__main__":
    from gevent.pywsgi import WSGIServer
    from geventwebsocket import WebSocketError
    from geventwebsocket.handler import WebSocketHandler
    server = WSGIServer(("0.0.0.0", 8080), app,
                        handler_class=WebSocketHandler)
    server.serve_forever()
