projekt:python_fastapi
Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
| Beide Seiten der vorigen RevisionVorhergehende ÜberarbeitungNächste Überarbeitung | Vorhergehende Überarbeitung | ||
| projekt:python_fastapi [2026/02/21 11:30] – [Temperaturverlauf: Daten anlegen] torsten.roehl | projekt:python_fastapi [2026/02/23 07:26] (aktuell) – [Systemd] torsten.roehl | ||
|---|---|---|---|
| Zeile 5: | Zeile 5: | ||
| //In diesem Projekt wird auf dem Raspberry Pi eine Weboberfläche mit FastAPI erstellt, über die eine LED-Ampel geschaltet und die Temperatur eines DS18B20 angezeigt werden kann. Die Anwendung ist im lokalen Netzwerk erreichbar, sodass LEDs und Temperatursensor bequem über einen Webbrowser im LAN gesteuert und überwacht werden können.// | //In diesem Projekt wird auf dem Raspberry Pi eine Weboberfläche mit FastAPI erstellt, über die eine LED-Ampel geschaltet und die Temperatur eines DS18B20 angezeigt werden kann. Die Anwendung ist im lokalen Netzwerk erreichbar, sodass LEDs und Temperatursensor bequem über einen Webbrowser im LAN gesteuert und überwacht werden können.// | ||
| + | |||
| + | |{{ : | ||
| + | |Die LED-Ampel kann nun über den Webbrowser gesteuert und die Temperatur ausgelesen werden.| | ||
| ====== Überblick ====== | ====== Überblick ====== | ||
| * Voraussetzungen | * Voraussetzungen | ||
| Zeile 22: | Zeile 25: | ||
| < | < | ||
| - | source ~/ | + | source ~/ |
| </ | </ | ||
| Zeile 45: | Zeile 48: | ||
| < | < | ||
| course_web/ | course_web/ | ||
| - | |── data/ | ||
| - | | | ||
| └── src/ | └── src/ | ||
| ├── app.py | ├── app.py | ||
| Zeile 54: | Zeile 55: | ||
| └── html/ | └── html/ | ||
| ├── led.html | ├── led.html | ||
| - | ├── history.html | ||
| └── temp.html | └── temp.html | ||
| </ | </ | ||
| - | |||
| - | ==== Temperaturverlauf: | ||
| - | Die Messwerte werden in einer Textdatei ('' | ||
| - | |||
| - | |||
| - | < | ||
| - | **Format der Datei '' | ||
| - | |||
| - | Jede Zeile enthält Zeitstempel und Temperatur, getrennt durch ein Semikolon: | ||
| - | |||
| - | '' | ||
| - | |||
| - | Beispiel: | ||
| - | '' | ||
| - | </ | ||
| - | |||
| ==== Apache2 Startseite ==== | ==== Apache2 Startseite ==== | ||
| Im Verzeichnis des Apache2-Webservers (''/ | Im Verzeichnis des Apache2-Webservers (''/ | ||
| Zeile 100: | Zeile 84: | ||
| < | < | ||
| < | < | ||
| - | < | ||
| </ul> | </ul> | ||
| Zeile 106: | Zeile 89: | ||
| </ | </ | ||
| </ | </ | ||
| - | |||
| ==== Hardware ==== | ==== Hardware ==== | ||
| Die Hardware, also die LED-Ampel und der Temperatursensor, | Die Hardware, also die LED-Ampel und der Temperatursensor, | ||
| Zeile 112: | Zeile 94: | ||
| ===== Software ===== | ===== Software ===== | ||
| Im folgenden Abschnitt werden die für die Webanwendung benötigten Python- und HTML-Dateien vorgestellt. Dazu gehören die Hardware-Anbindung über GPIO und den Temperatursensor, | Im folgenden Abschnitt werden die für die Webanwendung benötigten Python- und HTML-Dateien vorgestellt. Dazu gehören die Hardware-Anbindung über GPIO und den Temperatursensor, | ||
| - | |||
| - | < | ||
| - | **Temperaturverlauf (History)** | ||
| - | |||
| - | Der Temperaturverlauf wird nicht nur beim Aufruf im Browser erzeugt, sondern durch einen Hintergrund-Thread im laufenden FastAPI-Programm. | ||
| - | Damit können Messwerte automatisch im Intervall gesammelt, gestoppt und zurückgesetzt werden. | ||
| - | </ | ||
| - | |||
| ==== API ==== | ==== API ==== | ||
| Zeile 212: | Zeile 186: | ||
| return float(temp_str) / 1000.0 | return float(temp_str) / 1000.0 | ||
| </ | </ | ||
| + | |||
| ==== HTML ==== | ==== HTML ==== | ||
| === LED === | === LED === | ||
| + | |||
| <code html / | <code html / | ||
| Zeile 248: | Zeile 224: | ||
| </ | </ | ||
| </ | </ | ||
| + | |||
| === Temperature === | === Temperature === | ||
| + | |||
| <code html / | <code html / | ||
| Zeile 270: | Zeile 248: | ||
| </ | </ | ||
| - | === History === | ||
| - | <code html / | + | ==== FASTAPI APP ==== |
| - | < | + | |
| - | < | + | |
| - | < | + | |
| - | < | + | |
| - | <meta charset=" | + | |
| - | <script src=" | + | |
| - | </ | + | |
| - | < | + | |
| - | < | ||
| - | <h2> | + | <code python |
| - | <a href="/history/start"> | + | |
| - | <a href="/history/stop"> | + | |
| - | <a href="/ | + | |
| - | < | ||
| - | <a href="/ | ||
| - | <a href="/ | ||
| - | <a href="/ | ||
| - | |||
| - | < | ||
| - | <canvas id=" | ||
| - | |||
| - | < | ||
| - | let chart = null; | ||
| - | |||
| - | async function loadData() { | ||
| - | const res = await fetch("/ | ||
| - | return await res.json(); | ||
| - | } | ||
| - | |||
| - | async function plot() { | ||
| - | const data = await loadData(); | ||
| - | |||
| - | const ctx = document.getElementById(" | ||
| - | if (chart) chart.destroy(); | ||
| - | |||
| - | chart = new Chart(ctx, { | ||
| - | type: " | ||
| - | data: { | ||
| - | labels: data.labels, | ||
| - | datasets: [{ | ||
| - | label: " | ||
| - | data: data.values | ||
| - | }] | ||
| - | }, | ||
| - | options: { | ||
| - | animation: false | ||
| - | } | ||
| - | }); | ||
| - | } | ||
| - | |||
| - | plot(); | ||
| - | setInterval(plot, | ||
| - | </ | ||
| - | |||
| - | < | ||
| - | <a href="/"> | ||
| - | |||
| - | </ | ||
| - | </ | ||
| - | </ | ||
| - | |||
| - | ==== FASTAPI APP ==== | ||
| - | |||
| - | <code python / | ||
| from fastapi import FastAPI, HTTPException | from fastapi import FastAPI, HTTPException | ||
| - | from fastapi.responses import HTMLResponse, | + | from fastapi.responses import HTMLResponse, |
| from core import hardware | from core import hardware | ||
| - | |||
| - | import threading | ||
| - | import time | ||
| - | from datetime import datetime | ||
| app = FastAPI() | app = FastAPI() | ||
| - | |||
| - | LOG_FILE = "/ | ||
| - | |||
| - | recording = False | ||
| - | interval_seconds = 60 | ||
| - | _collector_started = False | ||
| - | _lock = threading.Lock() | ||
| - | |||
| - | |||
| - | def _collector_loop(): | ||
| - | global recording | ||
| - | |||
| - | while True: | ||
| - | if recording: | ||
| - | t = hardware.get_temperature() | ||
| - | if t is not None: | ||
| - | ts = datetime.now().strftime(" | ||
| - | try: | ||
| - | with open(LOG_FILE, | ||
| - | f.write(f" | ||
| - | except Exception: | ||
| - | pass | ||
| - | |||
| - | time.sleep(interval_seconds) | ||
| - | |||
| - | |||
| - | def _ensure_collector(): | ||
| - | global _collector_started | ||
| - | |||
| - | with _lock: | ||
| - | if _collector_started: | ||
| - | return | ||
| - | |||
| - | th = threading.Thread(target=_collector_loop, | ||
| - | th.start() | ||
| - | _collector_started = True | ||
| Zeile 391: | Zeile 265: | ||
| def startup(): | def startup(): | ||
| hardware.init() | hardware.init() | ||
| - | _ensure_collector() | ||
| Zeile 405: | Zeile 278: | ||
| return html | return html | ||
| - | |||
| @app.get("/ | @app.get("/ | ||
| def led_page(): | def led_page(): | ||
| r, y, g = hardware.status() | r, y, g = hardware.status() | ||
| + | |||
| return HTMLResponse( | return HTMLResponse( | ||
| load_template(" | load_template(" | ||
| " | " | ||
| " | " | ||
| - | " | + | " |
| + | " | ||
| + | " | ||
| + | " | ||
| }) | }) | ||
| ) | ) | ||
| - | |||
| @app.get("/ | @app.get("/ | ||
| Zeile 451: | Zeile 326: | ||
| }) | }) | ||
| ) | ) | ||
| + | </ | ||
| - | # ----------------------------- | ||
| - | # History (Temperaturverlauf) | ||
| - | # ----------------------------- | ||
| - | @app.get("/ | ||
| - | def history_page(): | ||
| - | return HTMLResponse(load_template(" | ||
| + | ===== Konfiguration ===== | ||
| + | In diesem Abschnitt wird die Einbindung der **FastAPI-Anwendung** in den Apache-Webserver sowie die Einrichtung als '' | ||
| + | ==== Apache Proxy ==== | ||
| - | @app.get("/ | + | === Konfiguration === |
| - | def history_start(): | + | |
| - | global recording | + | |
| - | recording | + | |
| - | return RedirectResponse(url="/ | + | |
| + | In der Datei '' | ||
| + | innerhalb von ''< | ||
| - | @app.get("/ | ||
| - | def history_stop(): | ||
| - | global recording | ||
| - | recording = False | ||
| - | return RedirectResponse(url="/ | ||
| + | <note tip> **Tip** | ||
| - | @app.get(" | + | Bevor die Datei '' |
| - | def history_reset(): | + | sollte die vorhandene Konfiguration gesichert werden. |
| - | open(LOG_FILE, | + | |
| - | return RedirectResponse(url=" | + | |
| - | + | ||
| - | + | ||
| - | @app.get(" | + | |
| - | def history_interval(minutes: | + | |
| - | global interval_seconds | + | |
| - | + | ||
| - | if minutes < 1: | + | |
| - | raise HTTPException(status_code=400) | + | |
| - | + | ||
| - | interval_seconds = minutes * 60 | + | |
| - | return RedirectResponse(url="/ | + | |
| - | + | ||
| - | + | ||
| - | @app.get("/ | + | |
| - | def history_data(): | + | |
| - | labels = [] | + | |
| - | values = [] | + | |
| - | + | ||
| - | try: | + | |
| - | with open(LOG_FILE, " | + | |
| - | for line in f: | + | |
| - | line = line.strip() | + | |
| - | if not line: | + | |
| - | continue | + | |
| - | try: | + | |
| - | ts, val = line.split(";" | + | |
| - | labels.append(ts) | + | |
| - | values.append(float(val)) | + | |
| - | except Exception: | + | |
| - | continue | + | |
| - | except FileNotFoundError: | + | |
| - | pass | + | |
| - | + | ||
| - | return JSONResponse({" | + | |
| + | <code bash> | ||
| + | cd / | ||
| + | sudo cp 000-default.conf 000-default.conf.course_backup | ||
| </ | </ | ||
| - | ===== Konfiguration ===== | + | </ |
| - | In diesem Abschnitt wird die Einbindung der **FastAPI-Anwendung** in den Apache-Webserver sowie die Einrichtung als '' | + | |
| - | ==== Apache Proxy ==== | ||
| - | |||
| - | === Konfiguration === | ||
| - | |||
| - | In der Datei '' | ||
| <code bash / | <code bash / | ||
| ProxyPreserveHost On | ProxyPreserveHost On | ||
| - | ProxyPass | + | ProxyPass |
| - | ProxyPassReverse /led http:// | + | ProxyPassReverse /led |
| - | + | ||
| - | ProxyPass | + | |
| - | ProxyPassReverse /temp | + | |
| - | ProxyPass | + | ProxyPass |
| - | ProxyPassReverse /history | + | ProxyPassReverse /temp |
| </ | </ | ||
| - | <note tip> | + | === Aktivieren === |
| - | Falls ''/ | + | Damit die Weiterleitung an die FastAPI-Anwendung funktioniert, müssen die benötigten Apache-Module aktiviert und der Webserver neu gestartet werden. |
| - | < | ||
| - | ProxyPass | ||
| - | ProxyPassReverse / | ||
| - | </ | ||
| - | </ | ||
| - | |||
| - | === Aktivieren === | ||
| <code bash> | <code bash> | ||
| sudo a2enmod proxy | sudo a2enmod proxy | ||
| Zeile 558: | Zeile 376: | ||
| Die Service-Datei muss unter ''/ | Die Service-Datei muss unter ''/ | ||
| - | |||
| === Service === | === Service === | ||
| + | |||
| <code bash / | <code bash / | ||
| Zeile 578: | Zeile 396: | ||
| === Registrierung === | === Registrierung === | ||
| + | Damit die neu erstellte Service-Datei von '' | ||
| + | |||
| <code bash> | <code bash> | ||
| sudo systemctl daemon-reload | sudo systemctl daemon-reload | ||
| sudo systemctl enable course_web | sudo systemctl enable course_web | ||
| sudo systemctl start course_web | sudo systemctl start course_web | ||
| - | sudo systemctl status course_web | + | |
| </ | </ | ||
| - | ==== Test Temperaturverlauf ==== | + | Nützlich: |
| <code bash> | <code bash> | ||
| - | tail -n 20 / | + | sudo systemctl restart |
| + | sudo systemctl status course_web | ||
| </ | </ | ||
projekt/python_fastapi.1771673459.txt.gz · Zuletzt geändert: von torsten.roehl
