summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRobert Scheibe <rob.scheibe@gmail.com>2024-12-23 00:33:15 +0100
committerRobert Scheibe <rob.scheibe@gmail.com>2024-12-23 00:33:15 +0100
commit8bab6a72c76fd6ace5d784b1b09745c518cbe6bf (patch)
treec4f4b8df3ffbfbc060d7057bd593e6ede63d7f66
parentab7db5a0767e24adfc13ce82ddabb452b3bfa687 (diff)
added dht11 reading for room temperature and moisture
-rwxr-xr-xdeploy.sh4
-rwxr-xr-xmake_photo4
-rw-r--r--plot_new.py128
-rwxr-xr-xread_dht11.py64
4 files changed, 196 insertions, 4 deletions
diff --git a/deploy.sh b/deploy.sh
index 5032c15..3fffd76 100755
--- a/deploy.sh
+++ b/deploy.sh
@@ -1,4 +1,4 @@
#!/bin/bash
set -e
-scp water_the_plant create_backup make_photo *.py index.html history.html *.png robert@waterpi:
-ssh robert@waterpi -C 'sudo cp index.html history.html *.png /var/www/html; sudo chown www-data:www-data /var/www/html/*.html /var/www/html/*.png; sudo cp create_backup make_photo plot.py read_temperature.py water_the_plant /usr/local/bin'
+scp plot_new.py read_dht11.py water_the_plant create_backup make_photo index.html history.html *.png robert@waterpi:
+ssh robert@waterpi -C 'sudo cp index.html history.html *.png /var/www/html; sudo chown www-data:www-data /var/www/html/*.html /var/www/html/*.png; sudo cp plot_new.py read_dht11.py create_backup make_photo plot.py read_temperature.py water_the_plant /usr/local/bin'
diff --git a/make_photo b/make_photo
index 3123525..76c9918 100755
--- a/make_photo
+++ b/make_photo
@@ -8,6 +8,6 @@ rpicam-still -o $image
#add date string
convert $image -resize 1024x768 -gravity SouthEast -font DejaVu-Sans -pointsize 50 -stroke black -undercolor black -fill "rgba(255,255,255,0.5)" -annotate +30+30 "$(date +\\'%Y-%m-%d %H:%M\')" $image
#read cpu temp
-read_temperature.py
+read_dht11.py
#plot cpu temp
-plot.py $image $image
+plot_new.py $image $image
diff --git a/plot_new.py b/plot_new.py
new file mode 100644
index 0000000..4a6ee16
--- /dev/null
+++ b/plot_new.py
@@ -0,0 +1,128 @@
+#!/usr/bin/python3
+import sys
+import sqlite3
+import matplotlib.pyplot as plt
+import numpy as np
+from datetime import datetime, timedelta
+import matplotlib.dates as mdates
+from PIL import Image
+
+# Funktion zum Lesen von Temperatur-, Luftfeuchtigkeits- und Zeitstempeldaten aus der SQLite-Datenbank
+def read_data_from_db(db_name):
+ try:
+ conn = sqlite3.connect(db_name)
+ cursor = conn.cursor()
+ cursor.execute("SELECT timestamp, temperature, humidity FROM sensor_data")
+ data = cursor.fetchall()
+ conn.close()
+ return data
+ except sqlite3.Error as e:
+ print(f"Fehler beim Lesen aus der Datenbank: {e}")
+ return []
+
+# Funktion zum Erstellen eines Diagramms für Temperatur und Luftfeuchtigkeit (800x200 Pixel)
+def create_temperature_humidity_plot(records, output_filename):
+ if not records:
+ print("Keine Daten gefunden.")
+ return
+
+ # Aktuelle Zeit und Filterzeitraum (letzte 24 Stunden)
+ now = datetime.now()
+ last_24_hours = now - timedelta(hours=24)
+
+ # Filtern der Datensätze nach den letzten 24 Stunden
+ filtered_records = [
+ (datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S"), temperature, humidity)
+ for timestamp, temperature, humidity in records
+ if datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") >= last_24_hours
+ ]
+ if not filtered_records:
+ print("Keine Daten in den letzten 24 Stunden gefunden.")
+ return
+
+ # Extrahieren von Zeitstempeln, Temperaturen und Luftfeuchtigkeit
+ times = [timestamp for timestamp, _, _ in filtered_records]
+ temperatures = [temperature for _, temperature, _ in filtered_records]
+ humidities = [humidity for _, _, humidity in filtered_records]
+
+ # Grenzen für die y-Achsen basierend auf den Daten
+ min_temp = np.floor(min(temperatures) / 5) * 5
+ max_temp = np.ceil(max(temperatures) / 5) * 5
+ min_humidity = np.floor(min(humidities) / 10) * 10
+ max_humidity = np.ceil(max(humidities) / 10) * 10
+
+ # Diagramm zeichnen (800x200 Pixel)
+ fig, ax1 = plt.subplots(figsize=(8, 2), dpi=100)
+
+ # Temperaturplot (linke Y-Achse)
+ ax1.set_xlabel('Uhrzeit', color='white')
+ ax1.set_ylabel('Temperatur (°C)', color='tab:red')
+ ax1.plot(times, temperatures, color='tab:red', label='Temperatur')
+ ax1.tick_params(axis='y', labelcolor='tab:red')
+ ax1.tick_params(axis='x', colors='white')
+ ax1.set_ylim(min_temp, max_temp)
+ ax1.spines['top'].set_color('white')
+ ax1.spines['bottom'].set_color('white')
+ ax1.spines['left'].set_color('white')
+ ax1.spines['right'].set_color('white')
+
+ # Luftfeuchtigkeitsplot (rechte Y-Achse)
+ ax2 = ax1.twinx()
+ ax2.set_ylabel('Luftfeuchtigkeit (%)', color='tab:blue')
+ ax2.plot(times, humidities, color='tab:blue', label='Luftfeuchtigkeit')
+ ax2.tick_params(axis='y', labelcolor='tab:blue')
+ ax2.set_ylim(min_humidity, max_humidity)
+ ax2.spines['top'].set_color('white')
+ ax2.spines['bottom'].set_color('white')
+ ax2.spines['left'].set_color('white')
+ ax2.spines['right'].set_color('white')
+
+ # X-Achse formatieren
+ ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
+ fig.tight_layout()
+
+ # Diagramm speichern (transparent)
+ plt.savefig(output_filename, transparent=True, bbox_inches='tight')
+ plt.close()
+
+# Funktion zum Überlagern des Diagramms auf das Basisbild
+def overlay_plot_on_image(base_image_path, plot_image_path, output_image_path):
+ try:
+ base_image = Image.open(base_image_path)
+ plot_image = Image.open(plot_image_path).resize((800, 200)) # Größe des Plots anpassen
+
+ # Überlagern des Diagramms auf das Basisbild (mit Transparenz)
+ base_image.paste(plot_image, (112, 0), plot_image) # Zentrieren: (1024 - 800) / 2 = 112
+
+ # Kombiniertes Bild speichern
+ base_image.save(output_image_path)
+ print(f"Kombiniertes Bild gespeichert als {output_image_path}")
+ except Exception as e:
+ print(f"Fehler beim Überlagern des Diagramms: {e}")
+
+# Hauptfunktion
+def main():
+ if len(sys.argv) != 3:
+ print("Bitte geben Sie den Pfad zum Basisbild und den Pfad zum Ausgabebild an.")
+ sys.exit(1)
+
+ base_image_path = sys.argv[1]
+ output_image_path = sys.argv[2]
+
+ db_name = "/var/www/html/sensor_data.db"
+
+ # Daten aus der Datenbank lesen
+ records = read_data_from_db(db_name)
+
+ # Temporäre Datei für das transparente Temperatur- und Feuchtigkeitsdiagramm
+ plot_filename = "temperature_humidity_plot.png"
+
+ # Diagramm erstellen und speichern
+ create_temperature_humidity_plot(records, plot_filename)
+
+ # Basisbild laden und Diagramm überlagern
+ overlay_plot_on_image(base_image_path, plot_filename, output_image_path)
+
+if __name__ == "__main__":
+ main()
+
diff --git a/read_dht11.py b/read_dht11.py
new file mode 100755
index 0000000..524fdba
--- /dev/null
+++ b/read_dht11.py
@@ -0,0 +1,64 @@
+#!/usr/bin/python3
+import sqlite3
+from datetime import datetime
+import adafruit_dht
+import board
+
+# GPIO-Pin für den DHT11-Sensor
+DHT_SENSOR = adafruit_dht.DHT11(board.D26)
+
+# Funktion zur Initialisierung der SQLite-Datenbank
+def init_db(db_name):
+ conn = sqlite3.connect(db_name)
+ cursor = conn.cursor()
+ # Erstellt eine Tabelle, falls sie noch nicht existiert
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS sensor_data (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ timestamp TEXT NOT NULL,
+ temperature REAL NOT NULL,
+ humidity REAL NOT NULL
+ )
+ """)
+ conn.commit()
+ return conn
+
+# Funktion zum Einfügen von Daten in die Datenbank
+def insert_data(conn, timestamp, temperature, humidity):
+ cursor = conn.cursor()
+ cursor.execute("""
+ INSERT INTO sensor_data (timestamp, temperature, humidity)
+ VALUES (?, ?, ?)
+ """, (timestamp, temperature, humidity))
+ conn.commit()
+
+# Funktion zum Lesen von Temperatur und Luftfeuchtigkeit vom DHT11-Sensor
+def read_dht11():
+ humidity = DHT_SENSOR.humidity
+ temperature = DHT_SENSOR.temperature
+ if humidity is not None and temperature is not None:
+ return round(temperature, 1), round(humidity, 1)
+ else:
+ print("Fehler beim Lesen des Sensors. Versuche erneut...")
+ return None, None
+
+# Hauptfunktion
+def main():
+ db_name = "/var/www/html/sensor_data.db"
+ conn = init_db(db_name)
+
+ # Ruft Temperatur und Luftfeuchtigkeit ab
+ temperature, humidity = read_dht11()
+
+ if temperature is not None and humidity is not None:
+ # Holt das aktuelle Datum und die Uhrzeit
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ # Speichert die Daten in der Datenbank
+ insert_data(conn, timestamp, temperature, humidity)
+ print(f"Gespeichert: {timestamp} - Temperatur: {temperature}°C - Luftfeuchtigkeit: {humidity}%")
+
+ conn.close()
+
+if __name__ == "__main__":
+ main()
+