Tablett zuornung update
Build und Push Docker Image / build-and-push (push) Successful in 11s

This commit is contained in:
2026-11-05 08:53:55 +01:00
parent 4f6a4952d9
commit c954696d56
9 changed files with 291 additions and 62 deletions
+157 -44
View File
@@ -23,7 +23,7 @@ import hmac
import re
import tempfile
import uuid
from datetime import date
from datetime import date, datetime, timezone
import openpyxl
from openpyxl.styles import Font
@@ -1750,17 +1750,19 @@ def leitstand_import():
# Gerät eine zufällige Kennung (Cookie) und wird in der Tabelle "Tablets"
# registriert. Im Admin-Bereich (/start_tablets, passwortgeschützt) wird ihm
# eine Zielseite zugeordnet; das Tablet wird dann dorthin weitergeleitet und
# folgt späteren Änderungen der Zuordnung selbst (kleines Skript, alle 20 s).
# folgt späteren Änderungen der Zuordnung selbst (kleines Skript, siehe TABLET_ABFRAGE_SEKUNDEN).
TABLET_COOKIE = "hbh_tablet"
# Chrome begrenzt die Cookie-Laufzeit ohnehin auf 400 Tage; das Cookie wird bei
# jedem Aufruf von /tablet und jeder Abfrage (alle 20 s) erneuert.
# jedem Aufruf von /tablet und jeder Abfrage erneuert.
TABLET_COOKIE_MAX_ALTER = 400 * 24 * 3600
TABLET_ONLINE_SEKUNDEN = 90
# Abstand der Tablet-Abfragen (Lebenszeichen + Zuordnung). Ein Tablet gilt als
# online, solange die letzte Meldung höchstens 2,5 Abfragen zurückliegt.
TABLET_ABFRAGE_SEKUNDEN = 60
TABLET_ONLINE_SEKUNDEN = int(TABLET_ABFRAGE_SEKUNDEN * 2.5)
TABLET_ZIELE = {
"maschine": "Maschinenseite",
"show": "Anzeige (Show)",
"start": "Startseite Produktionsleiter",
"auswahl": "Maschinen-Auswahl",
}
# Kennung: zufällig (32 Hex-Zeichen) oder per Link vorgegeben (?id=<Seriennummer>)
_TABLET_KENNUNG_RE = re.compile(r"^[A-Za-z0-9._-]{3,64}$")
@@ -1834,9 +1836,14 @@ def _tablet_lernen():
neu = uuid.uuid4().hex
cur.execute(
'INSERT INTO "Tablets" (kennung, name, ziel_typ, maschine_id, erstellt_am, zuletzt_gesehen) '
'VALUES (%s, %s, %s, %s, %s, %s)',
'VALUES (%s, %s, %s, %s, %s, %s) RETURNING *',
(neu, f"Tablet {_tablet_kurzkennung(neu)} (gelernt)", typ, maschine_id, now_ts(), now_ts()),
)
gelernt = cur.fetchone()
tablet_log(
cur, "Automatisch gelernt",
f"Über {request.path} erkannt, zugeordnet: {_ziel_text(cur, typ, maschine_id)}", gelernt,
)
g.tablet_neu = neu
except Exception as exc: # Seitenanzeige darf nie am Lernmodus scheitern
log.warning("Tablet-Lernmodus fehlgeschlagen: %s", exc)
@@ -1855,8 +1862,6 @@ def _tablet_ziel_pfad(cur, tablet):
typ = tablet["ziel_typ"]
if typ == "start":
return url_for("leitstand_home")
if typ == "auswahl":
return url_for("leitstand_maschinen")
if typ in ("maschine", "show") and tablet["maschine_id"] is not None:
cur.execute('SELECT 1 FROM "Maschinen" WHERE id = %s', (tablet["maschine_id"],))
if cur.fetchone():
@@ -1871,6 +1876,43 @@ def _tablet_cookie_setzen(antwort, kennung):
)
def _anfrage_ip():
"""IP des Anfragenden (hinter einem Proxy aus X-Forwarded-For); nur zur Information."""
weiter = (request.headers.get("X-Forwarded-For") or "").split(",")[0].strip()
return (weiter or request.remote_addr or "")[:64]
def _ziel_text(cur, typ, maschine_id):
"""Lesbare Beschreibung einer Zuordnung für den Änderungsverlauf."""
if typ not in TABLET_ZIELE:
return "nicht zugeordnet"
if typ == "start":
return TABLET_ZIELE["start"]
cur.execute('SELECT name FROM "Maschinen" WHERE id = %s', (maschine_id,))
m = cur.fetchone()
name = (m["name"] if m and m["name"] else f"Maschine {int(maschine_id)}") if maschine_id is not None else "?"
return f"{TABLET_ZIELE[typ]} {name}"
TABLET_VERLAUF_AUFBEWAHRUNG_SEKUNDEN = 400 * 24 * 3600
def tablet_log(cur, aktion, details, tablet=None):
"""Schreibt einen Eintrag in den Änderungsverlauf der Tablets. `tablet` ist
ein Datensatz (id, kennung, name) oder None (z.B. Lernmodus). Name und
Kennung werden kopiert, damit der Eintrag auch nach dem Entfernen lesbar bleibt."""
jetzt = now_ts()
cur.execute(
'INSERT INTO "Tablet_Verlauf" (zeitpunkt, tablet_id, kennung, tablet_name, aktion, details, von_ip) '
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
(
jetzt, tablet["id"] if tablet else None, tablet["kennung"] if tablet else None,
tablet["name"] if tablet else None, aktion, details, _anfrage_ip(),
),
)
cur.execute('DELETE FROM "Tablet_Verlauf" WHERE zeitpunkt < %s', (jetzt - TABLET_VERLAUF_AUFBEWAHRUNG_SEKUNDEN,))
def _tablet_nocache(antwort):
antwort.headers["Cache-Control"] = "no-store"
return antwort
@@ -1891,6 +1933,7 @@ def _tablet_kontext():
return {
"tablet_ziel": _tablet_ziel_pfad(cur, tablet) or url_for("tablet_start"),
"tablet_code": _tablet_kurzkennung(tablet["kennung"]),
"tablet_intervall": TABLET_ABFRAGE_SEKUNDEN,
}
except Exception as exc: # Seitenanzeige darf nie an der Tablet-Funktion scheitern
log.warning("Tablet-Kontext nicht ermittelbar: %s", exc)
@@ -1907,35 +1950,36 @@ def tablet_start():
else:
ungueltige_id = False
def anlegen(cur, kennung, quelle):
cur.execute(
'INSERT INTO "Tablets" (kennung, name, erstellt_am, zuletzt_gesehen) VALUES (%s, %s, %s, %s) RETURNING *',
(kennung, f"Tablet {_tablet_kurzkennung(kennung)}", now_ts(), now_ts()),
)
neu = cur.fetchone()
tablet_log(cur, "Neu registriert", quelle, neu)
return neu
with db.get_cursor() as cur:
tablet = _tablet_aus_cookie(cur)
cookie_setzen = None
if link_id:
if tablet and tablet["kennung"] == link_id:
pass
else:
if not (tablet and tablet["kennung"] == link_id):
cur.execute('SELECT * FROM "Tablets" WHERE kennung = %s', (link_id,))
vorhanden = cur.fetchone()
if vorhanden:
tablet = vorhanden
elif tablet:
# bisher zufällig registriertes Gerät behält Name und Zuordnung
alt_kennung = tablet["kennung"]
cur.execute('UPDATE "Tablets" SET kennung = %s WHERE id = %s RETURNING *', (link_id, tablet["id"]))
tablet = cur.fetchone()
tablet_log(cur, "Kennung geändert", f"Per Link gesetzt: {alt_kennung} → {link_id}", tablet)
else:
cur.execute(
'INSERT INTO "Tablets" (kennung, name, erstellt_am, zuletzt_gesehen) VALUES (%s, %s, %s, %s) RETURNING *',
(link_id, f"Tablet {_tablet_kurzkennung(link_id)}", now_ts(), now_ts()),
)
tablet = cur.fetchone()
tablet = anlegen(cur, link_id, f"Über /tablet?id={link_id}")
cookie_setzen = link_id
if not tablet:
cookie_setzen = uuid.uuid4().hex
cur.execute(
'INSERT INTO "Tablets" (kennung, name, erstellt_am, zuletzt_gesehen) VALUES (%s, %s, %s, %s) RETURNING *',
(cookie_setzen, f"Tablet {_tablet_kurzkennung(cookie_setzen)}", now_ts(), now_ts()),
)
tablet = cur.fetchone()
tablet = anlegen(cur, cookie_setzen, "Über /tablet")
else:
cur.execute('UPDATE "Tablets" SET zuletzt_gesehen = %s WHERE id = %s', (now_ts(), tablet["id"]))
ziel = _tablet_ziel_pfad(cur, tablet)
@@ -1956,7 +2000,7 @@ def tablet_start():
@app.route("/tablet/ziel")
def tablet_ziel():
"""Wird vom Tablet alle 20 s abgefragt: Lebenszeichen + aktuelle Zuordnung."""
"""Wird vom Tablet regelmäßig abgefragt: Lebenszeichen + aktuelle Zuordnung."""
with db.get_cursor() as cur:
tablet = _tablet_aus_cookie(cur)
if not tablet:
@@ -1981,8 +2025,9 @@ def _vor_zeit(sekunden):
def _tablet_anzeige(cur):
"""Tablets für die Admin-Liste (unzugeordnete zuerst)."""
cur.execute('SELECT * FROM "Tablets" ORDER BY (ziel_typ IS NULL) DESC, name ASC, id ASC')
"""Tablets für die Admin-Liste. Feste Reihenfolge (Registrierung), damit
Zeilen beim Speichern nicht herumspringen."""
cur.execute('SELECT * FROM "Tablets" ORDER BY id ASC')
jetzt = now_ts()
tablets = cur.fetchall()
for t in tablets:
@@ -1994,21 +2039,28 @@ def _tablet_anzeige(cur):
return tablets
def _tablets_seite(error=None, info=None):
def _tablets_seite(error=None, gespeichert_id=None, fehler_id=None):
with db.get_cursor() as cur:
return render_template(
"tablets_verwaltung.html", title="Tablets", subtitle="Geräten eine Seite zuordnen",
tablets=_tablet_anzeige(cur), maschinen=get_maschinen_liste(cur), ziele=TABLET_ZIELE,
lernmodus=tablet_lernmodus_aktiv(cur),
lernmodus=tablet_lernmodus_aktiv(cur), abfrage_sekunden=TABLET_ABFRAGE_SEKUNDEN,
online_sekunden=TABLET_ONLINE_SEKUNDEN,
tablet_url=request.host_url.rstrip("/") + url_for("tablet_start"),
error=error, info=info,
error=None if fehler_id else error, zeilenfehler=error if fehler_id else None,
gespeichert_id=gespeichert_id, fehler_id=fehler_id,
)
def _zur_tablet_zeile(tablet_id, **args):
"""Zurück zur Liste, direkt an die Zeile des Tablets (Seite springt nicht nach oben)."""
return redirect(url_for("tablets_verwaltung", ok=tablet_id, **args) + f"#tablet-{tablet_id}")
@app.route("/start_tablets")
@require_maschinen_auth
def tablets_verwaltung():
return _tablets_seite(info="Zuordnung gespeichert." if request.args.get("ok") else None)
return _tablets_seite(gespeichert_id=request.args.get("ok", type=int))
@app.route("/start_tablets/<int:tablet_id>/speichern", methods=["POST"])
@@ -2025,36 +2077,63 @@ def tablets_speichern(tablet_id):
with db.get_cursor() as cur:
cur.execute('SELECT * FROM "Tablets" WHERE id = %s', (ersetzt_id,))
alt = cur.fetchone()
cur.execute('SELECT id FROM "Tablets" WHERE id = %s', (tablet_id,))
if not alt or not cur.fetchone():
cur.execute('SELECT * FROM "Tablets" WHERE id = %s', (tablet_id,))
neu = cur.fetchone()
if not alt or not neu:
abort(404)
cur.execute(
'UPDATE "Tablets" SET name = %s, ziel_typ = %s, maschine_id = %s WHERE id = %s',
'UPDATE "Tablets" SET name = %s, ziel_typ = %s, maschine_id = %s WHERE id = %s RETURNING *',
(alt["name"], alt["ziel_typ"], alt["maschine_id"], tablet_id),
)
neu = cur.fetchone()
ziel = _ziel_text(cur, alt["ziel_typ"], alt["maschine_id"])
tablet_log(
cur, "Eintrag ersetzt",
f"Übernimmt Name \"{alt['name']}\" und Zuordnung ({ziel}) von Tablet {_tablet_kurzkennung(alt['kennung'])}",
neu,
)
tablet_log(cur, "Entfernt", f"Ersetzt durch Tablet {_tablet_kurzkennung(neu['kennung'])} (\"{neu['name']}\")", alt)
cur.execute('DELETE FROM "Tablets" WHERE id = %s', (ersetzt_id,))
return redirect(url_for("tablets_verwaltung", ok=1))
return _zur_tablet_zeile(tablet_id)
if ziel_typ and ziel_typ not in TABLET_ZIELE:
return _tablets_seite(error="Ungültiges Ziel."), 400
return _tablets_seite(error="Ungültiges Ziel.", fehler_id=tablet_id), 400
with db.get_cursor() as cur:
cur.execute('SELECT id, kennung FROM "Tablets" WHERE id = %s', (tablet_id,))
tablet = cur.fetchone()
if not tablet:
cur.execute('SELECT * FROM "Tablets" WHERE id = %s', (tablet_id,))
alt = cur.fetchone()
if not alt:
abort(404)
if not name:
name = f"Tablet {_tablet_kurzkennung(tablet['kennung'])}"
name = f"Tablet {_tablet_kurzkennung(alt['kennung'])}"
if ziel_typ in ("maschine", "show"):
cur.execute('SELECT 1 FROM "Maschinen" WHERE id = %s', (maschine_id,))
if maschine_id is None or not cur.fetchone():
return _tablets_seite(error=f"{name}: Für \"{TABLET_ZIELE[ziel_typ]}\" muss eine Maschine gewählt werden."), 400
return _tablets_seite(
error=f"{name}: Für \"{TABLET_ZIELE[ziel_typ]}\" muss eine Maschine gewählt werden.",
fehler_id=tablet_id,
), 400
else:
maschine_id = None
neues_ziel = ziel_typ or None
alt_ziel_text = _ziel_text(cur, alt["ziel_typ"], alt["maschine_id"])
neu_ziel_text = _ziel_text(cur, neues_ziel, maschine_id)
cur.execute(
'UPDATE "Tablets" SET name = %s, ziel_typ = %s, maschine_id = %s WHERE id = %s',
(name, ziel_typ or None, maschine_id, tablet_id),
'UPDATE "Tablets" SET name = %s, ziel_typ = %s, maschine_id = %s WHERE id = %s RETURNING *',
(name, neues_ziel, maschine_id, tablet_id),
)
return redirect(url_for("tablets_verwaltung", ok=1))
neu = cur.fetchone()
aenderungen = []
if alt_ziel_text != neu_ziel_text:
aenderungen.append(f"Zuordnung: {alt_ziel_text} → {neu_ziel_text}")
if (alt["name"] or "") != name:
aenderungen.append(f"Name: \"{alt['name'] or ''}\" → \"{name}\"")
if aenderungen:
if alt_ziel_text != neu_ziel_text:
aktion = "Zugeordnet" if alt["ziel_typ"] not in TABLET_ZIELE else "Zuordnung geändert"
else:
aktion = "Umbenannt"
tablet_log(cur, aktion, "; ".join(aenderungen), neu)
return _zur_tablet_zeile(tablet_id)
@app.route("/start_tablets/lernmodus", methods=["POST"])
@@ -2062,20 +2141,54 @@ def tablets_speichern(tablet_id):
def tablets_lernmodus():
an = "1" if request.form.get("an") == "1" else "0"
with db.get_cursor() as cur:
vorher = tablet_lernmodus_aktiv(cur)
cur.execute(
'INSERT INTO "Einstellungen" (schluessel, wert) VALUES (%s, %s) '
'ON CONFLICT (schluessel) DO UPDATE SET wert = EXCLUDED.wert',
("tablet_lernmodus", an),
)
return redirect(url_for("tablets_verwaltung"))
if vorher != (an == "1"):
tablet_log(cur, "Lernmodus eingeschaltet" if an == "1" else "Lernmodus ausgeschaltet", "", None)
return redirect(url_for("tablets_verwaltung") + "#lernmodus")
@app.route("/start_tablets/<int:tablet_id>/loeschen", methods=["POST"])
@require_maschinen_auth
def tablets_loeschen(tablet_id):
with db.get_cursor() as cur:
cur.execute('DELETE FROM "Tablets" WHERE id = %s', (tablet_id,))
return redirect(url_for("tablets_verwaltung"))
cur.execute('SELECT * FROM "Tablets" WHERE id = %s', (tablet_id,))
alt = cur.fetchone()
if alt:
tablet_log(cur, "Entfernt", f"Zuordnung war: {_ziel_text(cur, alt['ziel_typ'], alt['maschine_id'])}", alt)
cur.execute('DELETE FROM "Tablets" WHERE id = %s', (tablet_id,))
return redirect(url_for("tablets_verwaltung") + "#tablet-liste")
@app.route("/start_tablets/verlauf")
@require_maschinen_auth
def tablets_verlauf():
"""Änderungsverlauf (neueste zuerst), optional für ein Tablet (?tablet=<id>)."""
tablet_id = request.args.get("tablet", type=int)
with db.get_cursor() as cur:
if tablet_id:
cur.execute(
'SELECT * FROM "Tablet_Verlauf" WHERE tablet_id = %s ORDER BY id DESC LIMIT 500', (tablet_id,)
)
else:
cur.execute('SELECT * FROM "Tablet_Verlauf" ORDER BY id DESC LIMIT 500')
eintraege = cur.fetchall()
for e in eintraege:
e["zeit_utc"] = datetime.fromtimestamp(int(e["zeitpunkt"]), timezone.utc).strftime("%d.%m.%Y %H:%M:%S UTC")
e["kurz"] = _tablet_kurzkennung(e["kennung"]) if e["kennung"] else ""
filter_name = None
if tablet_id:
cur.execute('SELECT name FROM "Tablets" WHERE id = %s', (tablet_id,))
t = cur.fetchone()
filter_name = t["name"] if t else (eintraege[0]["tablet_name"] if eintraege else f"#{tablet_id}")
return render_template(
"tablets_verlauf.html", title="Änderungsverlauf", subtitle="Tablet-Zuordnungen",
eintraege=eintraege, filter_name=filter_name, tablet_id=tablet_id,
)
# ---------------------------------------------------------------------