from flask import Flask, request, render_template_string
import serial
import threading
import time

# ---------------- SERIAL ----------------
ser = serial.Serial("/dev/ttyUSB1", 38400, timeout=0.1)
time.sleep(2)

# Shared buffer für Arduino Daten
latest_lines = []

lock = threading.Lock()

# ---------------- BACKGROUND READER ----------------
def read_serial():
    while True:
        try:
            line = ser.readline().decode(errors="ignore").strip()
            if line:
                with lock:
                    latest_lines.append(line)
                    if len(latest_lines) > 50:
                        latest_lines.pop(0)
        except:
            pass

threading.Thread(target=read_serial, daemon=True).start()

# ---------------- FLASK ----------------
app = Flask(__name__)

html = """
<!DOCTYPE html>
<html>
<head>
    <title>Motor Steuerung</title>

    <style>
        body {
            font-family: Arial;
            text-align: center;
            margin-top: 40px;
            background-color: #202020;
            color: white;
        }

        input[type=range] {
            width: 400px;
        }

        .value {
            font-size: 40px;
            margin: 20px;
        }

        #console {
            margin-top: 40px;
            width: 80%;
            height: 250px;
            background: black;
            color: #00ff00;
            text-align: left;
            padding: 10px;
            overflow-y: scroll;
            margin-left: auto;
            margin-right: auto;
            font-family: monospace;
        }
    </style>
</head>

<body>

<h1>Motor Steuerung</h1>

<div class="value">
    <span id="angle">90</span>°
</div>

<input type="range" min="0" max="180" value="90" id="slider">

<h3>Arduino Konsole</h3>
<div id="console"></div>

<script>
const slider = document.getElementById("slider");
const angleText = document.getElementById("angle");
const consoleBox = document.getElementById("console");

slider.oninput = function() {
    angleText.innerText = this.value;

    fetch("/set?angle=" + this.value);
};

function updateConsole() {
    fetch("/console")
        .then(res => res.json())
        .then(data => {
            consoleBox.innerHTML = data.join("<br>");
            consoleBox.scrollTop = consoleBox.scrollHeight;
        });
}

setInterval(updateConsole, 300);
</script>

</body>
</html>
"""

@app.route("/")
def index():
    return render_template_string(html)


@app.route("/set")
def set_angle():
    angle = request.args.get("angle", "90")
    cmd = f"MOTOR {angle}\n"

    ser.write(cmd.encode())

    print("Gesendet:", cmd.strip())
    return "OK"


@app.route("/console")
def console():
    with lock:
        return {"lines": latest_lines}


if __name__ == "__main__":
    print("Server läuft: http://0.0.0.0:5000")
    app.run(host="0.0.0.0", port=5000)