projekt:python_fastapi1
Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
| Beide Seiten der vorigen RevisionVorhergehende Überarbeitung | |||
| projekt:python_fastapi1 [2026/02/21 11:59] – torsten.roehl | projekt:python_fastapi1 [2026/02/21 13:22] (aktuell) – gelöscht torsten.roehl | ||
|---|---|---|---|
| Zeile 1: | Zeile 1: | ||
| - | ====== Python FASTAPI ====== | ||
| - | [[raspberry_pi: | ||
| - | |||
| - | |||
| - | //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.// | ||
| - | |||
| - | ====== Überblick ====== | ||
| - | * Voraussetzungen | ||
| - | * Software | ||
| - | * Konfiguration | ||
| - | |||
| - | ====== Details ====== | ||
| - | |||
| - | ===== Voraussetzungen ===== | ||
| - | |||
| - | ==== ENV ==== | ||
| - | |||
| - | <note important> | ||
| - | **Aktivierung der Python-Environment: | ||
| - | |||
| - | Alle weiteren Schritte erfolgen mit der aktivierten Python-Umgebung. | ||
| - | |||
| - | < | ||
| - | source ~/ | ||
| - | </ | ||
| - | </ | ||
| - | |||
| - | Anschließend werden FastAPI und Uvicorn installiert: | ||
| - | |||
| - | <code bash> | ||
| - | pip install fastapi uvicorn | ||
| - | </ | ||
| - | |||
| - | < | ||
| - | **FastAPI / Uvicorn** | ||
| - | |||
| - | * **FastAPI** | ||
| - | * stellt das Web-Framework bereit, mit dem die Webseiten und Routen programmiert werden. | ||
| - | * **Uvicorn** | ||
| - | * startet die Anwendung und sorgt dafür, dass sie im Browser erreichbar ist. | ||
| - | </ | ||
| - | |||
| - | ==== Projektstruktur ==== | ||
| - | |||
| - | '' | ||
| - | |||
| - | < | ||
| - | course_web/ | ||
| - | |── data/ | ||
| - | | | ||
| - | └── src/ | ||
| - | ├── app.py | ||
| - | ├── core/ | ||
| - | │ | ||
| - | │ | ||
| - | └── html/ | ||
| - | ├── led.html | ||
| - | ├── history.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: | ||
| - | '' | ||
| - | </ | ||
| - | |||
| - | ===== 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, | ||
| - | |||
| - | < | ||
| - | **Temperaturverlauf (History)** | ||
| - | |||
| - | Für den Temperaturverlauf wird die Hardware-API erweitert: | ||
| - | |||
| - | * Messwerte in '' | ||
| - | * Messwerte aus '' | ||
| - | * Messwerte löschen (reset) | ||
| - | </ | ||
| - | |||
| - | ==== API ==== | ||
| - | |||
| - | Datei: ''/ | ||
| - | |||
| - | <code python> | ||
| - | import RPi.GPIO as GPIO | ||
| - | import glob | ||
| - | import time | ||
| - | import os | ||
| - | from datetime import datetime | ||
| - | |||
| - | # ----------------------------- | ||
| - | # API-Funktionen GPIO LED Ampel | ||
| - | # ----------------------------- | ||
| - | |||
| - | PIN_R = 17 | ||
| - | PIN_Y = 27 | ||
| - | PIN_G = 22 | ||
| - | |||
| - | _initialized = False | ||
| - | |||
| - | def init(): | ||
| - | global _initialized | ||
| - | if _initialized: | ||
| - | return | ||
| - | |||
| - | GPIO.setwarnings(False) | ||
| - | GPIO.setmode(GPIO.BCM) | ||
| - | |||
| - | GPIO.setup(PIN_R, | ||
| - | GPIO.setup(PIN_Y, | ||
| - | GPIO.setup(PIN_G, | ||
| - | |||
| - | _initialized = True | ||
| - | |||
| - | |||
| - | def setLED(pin, value): | ||
| - | GPIO.output(pin, | ||
| - | |||
| - | |||
| - | def setRedLED(value): | ||
| - | setLED(PIN_R, | ||
| - | |||
| - | |||
| - | def setYellowLED(value): | ||
| - | setLED(PIN_Y, | ||
| - | |||
| - | |||
| - | def setGreenLED(value): | ||
| - | setLED(PIN_G, | ||
| - | |||
| - | |||
| - | def status(): | ||
| - | return ( | ||
| - | int(GPIO.input(PIN_R)), | ||
| - | int(GPIO.input(PIN_Y)), | ||
| - | int(GPIO.input(PIN_G)), | ||
| - | ) | ||
| - | |||
| - | |||
| - | # ----------------------------- | ||
| - | # API-Funktionen ds18b20 | ||
| - | # ----------------------------- | ||
| - | |||
| - | SENSOR_TIMEOUT = 1 | ||
| - | |||
| - | def get_sensor(): | ||
| - | sensors = glob.glob("/ | ||
| - | if not sensors: | ||
| - | return None | ||
| - | return sensors[0] + "/ | ||
| - | |||
| - | |||
| - | def get_temperature(): | ||
| - | sensor_file = get_sensor() | ||
| - | if sensor_file is None: | ||
| - | return None | ||
| - | |||
| - | start_time = time.time() | ||
| - | |||
| - | while True: | ||
| - | with open(sensor_file, | ||
| - | lines = f.readlines() | ||
| - | |||
| - | if lines[0].strip().endswith(" | ||
| - | break | ||
| - | |||
| - | if time.time() - start_time > SENSOR_TIMEOUT: | ||
| - | return None | ||
| - | |||
| - | time.sleep(0.1) | ||
| - | |||
| - | temp_line = lines[1] | ||
| - | temp_str = temp_line.split(" | ||
| - | return float(temp_str) / 1000.0 | ||
| - | |||
| - | |||
| - | # ----------------------------- | ||
| - | # Temperaturverlauf (History) | ||
| - | # ----------------------------- | ||
| - | # Datei-Format: | ||
| - | # Beispiel: | ||
| - | |||
| - | DEFAULT_LOG_FILE = "/ | ||
| - | |||
| - | def _ensure_parent_dir(path: | ||
| - | parent = os.path.dirname(path) | ||
| - | if parent and not os.path.exists(parent): | ||
| - | os.makedirs(parent, | ||
| - | |||
| - | def history_append(value: | ||
| - | """ | ||
| - | Speichert einen Messwert mit Zeitstempel in temperature.txt. | ||
| - | Rückgabe: True wenn erfolgreich, | ||
| - | """ | ||
| - | try: | ||
| - | _ensure_parent_dir(log_file) | ||
| - | ts = datetime.now().strftime(" | ||
| - | with open(log_file, | ||
| - | f.write(f" | ||
| - | return True | ||
| - | except Exception: | ||
| - | return False | ||
| - | |||
| - | def history_reset(log_file: | ||
| - | """ | ||
| - | Löscht die Messdatei (setzt den Verlauf zurück). | ||
| - | Rückgabe: True wenn erfolgreich, | ||
| - | """ | ||
| - | try: | ||
| - | _ensure_parent_dir(log_file) | ||
| - | with open(log_file, | ||
| - | f.write("" | ||
| - | return True | ||
| - | except Exception: | ||
| - | return False | ||
| - | |||
| - | def history_load(log_file: | ||
| - | """ | ||
| - | Lädt Messwerte aus temperature.txt. | ||
| - | Rückgabe: (labels, values) | ||
| - | labels: Liste von Zeitstempeln (String) | ||
| - | values: Liste von Temperaturen (float) | ||
| - | Hinweis: max_lines begrenzt die Menge (für Browser/ | ||
| - | """ | ||
| - | labels = [] | ||
| - | values = [] | ||
| - | |||
| - | try: | ||
| - | with open(log_file, | ||
| - | lines = f.readlines() | ||
| - | except FileNotFoundError: | ||
| - | return labels, values | ||
| - | except Exception: | ||
| - | return labels, values | ||
| - | |||
| - | # nur die letzten max_lines verwenden | ||
| - | if max_lines and len(lines) > max_lines: | ||
| - | lines = lines[-max_lines: | ||
| - | |||
| - | for line in lines: | ||
| - | line = line.strip() | ||
| - | if not line: | ||
| - | continue | ||
| - | try: | ||
| - | ts, val = line.split(";" | ||
| - | labels.append(ts) | ||
| - | values.append(float(val)) | ||
| - | except Exception: | ||
| - | continue | ||
| - | |||
| - | return labels, values | ||
| - | </ | ||
| - | |||
| - | ==== HTML ==== | ||
| - | |||
| - | === History === | ||
| - | |||
| - | Datei: ''/ | ||
| - | |||
| - | <code html> | ||
| - | < | ||
| - | < | ||
| - | < | ||
| - | < | ||
| - | <meta charset=" | ||
| - | </ | ||
| - | < | ||
| - | |||
| - | < | ||
| - | |||
| - | < | ||
| - | <a href="/ | ||
| - | <a href="/ | ||
| - | <a href="/ | ||
| - | |||
| - | < | ||
| - | <a href="/ | ||
| - | <a href="/ | ||
| - | <a href="/ | ||
| - | |||
| - | < | ||
| - | <img src="/ | ||
| - | |||
| - | < | ||
| - | <a href="/"> | ||
| - | |||
| - | </ | ||
| - | </ | ||
| - | </ | ||
| - | |||
| - | ==== FASTAPI APP ==== | ||
| - | |||
| - | Datei: ''/ | ||
| - | |||
| - | <code python> | ||
| - | from fastapi import FastAPI, HTTPException | ||
| - | from fastapi.responses import HTMLResponse, | ||
| - | from core import hardware | ||
| - | |||
| - | import threading | ||
| - | import time | ||
| - | |||
| - | app = FastAPI() | ||
| - | |||
| - | 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: | ||
| - | hardware.history_append(t) | ||
| - | 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 | ||
| - | |||
| - | |||
| - | @app.on_event(" | ||
| - | def startup(): | ||
| - | hardware.init() | ||
| - | _ensure_collector() | ||
| - | |||
| - | |||
| - | def load_template(name, | ||
| - | try: | ||
| - | with open(f" | ||
| - | html = f.read() | ||
| - | except FileNotFoundError: | ||
| - | raise HTTPException(status_code=500, | ||
| - | |||
| - | for key, value in replacements.items(): | ||
| - | html = html.replace(key, | ||
| - | |||
| - | return html | ||
| - | |||
| - | |||
| - | @app.get("/ | ||
| - | def led_page(): | ||
| - | r, y, g = hardware.status() | ||
| - | return HTMLResponse( | ||
| - | load_template(" | ||
| - | " | ||
| - | " | ||
| - | " | ||
| - | }) | ||
| - | ) | ||
| - | |||
| - | |||
| - | @app.get("/ | ||
| - | def set_led(color: | ||
| - | if value not in (0, 1): | ||
| - | raise HTTPException(status_code=400) | ||
| - | |||
| - | if color == " | ||
| - | hardware.setRedLED(value) | ||
| - | elif color == " | ||
| - | hardware.setYellowLED(value) | ||
| - | elif color == " | ||
| - | hardware.setGreenLED(value) | ||
| - | else: | ||
| - | raise HTTPException(status_code=400) | ||
| - | |||
| - | return RedirectResponse(url="/ | ||
| - | |||
| - | |||
| - | @app.get("/ | ||
| - | def temp_page(): | ||
| - | t = hardware.get_temperature() | ||
| - | |||
| - | if t is None: | ||
| - | value = " | ||
| - | else: | ||
| - | value = f" | ||
| - | |||
| - | return HTMLResponse(load_template(" | ||
| - | |||
| - | |||
| - | # ----------------------------- | ||
| - | # History (Temperaturverlauf) | ||
| - | # ----------------------------- | ||
| - | |||
| - | @app.get("/ | ||
| - | def history_page(): | ||
| - | return HTMLResponse(load_template(" | ||
| - | |||
| - | |||
| - | @app.get("/ | ||
| - | def history_start(): | ||
| - | global recording | ||
| - | recording = True | ||
| - | return RedirectResponse(url="/ | ||
| - | |||
| - | |||
| - | @app.get("/ | ||
| - | def history_stop(): | ||
| - | global recording | ||
| - | recording = False | ||
| - | return RedirectResponse(url="/ | ||
| - | |||
| - | |||
| - | @app.get("/ | ||
| - | def history_reset(): | ||
| - | hardware.history_reset() | ||
| - | 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="/ | ||
| - | |||
| - | |||
| - | def _svg_plot(labels, | ||
| - | # sehr einfache SVG-Linie (ohne JS, ohne externe Libs) | ||
| - | if not values: | ||
| - | return f'< | ||
| - | |||
| - | vmin = min(values) | ||
| - | vmax = max(values) | ||
| - | if vmax == vmin: | ||
| - | vmax = vmin + 1e-6 | ||
| - | |||
| - | n = len(values) | ||
| - | x0 = pad | ||
| - | y0 = pad | ||
| - | w = width - 2*pad | ||
| - | h = height - 2*pad | ||
| - | |||
| - | def x(i): | ||
| - | return x0 + (i * w / (n - 1 if n > 1 else 1)) | ||
| - | |||
| - | def y(v): | ||
| - | return y0 + (h - (v - vmin) * h / (vmax - vmin)) | ||
| - | |||
| - | pts = " " | ||
| - | |||
| - | # Achsen + Linie + Min/Max Text | ||
| - | svg = [] | ||
| - | svg.append(f'< | ||
| - | svg.append(f'< | ||
| - | svg.append(f'< | ||
| - | svg.append(f'< | ||
| - | svg.append(f'< | ||
| - | svg.append(f'< | ||
| - | svg.append(f'< | ||
| - | svg.append('</ | ||
| - | return "" | ||
| - | |||
| - | |||
| - | @app.get("/ | ||
| - | def history_plot(): | ||
| - | labels, values = hardware.history_load(max_lines=500) | ||
| - | svg = _svg_plot(labels, | ||
| - | return Response(content=svg, | ||
| - | </ | ||
| - | |||
| - | ===== Konfiguration ===== | ||
| - | |||
| - | ==== Apache Proxy ==== | ||
| - | |||
| - | In der Datei ''/ | ||
| - | |||
| - | <code bash> | ||
| - | ProxyPreserveHost On | ||
| - | |||
| - | ProxyPass | ||
| - | ProxyPassReverse /led http:// | ||
| - | |||
| - | ProxyPass | ||
| - | ProxyPassReverse /temp | ||
| - | |||
| - | ProxyPass | ||
| - | ProxyPassReverse / | ||
| - | |||
| - | ProxyPass | ||
| - | ProxyPassReverse / | ||
| - | </ | ||
| - | |||
| - | === Aktivieren === | ||
| - | |||
| - | <code bash> | ||
| - | sudo a2enmod proxy | ||
| - | sudo a2enmod proxy_http | ||
| - | sudo systemctl restart apache2 | ||
| - | </ | ||
| - | |||
| - | ==== Systemd ==== | ||
| - | |||
| - | <code bash / | ||
| - | [Unit] | ||
| - | Description=Python Web FastAPI | ||
| - | After=network-online.target | ||
| - | Wants=network-online.target | ||
| - | |||
| - | [Service] | ||
| - | User=pi | ||
| - | WorkingDirectory=/ | ||
| - | ExecStart=/ | ||
| - | Restart=always | ||
| - | |||
| - | [Install] | ||
| - | WantedBy=multi-user.target | ||
| - | </ | ||
| - | |||
| - | === Registrierung === | ||
| - | |||
| - | <code bash> | ||
| - | sudo systemctl daemon-reload | ||
| - | sudo systemctl enable course_web | ||
| - | sudo systemctl start course_web | ||
| - | sudo systemctl status course_web | ||
| - | </ | ||
| - | |||
| - | ==== Test Temperaturverlauf ==== | ||
| - | |||
| - | <code bash> | ||
| - | tail -n 20 / | ||
| - | </ | ||
projekt/python_fastapi1.1771675192.txt.gz · Zuletzt geändert: von torsten.roehl
