First test app thing.

This commit is contained in:
Kalzu Rekku 2025-02-25 17:51:06 +02:00
commit a9a4709a07
3 changed files with 80 additions and 0 deletions

20
frontend.js Normal file
View File

@ -0,0 +1,20 @@
function updateLights(state) {
document.getElementById("red").classList.toggle("red", state === "red");
document.getElementById("green").classList.toggle("green", state === "green");
}
function fetchStatus() {
fetch("/status")
.then(response => response.json())
.then(data => updateLights(data.state))
.catch(console.error);
}
function toggleLight() {
fetch("/toggle", { method: "POST" })
.then(response => response.json())
.then(data => updateLights(data.state))
.catch(console.error);
}
setInterval(fetchStatus, 1000);

33
main.py Normal file
View File

@ -0,0 +1,33 @@
from flask import Flask, render_template, jsonify
import threading
import time
app = Flask(__name__)
current_state = "red"
lock = threading.Lock()
def reset_to_red():
global current_state
time.sleep(10)
with lock:
current_state = "red"
@app.route("/")
def index():
return render_template("site_template.j2", state=current_state)
@app.route("/status")
def status():
return jsonify({"state": current_state})
@app.route("/toggle", methods=["POST"])
def toggle():
global current_state
with lock:
if current_state != "green":
current_state = "green"
threading.Thread(target=reset_to_red, daemon=True).start()
return jsonify({"state": current_state})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)

27
site_template.j2 Normal file
View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Traffic Light</title>
<style>
body { text-align: center; font-family: Arial, sans-serif; }
.light-container { display: inline-block; margin-top: 50px; }
.light { width: 80px; height: 80px; margin: 10px; border-radius: 50%; background: gray; }
.red { background: red; }
.yellow { background: yellow; }
.green { background: green; }
</style>
<script src="frontend.js" defer></script>
</head>
<body>
<h1>Traffic Light</h1>
<div class="light-container">
<div id="red" class="light {% if state == 'red' %}red{% endif %}"></div>
<div id="yellow" class="light"></div>
<div id="green" class="light {% if state == 'green' %}green{% endif %}"></div>
</div>
<br>
<button onclick="toggleLight()">Toggle Green</button>
</body>
</html>