next step - index.html, app.js, custom.css and config example
This commit is contained in:
parent
1434f35f8b
commit
8955cff47b
153
app.py
153
app.py
@ -1,134 +1,81 @@
|
|||||||
import json
|
# app.py
|
||||||
import os
|
import os
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
from flask import Flask, render_template, jsonify, request, send_from_directory, redirect, url_for
|
from flask import Flask, render_template, redirect, url_for, send_from_directory, request, jsonify
|
||||||
|
|
||||||
from mkconnect.mouldking.MouldKing import MouldKing
|
|
||||||
from mkconnect.tracer.TracerConsole import TracerConsole
|
|
||||||
from mkconnect.advertiser.AdvertiserBTSocket import AdvertiserBTSocket
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
# Konfiguration
|
||||||
app.config['CONFIG_DIR'] = 'configs'
|
app.config['CONFIG_DIR'] = 'configs'
|
||||||
os.makedirs(app.config['CONFIG_DIR'], exist_ok=True)
|
os.makedirs(app.config['CONFIG_DIR'], exist_ok=True)
|
||||||
|
|
||||||
# Logging setup
|
# Logging
|
||||||
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
logging.basicConfig(
|
||||||
|
filename='app.log',
|
||||||
|
level=logging.INFO,
|
||||||
|
format='%(asctime)s | %(levelname)-8s | %(message)s',
|
||||||
|
datefmt='%Y-%m-%d %H:%M:%S'
|
||||||
|
)
|
||||||
|
|
||||||
tracer = TracerConsole()
|
logger = logging.getLogger(__name__)
|
||||||
advertiser = AdvertiserBTSocket()
|
|
||||||
|
|
||||||
current_hub = None
|
|
||||||
current_config = None
|
|
||||||
|
|
||||||
def load_configs():
|
def load_configs():
|
||||||
|
"""Liest alle .json Dateien aus dem configs-Ordner"""
|
||||||
configs = []
|
configs = []
|
||||||
for file in os.listdir(app.config['CONFIG_DIR']):
|
if not os.path.exists(app.config['CONFIG_DIR']):
|
||||||
if file.endswith('.json'):
|
|
||||||
with open(os.path.join(app.config['CONFIG_DIR'], file)) as f:
|
|
||||||
cfg = json.load(f)
|
|
||||||
cfg['filename'] = file
|
|
||||||
configs.append(cfg)
|
|
||||||
return configs
|
return configs
|
||||||
|
|
||||||
|
for filename in os.listdir(app.config['CONFIG_DIR']):
|
||||||
|
if filename.lower().endswith('.json'):
|
||||||
|
path = os.path.join(app.config['CONFIG_DIR'], filename)
|
||||||
|
try:
|
||||||
|
with open(path, 'r', encoding='utf-8') as f:
|
||||||
|
data = json.load(f)
|
||||||
|
data['filename'] = filename
|
||||||
|
# Optional: name fallback, falls nicht vorhanden
|
||||||
|
data.setdefault('name', filename.replace('.json', '').replace('_', ' ').title())
|
||||||
|
configs.append(data)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Fehler beim Laden von {filename}: {e}")
|
||||||
|
return sorted(configs, key=lambda x: x.get('name', ''))
|
||||||
|
|
||||||
|
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
def index():
|
def index():
|
||||||
return render_template('index.html', configs=load_configs())
|
configs = load_configs()
|
||||||
|
return render_template('index.html', configs=configs)
|
||||||
|
|
||||||
|
|
||||||
@app.route('/load_config/<filename>')
|
@app.route('/load_config/<filename>')
|
||||||
def load_config(filename):
|
def load_config(filename):
|
||||||
global current_config
|
# Später: Config in Session speichern oder global (für Entwicklung erstmal redirect)
|
||||||
|
# Hier nur redirect zur Steuerseite – echte Logik kommt später
|
||||||
path = os.path.join(app.config['CONFIG_DIR'], filename)
|
path = os.path.join(app.config['CONFIG_DIR'], filename)
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
return "Config not found", 404
|
return "Konfigurationsdatei nicht gefunden", 404
|
||||||
with open(path) as f:
|
|
||||||
current_config = json.load(f)
|
|
||||||
current_config['filename'] = filename
|
|
||||||
return redirect(url_for('control_page'))
|
|
||||||
|
|
||||||
@app.route('/control')
|
# Für den Moment nur redirect – später speichern wir current_config
|
||||||
def control_page():
|
return redirect(url_for('control_page', filename=filename))
|
||||||
if not current_config:
|
|
||||||
return redirect(url_for('index'))
|
|
||||||
return render_template('control.html', config=current_config)
|
|
||||||
|
|
||||||
@app.route('/api/connect', methods=['POST'])
|
|
||||||
def connect():
|
|
||||||
global current_hub
|
|
||||||
if not current_config:
|
|
||||||
return jsonify({"error": "Keine Config geladen"}), 400
|
|
||||||
try:
|
|
||||||
hub_id = current_config['hub_id']
|
|
||||||
current_hub = MouldKing(hub_id=hub_id, advertiser=advertiser, tracer=tracer)
|
|
||||||
current_hub.connect()
|
|
||||||
logging.info(f"Verbunden mit Hub {hub_id} für {current_config['name']}")
|
|
||||||
return jsonify({"status": "connected"})
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(f"Connect-Fehler: {str(e)}")
|
|
||||||
return jsonify({"error": str(e)}), 500
|
|
||||||
|
|
||||||
@app.route('/api/control', methods=['POST'])
|
@app.route('/control/<filename>')
|
||||||
def control():
|
def control_page(filename):
|
||||||
if not current_hub:
|
# Später: Config laden und übergeben
|
||||||
return jsonify({"error": "Nicht verbunden"}), 400
|
# Aktuell nur Dummy-Template
|
||||||
data = request.json
|
return render_template('control.html', filename=filename)
|
||||||
port = data['port']
|
|
||||||
value = float(data['value'])
|
|
||||||
|
|
||||||
ch = next((c for c in current_config['channels'] if c['port'] == port), None)
|
|
||||||
if not ch:
|
|
||||||
return jsonify({"error": "Port nicht in Config"}), 400
|
|
||||||
|
|
||||||
if ch.get('negative_only', False) and value > 0:
|
|
||||||
value = -abs(value) # Force negative
|
|
||||||
|
|
||||||
if ch.get('invert', False):
|
|
||||||
value = -value
|
|
||||||
|
|
||||||
if ch['type'] != 'motor':
|
|
||||||
value = ch.get('on_value', 1.0) if value != 0 else ch.get('off_value', 0.0)
|
|
||||||
|
|
||||||
try:
|
|
||||||
current_hub.set_motor(channel=port, power=value) # Passe an reale Methode an
|
|
||||||
logging.info(f"Control: {port} @ {value}")
|
|
||||||
return jsonify({"status": "ok"})
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(f"Control-Fehler: {str(e)}")
|
|
||||||
return jsonify({"error": str(e)}), 500
|
|
||||||
|
|
||||||
@app.route('/api/stop_all', methods=['POST'])
|
|
||||||
def stop_all():
|
|
||||||
if current_hub:
|
|
||||||
current_hub.stop_all()
|
|
||||||
logging.info("Alle gestoppt")
|
|
||||||
return jsonify({"status": "ok"})
|
|
||||||
|
|
||||||
@app.route('/admin')
|
|
||||||
def admin():
|
|
||||||
return render_template('admin.html', configs=load_configs())
|
|
||||||
|
|
||||||
@app.route('/admin/edit/<filename>', methods=['GET', 'POST'])
|
|
||||||
def edit_config(filename):
|
|
||||||
path = os.path.join(app.config['CONFIG_DIR'], filename)
|
|
||||||
if request.method == 'POST':
|
|
||||||
data = request.form['config']
|
|
||||||
with open(path, 'w') as f:
|
|
||||||
json.dump(json.loads(data), f, indent=4)
|
|
||||||
return redirect(url_for('admin'))
|
|
||||||
if not os.path.exists(path):
|
|
||||||
return "Not found", 404
|
|
||||||
with open(path) as f:
|
|
||||||
config = json.load(f)
|
|
||||||
return render_template('edit.html', config=json.dumps(config, indent=4), filename=filename)
|
|
||||||
|
|
||||||
@app.route('/admin/logs')
|
|
||||||
def view_logs():
|
|
||||||
with open('app.log') as f:
|
|
||||||
logs = f.read()
|
|
||||||
return render_template('logs.html', logs=logs)
|
|
||||||
|
|
||||||
@app.route('/configs/<path:filename>')
|
@app.route('/configs/<path:filename>')
|
||||||
def serve_config_file(filename):
|
def serve_config_file(filename):
|
||||||
|
"""Bilder und andere Dateien aus configs/ ausliefern"""
|
||||||
return send_from_directory(app.config['CONFIG_DIR'], filename)
|
return send_from_directory(app.config['CONFIG_DIR'], filename)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/admin')
|
||||||
|
def admin():
|
||||||
|
return render_template('admin.html')
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app.run(host='0.0.0.0', port=5050, debug=True)
|
app.run(host='0.0.0.0', port=5050, debug=True)
|
||||||
BIN
configs/testlok.jpg
Normal file
BIN
configs/testlok.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 181 KiB |
7
configs/testlok.json
Normal file
7
configs/testlok.json
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
|
||||||
|
{
|
||||||
|
"name": "Test Dampflok",
|
||||||
|
"image": "testlok.jpg",
|
||||||
|
"hub_id": 0,
|
||||||
|
"hub_type": "4channel"
|
||||||
|
}
|
||||||
@ -5,3 +5,14 @@ body {
|
|||||||
.card {
|
.card {
|
||||||
margin-bottom: 1.5rem;
|
margin-bottom: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.card-img-top {
|
||||||
|
background-color: #e9ecef;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
transition: transform 0.15s ease-in-out;
|
||||||
|
}
|
||||||
|
.card:hover {
|
||||||
|
transform: translateY(-4px);
|
||||||
|
box-shadow: 0 8px 16px rgba(0,0,0,0.15) !important;
|
||||||
|
}
|
||||||
@ -1,2 +1,7 @@
|
|||||||
// app.js – gemeinsames JavaScript
|
// app.js – gemeinsames JavaScript
|
||||||
console.log("MK Control JS geladen");
|
console.log("MK Control JS geladen");
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
console.log('MK Control Frontend geladen');
|
||||||
|
// Hier kommen später alle Fetch-Logiken, Slider-Handler etc. rein
|
||||||
|
});
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Zugmodelle auswählen{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<div class="container my-4">
|
||||||
|
<h1 class="mb-4 text-center">Wähle dein Zugmodell</h1>
|
||||||
|
|
||||||
|
{% if configs %}
|
||||||
|
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
|
||||||
|
{% for cfg in configs %}
|
||||||
|
<div class="col">
|
||||||
|
<div class="card h-100 shadow-sm">
|
||||||
|
{% if cfg.image %}
|
||||||
|
<img src="{{ url_for('serve_config_file', filename=cfg.image) }}"
|
||||||
|
class="card-img-top" alt="{{ cfg.name }}"
|
||||||
|
style="height: 180px; object-fit: cover;">
|
||||||
|
{% else %}
|
||||||
|
<div class="card-img-top bg-light d-flex align-items-center justify-content-center"
|
||||||
|
style="height: 180px;">
|
||||||
|
<i class="bi bi-train-freight-front fs-1 text-muted"></i>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="card-body d-flex flex-column">
|
||||||
|
<h5 class="card-title">{{ cfg.name }}</h5>
|
||||||
|
<p class="card-text text-muted small">
|
||||||
|
Hub-ID: {{ cfg.hub_id | default('?') }} •
|
||||||
|
{{ cfg.hub_type | default('unbekannt') }}
|
||||||
|
</p>
|
||||||
|
<div class="mt-auto">
|
||||||
|
<a href="{{ url_for('load_config', filename=cfg.filename) }}"
|
||||||
|
class="btn btn-primary w-100">
|
||||||
|
Auswählen & Steuern
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="alert alert-info text-center my-5">
|
||||||
|
<h4>Noch keine Konfigurationen vorhanden</h4>
|
||||||
|
<p>Lege im <code>configs/</code>-Ordner JSON-Dateien an oder gehe zum <a href="{{ url_for('admin') }}">Admin-Bereich</a>.</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="text-center mt-5">
|
||||||
|
<a href="{{ url_for('admin') }}" class="btn btn-outline-secondary">
|
||||||
|
<i class="bi bi-gear me-2"></i>Admin-Bereich
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
Loading…
x
Reference in New Issue
Block a user