Software Python 3: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Geli (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „'''Das Python 3 Skript''' #!/usr/bin/env python # -*- coding: utf-8 -*- #-------------------------------- import os, io, sys, time import csv import picamera import Adafruit_DHT import Adafruit_BMP.BMP085 as BMP085 import decimal from decimal import * import mysql.connector as mariadb from PIL import Image from PIL import ImageFont from PIL import ImageDraw import paho.mqtt.client as mqtt import json #-------------------------------------…“) |
Geli (Diskussion | Beiträge) Keine Bearbeitungszusammenfassung |
||
| Zeile 410: | Zeile 410: | ||
Jahr = time.strftime("%Y") | Jahr = time.strftime("%Y") | ||
dirJahr = "/media/usbhdd/" + Jahr + "/" | dirJahr = "/media/usbhdd/" + Jahr + "/" | ||
try: os.stat(dirJahr) | try: os.stat(dirJahr) | ||
except: os.mkdir(dirJahr) | except: os.mkdir(dirJahr) | ||
# Ordner für Nachtbilder nicht mehr anlegen | # Ordner für Nachtbilder nicht mehr anlegen | ||
# dirJahrN = "/media/usbhdd/" + Jahr + "N/" | # dirJahrN = "/media/usbhdd/" + Jahr + "N/" | ||
# try: os.stat(dirJahrN) | # try: os.stat(dirJahrN) | ||
# except: os.mkdir(dirJahrN) | # except: os.mkdir(dirJahrN) | ||
# Foto machen -------------------------------- | # Foto machen -------------------------------- | ||
# Create the in-memory stream | # Create the in-memory stream | ||
stream = io.BytesIO() | stream = io.BytesIO() | ||
with picamera.PiCamera() as camera: | with picamera.PiCamera() as camera: | ||
camera.resolution = (1920, 1080) | |||
camera.start_preview() | |||
camera.meter_mode = 'matrix' | |||
# camera.sharpness = 10 | |||
# camera.saturation = 5 | |||
# Camera warm-up time | |||
time.sleep(2) | |||
camera.capture(stream, format='jpeg') | |||
# "Rewind" the stream to the beginning so we can read its content | |||
camera.stop_preview() | |||
stream.seek(0) | |||
bild = Image.open(stream) | |||
camera.close() | |||
# Bild beschriften------------------------------------------------------- | # Bild beschriften------------------------------------------------------- | ||
#------------------------------------------------------------------------ | #------------------------------------------------------------------------ | ||
draw = ImageDraw.Draw(bild, 'RGBA') | draw = ImageDraw.Draw(bild, 'RGBA') | ||
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",35) | font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",35) | ||
fontk = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",30) | fontk = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",30) | ||
fontg = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",40) | fontg = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",40) | ||
draw.rectangle((0,991,1919,1079),fill=(80,80,80,144)) | draw.rectangle((0,991,1919,1079),fill=(80,80,80,144)) | ||
draw.rectangle((0,0,80,990),fill=(80,80,80,144)) | draw.rectangle((0,0,80,990),fill=(80,80,80,144)) | ||
draw.rectangle((1840,0,1919,990),fill=(80,80,80,144)) | draw.rectangle((1840,0,1919,990),fill=(80,80,80,144)) | ||
# Zeit schreiben -------------------------------------------------------- | # Zeit schreiben -------------------------------------------------------- | ||
draw.text((800, 1035),ZeitPIC,(255,255,255),font=font) | draw.text((800, 1035),ZeitPIC,(255,255,255),font=font) | ||
# Temperatur schreiben -------------------------------------------------- | # Temperatur schreiben -------------------------------------------------- | ||
# ----------------------------------------------------------------------- | # ----------------------------------------------------------------------- | ||
draw.text((3,994),chr(176)+"C",(255,255,255),font=font) | draw.text((3,994),chr(176)+"C",(255,255,255),font=font) | ||
tempstr = "%.1f" % temp | tempstr = "%.1f" % temp | ||
draw.text((3,1035),tempstr,(255,255,255),font=font) | draw.text((3,1035),tempstr,(255,255,255),font=font) | ||
# Temperaturbalken schreiben -------------------- | # Temperaturbalken schreiben -------------------- | ||
# oben=0, unten=990, Null Grad=660, 1 Grad=16,5 | # oben=0, unten=990, Null Grad=660, 1 Grad=16,5 | ||
rot, gruen, blau = tempcolor(temp) | rot, gruen, blau = tempcolor(temp) | ||
farbe = "rgb("+str(rot)+","+str(gruen)+","+str(blau)+")" | farbe = "rgb("+str(rot)+","+str(gruen)+","+str(blau)+")" | ||
tempfloat = float(temp) | tempfloat = float(temp) | ||
y = int(660 + 0.5 - tempfloat * 16.5) | y = int(660 + 0.5 - tempfloat * 16.5) | ||
if y < 0: | if y < 0: | ||
y = 0 | |||
if y > 990: | if y > 990: | ||
y = 990 | |||
coor = (0,y,30,990) | coor = (0,y,30,990) | ||
draw.rectangle(coor, fill=farbe) | draw.rectangle(coor, fill=farbe) | ||
coor = (0,0,30,990) | coor = (0,0,30,990) | ||
draw.rectangle(coor, outline="rgb(255,255,255)") | draw.rectangle(coor, outline="rgb(255,255,255)") | ||
# Hoch- und Tiefmarkierung | # Hoch- und Tiefmarkierung | ||
y = int(660 + 0.5 - tempfloath * 16.5) | y = int(660 + 0.5 - tempfloath * 16.5) | ||
if y < 1: y = 1 | if y < 1: y = 1 | ||
if y > 989: y = 989 | if y > 989: y = 989 | ||
coor = (0,y-1,30,y+1) | coor = (0,y-1,30,y+1) | ||
draw.rectangle(coor, fill="rgb(255,255,255)") | draw.rectangle(coor, fill="rgb(255,255,255)") | ||
y = int(660 + 0.5 - tempfloatt * 16.5) | y = int(660 + 0.5 - tempfloatt * 16.5) | ||
if y < 1: y = 1 | if y < 1: y = 1 | ||
if y > 989: y = 989 | if y > 989: y = 989 | ||
coor = (0,y-1,30,y+1) | coor = (0,y-1,30,y+1) | ||
draw.rectangle(coor, fill="rgb(255,255,255)") | draw.rectangle(coor, fill="rgb(255,255,255)") | ||
# Null-Grad Markierung | # Null-Grad Markierung | ||
coor = (0,659,39,661) | coor = (0,659,39,661) | ||
draw.rectangle(coor, fill="rgb(255,255,255)") | draw.rectangle(coor, fill="rgb(255,255,255)") | ||
draw.text((40,639),"0"+chr(176),(255,255,255),font=fontg) | draw.text((40,639),"0"+chr(176),(255,255,255),font=fontg) | ||
# max/min schreiben ------------------------------- | # max/min schreiben ------------------------------- | ||
draw.text((110,1003),"max",(255,255,255),font=fontk) | draw.text((110,1003),"max",(255,255,255),font=fontk) | ||
draw.text((110,1039),"min",(255,255,255),font=fontk) | draw.text((110,1039),"min",(255,255,255),font=fontk) | ||
draw.text((195,1020),"D",(255,255,255),font=font) | draw.text((195,1020),"D",(255,255,255),font=font) | ||
draw.text((235,1003),tempstrTh,(255,255,255),font=fontk) | draw.text((235,1003),tempstrTh,(255,255,255),font=fontk) | ||
draw.text((235,1039),tempstrTt,(255,255,255),font=fontk) | draw.text((235,1039),tempstrTt,(255,255,255),font=fontk) | ||
draw.text((335,1020),"M",(255,255,255),font=font) | draw.text((335,1020),"M",(255,255,255),font=font) | ||
draw.text((375,1003),tempstrMh,(255,255,255),font=fontk) | draw.text((375,1003),tempstrMh,(255,255,255),font=fontk) | ||
draw.text((375,1039),tempstrMt,(255,255,255),font=fontk) | draw.text((375,1039),tempstrMt,(255,255,255),font=fontk) | ||
draw.text((475,1020),"Y",(255,255,255),font=font) | draw.text((475,1020),"Y",(255,255,255),font=font) | ||
draw.text((515,1003),tempstrJh,(255,255,255),font=fontk) | draw.text((515,1003),tempstrJh,(255,255,255),font=fontk) | ||
draw.text((515,1039),tempstrJt,(255,255,255),font=fontk) | draw.text((515,1039),tempstrJt,(255,255,255),font=fontk) | ||
# Luftfeuchtigkeit ------------------------------------------------------ | # Luftfeuchtigkeit ------------------------------------------------------ | ||
# ----------------------------------------------------------------------- | # ----------------------------------------------------------------------- | ||
humstr = str(int(float(hum) + 0.5)) | humstr = str(int(float(hum) + 0.5)) | ||
draw.text ((1850,994),"rF%",(255,255,255),font=font) | draw.text ((1850,994),"rF%",(255,255,255),font=font) | ||
draw.text ((1850,1035),humstr,(255,255,255), font=font) | draw.text ((1850,1035),humstr,(255,255,255), font=font) | ||
# Luftfeuchtigkeitbalken schreiben --------------- | # Luftfeuchtigkeitbalken schreiben --------------- | ||
# oben=0, unten=990, 1 Prozent=9,9 | # oben=0, unten=990, 1 Prozent=9,9 | ||
rot, gruen, blau = humcolor(hum) | rot, gruen, blau = humcolor(hum) | ||
farbe = "rgb("+str(rot)+","+str(gruen)+","+str(blau)+")" | farbe = "rgb("+str(rot)+","+str(gruen)+","+str(blau)+")" | ||
humfloat = float(hum) | humfloat = float(hum) | ||
y = int(990 + 0.5 - humfloat * 9.9) | y = int(990 + 0.5 - humfloat * 9.9) | ||
coor = (1889,y,1919,990) | coor = (1889,y,1919,990) | ||
draw.rectangle(coor, fill=farbe) | draw.rectangle(coor, fill=farbe) | ||
coor = (1889,0,1919,990) | coor = (1889,0,1919,990) | ||
draw.rectangle(coor, outline="rgb(255,255,255)") | draw.rectangle(coor, outline="rgb(255,255,255)") | ||
# Hoch- und Tiefmarkierung | # Hoch- und Tiefmarkierung | ||
y = int(990 + 0.5 - humfloath * 9.9) | y = int(990 + 0.5 - humfloath * 9.9) | ||
if y < 1: y = 1 | if y < 1: y = 1 | ||
if y > 989: y = 989 | if y > 989: y = 989 | ||
coor = (1889,y-1,1919,y+1) | coor = (1889,y-1,1919,y+1) | ||
draw.rectangle(coor, fill="rgb(255,255,255)") | draw.rectangle(coor, fill="rgb(255,255,255)") | ||
y = int(990 + 0.5 - humfloatt * 9.9) | y = int(990 + 0.5 - humfloatt * 9.9) | ||
if y < 1: y = 1 | if y < 1: y = 1 | ||
if y > 989: y = 989 | if y > 989: y = 989 | ||
coor = (1889,y-1,1919,y+1) | coor = (1889,y-1,1919,y+1) | ||
draw.rectangle(coor, fill="rgb(255,255,255)") | draw.rectangle(coor, fill="rgb(255,255,255)") | ||
# Luftdruck ------------------------------------------------------------- | # Luftdruck ------------------------------------------------------------- | ||
#------------------------------------------------------------------------ | #------------------------------------------------------------------------ | ||
draw.text((1700,994),"hPa",(255,255,255),font=font) | draw.text((1700,994),"hPa",(255,255,255),font=font) | ||
hpastr = "%.1f" % hpa | hpastr = "%.1f" % hpa | ||
draw.text((1700, 1035),hpastr,(255,255,255),font=font) | draw.text((1700, 1035),hpastr,(255,255,255),font=font) | ||
# Luftdruckbalken schreiben ---------------------- | # Luftdruckbalken schreiben ---------------------- | ||
# oben=0, unten=990, 1 hPa=16,5 | # oben=0, unten=990, 1 hPa=16,5 | ||
# Farbe festlegen | # Farbe festlegen | ||
farbe = "rgb(170,170,170)" | farbe = "rgb(170,170,170)" | ||
hpafloat = float(hpa) | hpafloat = float(hpa) | ||
hpafloat = hpafloat - 980.0 | hpafloat = hpafloat - 980.0 | ||
y = int(990 + 0.5 - hpafloat * 16.5) | y = int(990 + 0.5 - hpafloat * 16.5) | ||
if y < 0: y = 0 | if y < 0: y = 0 | ||
if y > 990: y = 990 | if y > 990: y = 990 | ||
coor = (1839,y,1869,990) | coor = (1839,y,1869,990) | ||
draw.rectangle(coor, fill=farbe) | draw.rectangle(coor, fill=farbe) | ||
coor = (1839,0,1869,990) | coor = (1839,0,1869,990) | ||
draw.rectangle(coor, outline="rgb(255,255,255)") | draw.rectangle(coor, outline="rgb(255,255,255)") | ||
# Hoch- und Tiefmarkierung | # Hoch- und Tiefmarkierung | ||
y = int(990 + 0.5 - (hpafloath - 980.0) * 16.5) | y = int(990 + 0.5 - (hpafloath - 980.0) * 16.5) | ||
if y < 1: y = 1 | if y < 1: y = 1 | ||
if y > 989: y = 989 | if y > 989: y = 989 | ||
coor = (1839,y-1,1869,y+1) | coor = (1839,y-1,1869,y+1) | ||
draw.rectangle(coor, fill="rgb(255,255,255)") | draw.rectangle(coor, fill="rgb(255,255,255)") | ||
y = int(990 + 0.5 - (hpafloatt - 980.0) * 16.5) | y = int(990 + 0.5 - (hpafloatt - 980.0) * 16.5) | ||
if y < 1: y = 1 | if y < 1: y = 1 | ||
if y > 989: y = 989 | if y > 989: y = 989 | ||
coor = (1839,y-1,1869,y+1) | coor = (1839,y-1,1869,y+1) | ||
draw.rectangle(coor, fill="rgb(255,255,255)") | draw.rectangle(coor, fill="rgb(255,255,255)") | ||
# Luftdruck steigend oder fallend markieren | # Luftdruck steigend oder fallend markieren | ||
if hpaSign == "=": | if hpaSign == "=": | ||
coor = (1772,1013,1816,1017) | |||
draw.rectangle(coor, fill="rgb(255,225,0)") | |||
elif hpaSign == "+": | elif hpaSign == "+": | ||
draw.polygon(((1772,1025),(1792,1025),(1782,1005)),fill="rgb(0,255,0)") | |||
elif hpaSign == "++": | elif hpaSign == "++": | ||
draw.polygon(((1772,1025),(1792,1025),(1782,1005)),fill="rgb(0,255,0)") | |||
draw.polygon(((1792,1025),(1812,1025),(1802,1005)),fill="rgb(0,255,0)") | |||
elif hpaSign == "+++": | elif hpaSign == "+++": | ||
draw.polygon(((1772,1025),(1792,1025),(1782,1005)),fill="rgb(0,255,0)") | |||
draw.polygon(((1792,1025),(1812,1025),(1802,1005)),fill="rgb(0,255,0)") | |||
draw.polygon(((1812,1025),(1832,1025),(1822,1005)),fill="rgb(0,255,0)") | |||
elif hpaSign == "-": | elif hpaSign == "-": | ||
draw.polygon(((1772,1005),(1792,1005),(1782,1025)),fill="rgb(255,0,0)") | |||
elif hpaSign == "--": | elif hpaSign == "--": | ||
draw.polygon(((1772,1005),(1792,1005),(1782,1025)),fill="rgb(255,0,0)") | |||
draw.polygon(((1792,1005),(1812,1005),(1802,1025)),fill="rgb(255,0,0)") | |||
elif hpaSign == "---": | elif hpaSign == "---": | ||
draw.polygon(((1772,1005),(1792,1005),(1782,1025)),fill="rgb(255,0,0)") | |||
draw.polygon(((1792,1005),(1812,1005),(1802,1025)),fill="rgb(255,0,0)") | |||
draw.polygon(((1812,1005),(1832,1005),(1822,1025)),fill="rgb(255,0,0)") | |||
# max/min schreiben ------------------------------- | # max/min schreiben ------------------------------- | ||
draw.text((1530,1020),"D",(255,255,255),font=font) | draw.text((1530,1020),"D",(255,255,255),font=font) | ||
draw.text((1570,1003),hpastrTh,(255,255,255),font=fontk) | draw.text((1570,1003),hpastrTh,(255,255,255),font=fontk) | ||
draw.text((1570,1039),hpastrTt,(255,255,255),font=fontk) | draw.text((1570,1039),hpastrTt,(255,255,255),font=fontk) | ||
# Eventtext schreiben ----------------------------- | # Eventtext schreiben ----------------------------- | ||
EventArray = []; | EventArray = []; | ||
EventText = "" | EventText = "" | ||
# Datei Event.csv in Array EventArray einlesen | # Datei Event.csv in Array EventArray einlesen | ||
csvReader = csv.reader(open('/home/pi/Event.csv', 'r'), delimiter=';'); | csvReader = csv.reader(open('/home/pi/Event.csv', 'r'), delimiter=';'); | ||
for row in csvReader: | for row in csvReader: | ||
EventArray.append(row); | |||
# JJMMTT in Array EventArray suchen - mit 1 beginnen wegen Überschrift | # JJMMTT in Array EventArray suchen - mit 1 beginnen wegen Überschrift | ||
for i in range(1, len(EventArray)): | for i in range(1, len(EventArray)): | ||
if EventArray[i][0] == JJMMTT: | |||
EventText = EventArray[i][1] | |||
break | |||
if EventText != "": | if EventText != "": | ||
draw.rectangle((81,0,1838,55),fill=(80,80,80,144)) | |||
draw.text((38,3),EventText,(255,255,255),font=fontg) | |||
# ----------------------------------------------------------------------- | # ----------------------------------------------------------------------- | ||
# Array mit Sonnenauf- und untergangszeiten (Minuten) | # Array mit Sonnenauf- und untergangszeiten (Minuten) | ||
SonneAU = []; | SonneAU = []; | ||
# Datei YY.csv in Array SonneAU einlesen | # Datei YY.csv in Array SonneAU einlesen | ||
csvReader = csv.reader(open('/home/pi/' + YY + '.csv', 'r'), delimiter=';'); | csvReader = csv.reader(open('/home/pi/' + YY + '.csv', 'r'), delimiter=';'); | ||
for row in csvReader: | for row in csvReader: | ||
SonneAU.append(row); | |||
# TTMM und Tagesminute TagMin in Array SonneAU suchen | # TTMM und Tagesminute TagMin in Array SonneAU suchen | ||
for i in range(0, len(SonneAU)): | for i in range(0, len(SonneAU)): | ||
if SonneAU[i][0] == TTMM: | |||
SonneAuf = int(SonneAU[i][3]) - OffsetAuf | |||
SonneUnter = int (SonneAU[i][4]) + OffsetUnter | |||
break | |||
# Bild speichern | # Bild speichern | ||
if (SonneAuf <= int(TagMin)) and (SonneUnter >= int(TagMin)): | if (SonneAuf <= int(TagMin)) and (SonneUnter >= int(TagMin)): | ||
# bild.save(dirJahr+'P'+Zeit+'.jpg', format='JPEG', subsampling=0, quality=100) | |||
bild.save(dirJahr+'P'+Zeit+'.jpg') | |||
# Nachtbild nicht mehr speichern | # Nachtbild nicht mehr speichern | ||
# else: | # else: | ||
# bild.save(dirJahrN+'P'+Zeit+'.jpg') | # bild.save(dirJahrN+'P'+Zeit+'.jpg') | ||
bild.save('/media/usbhdd/webpic/weather.jpg') | bild.save('/media/usbhdd/webpic/weather.jpg') | ||
#-------------------------------------------- | #-------------------------------------------- | ||
# MQTT | # MQTT | ||
#-------------------------------------------- | #-------------------------------------------- | ||
client = mqtt.Client() | client = mqtt.Client() | ||
client.on_connect = on_connect | client.on_connect = on_connect | ||
try: | try: | ||
client.connect("10.0.0.9", 1883, 60) | |||
mqtt_string = {"time":ZeitPIC,"humidity_out":str(hum),"temp_out":str(temp),"pressure":str(hpa)} | |||
data_out = json.dumps(mqtt_string) | |||
client.publish("raspicam/weather/data", data_out) | |||
except: | except: | ||
pass | |||
#-------------------------------------------- | #-------------------------------------------- | ||
# Bild resize 640 | # Bild resize 640 | ||
#-------------------------------------------- | #-------------------------------------------- | ||
bild640 = bild.resize((640, 360), Image.ANTIALIAS) | bild640 = bild.resize((640, 360), Image.ANTIALIAS) | ||
bild640.save('/media/usbhdd/webpic/weather640.jpg') | bild640.save('/media/usbhdd/webpic/weather640.jpg') | ||
# Programmende---------------------------------------------------------------- | # Programmende---------------------------------------------------------------- | ||
Version vom 9. Februar 2023, 19:31 Uhr
Das Python 3 Skript
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#--------------------------------
import os, io, sys, time
import csv
import picamera
import Adafruit_DHT
import Adafruit_BMP.BMP085 as BMP085
import decimal
from decimal import *
import mysql.connector as mariadb
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import paho.mqtt.client as mqtt
import json
#-----------------------------------------------------------
# Offsets festlegen
#-----------------------------------------------------------
# Sonnenaufgang und -untergang (YY.csv)
OffsetAuf = 25
OffsetUnter = 30
#-----------------------------------------------------------
# Logfile definieren
#-----------------------------------------------------------
logfile = '/home/pi/timelapse.log'
#-----------------------------------------------------------
# Funktion Logfile schreiben
# log("string"+"\n")
#-----------------------------------------------------------
def log(msg):
file = open(logfile,"a")
file.write(msg)
file.close
#-----------------------------------------------------------
# Funktion Temperatur in Farbe umrechnen
#-----------------------------------------------------------
def tempcolor(temp):
gruppe = int(temp/10) + 2
mod = temp - int(temp/10)*10
if gruppe < 0:
gruppe = 0
if gruppe > 6:
gruppe = 6
if gruppe == 6:
r = 255
g = 0
b = 0
return (r, g, b)
elif gruppe == 5:
r = 200 + int(Decimal(5.5) * mod)
g = 0
b = 0
return (r, g, b)
elif gruppe == 4:
r = 200
g = 200 - int(20 * mod)
b = 0
return (r, g, b)
elif gruppe == 3:
r = 0 + int(20 * mod)
g = 200
b = 0
return (r, g, b)
elif gruppe == 2:
if temp >= 0:
r = 0
g = 200
b = 200 - int(20 * mod)
return (r, g, b)
else:
r = 0
g = 200 + int(20 * mod)
b = 200
return (r, g, b)
elif gruppe == 1:
r = 0 - int(20 * mod)
g = 0
b = 200
return (r, g, b)
else:
r = 200
g = 0
b = 100
return (r, g, b)
#-----------------------------------------------------------
# Funktion Humidity in Farbe umrechnen
#-----------------------------------------------------------
def humcolor(hum):
r = 255 - int(hum*255/100)
g = 255 - int(hum*255/100)
b = 255
return (r, g, b)
#-----------------------------------------------------------
# Function DS18B20 lesen
#-----------------------------------------------------------
def Temp(sensorfile):
# 1-wire Slave Datei lesen
file = open('/sys/bus/w1/devices/' + sensorfile + '/w1_slave')
filecontent = file.read()
file.close()
# Temperaturwerte auslesen und konvertieren
stringvalue = filecontent.split("\n")[1].split(" ")[9]
temperature = float(stringvalue[2:]) / 1000
# Temperatur zurückgeben
return(temperature)
#--------------------------
# MQTT
#--------------------------
def on_connect(client, userdata, flags, rc):
returncode = rc
#-----------------------------------------------------------
# Sensoren auswerten
#-----------------------------------------------------------
# DS18B20 auswerten ------------
temp1 = Temp('28-0516851390ff')
#temp = Decimal(temp1 -0.05).quantize(Decimal('.1'), rounding=ROUND_HALF_UP)
temp = Decimal(temp1).quantize(Decimal('.1'), rounding=ROUND_HALF_UP)
# DHT-22 auswerten ------------------
sensor = Adafruit_DHT.DHT22
# GPIO-Nummer festlegen -------------
pin = 17
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
humkorr = humidity * 1.047
# humkorr = humidity * 1.07
# humkorr = humidity * 1.13
# humkorr = humidity * 1.15
# humkorr = humidity * 1.22
if humkorr > 100:
humkorr = 100
hum = Decimal(humkorr).quantize(Decimal('.1'), rounding=ROUND_HALF_UP)
humraw = Decimal(humidity).quantize(Decimal('.1'), rounding=ROUND_HALF_UP)
# Luftdruck bestimmen ---------------
bmp = BMP085.BMP085()
BMP_temp = bmp.read_temperature() - 0.5
tempint = Decimal(BMP_temp).quantize(Decimal('.1'), rounding=ROUND_HALF_UP)
BMP_hpa = bmp.read_pressure()
# Meereshoehe Standort in m = 315 + Kalibrierwert
Kalib = -9.0
altitude = 315.0 + Kalib
BMP_psea = BMP_hpa / pow(1.0 - altitude/44330.0, 5.255) / 100
hpa = Decimal(BMP_psea).quantize(Decimal('.1'), rounding=ROUND_HALF_UP)
#-----------------------------------------------------------
# Datenbank schreiben
#-----------------------------------------------------------
# Aktuelles Datum und Zeit bestimmen
# Zeit = time.strftime("%y%m%d-%H%M%S")
Zeit = time.strftime("%y%m%d-%H%M")
UTC = int(time.time()/60)*60
YY = Zeit[0:2]
MM = Zeit[2:4]
DD = Zeit[4:6]
Stunde = Zeit[7:9]
Minute = Zeit[9:11]
Datum = Datum = DD + "." + MM + "." + YY
TTMM = DD + MM
JJMMTT = YY + MM + DD
TagMin = int(Stunde) * 60 + int(Minute)
ZeitPIC = DD + "." + MM + "." + "20" + YY + " " + Stunde + ":" + Minute
timestamp = YY + MM + DD + Stunde + Minute
# Vor dem Schreiben Plausibilitätsprüfung von Zeit und Temperatur durchführen
# Datenbank definieren
db = mariadb.connect(
user="pi",
password="password",
host="localhost",
port=3306,
database="sensor"
)
cursor = db.cursor()
# Letzten Datensatz aus werte lesen
sql = "SELECT * FROM werte ORDER BY id DESC LIMIT 1"
cursor.execute(sql)
checktime = cursor.fetchone()
if checktime is not None:
check_utc = checktime[1]
check_temp = checktime[3]
if (UTC - float(check_utc)) > 301:
log("E8: " + timestamp + " " + str((UTC - float(check_utc))/60) + " Minuten Zeitdifferenz!" + "\n")
if temp > 42:
log("E9: " + timestamp + " Temperaturwert > 42: " + str(temp) + "\n")
temp = check_temp
# 5-Minutenwerte schreiben Tabelle werte --------------------
sql = "INSERT INTO werte (utc, timestamp, temp, hum, humraw, hpa, tempint) \
VALUES ('%s', '%s', '%f', '%f', '%f', '%f', '%f')" % \
(UTC, timestamp, temp, hum, humraw, hpa, tempint)
try:
cursor.execute(sql)
db.commit()
except:
log("E1: " + timestamp + " SQL write to werte not ok!" +"\n")
db.rollback()
# 3-Stundenwert hpa aus Tabelle werte lesen ----------------
UTC_3h = UTC - 10800
sql = "SELECT hpa FROM werte WHERE UTC = %s"
cursor.execute(sql, (UTC_3h,))
UTC_3hDB = cursor.fetchone()
# Ausmaß der Luftdruckänderung feststellen -----------------
hpaSign = ""
hpadiff = 0
if UTC_3hDB is not None:
hpadiff = hpa - UTC_3hDB[0]
if (hpadiff > -1) and (hpadiff < 1):
hpaSign = "="
elif (hpadiff >= 1) and (hpadiff < 3):
hpaSign = "+"
elif (hpadiff >= 3) and (hpadiff < 5):
hpaSign = "++"
elif (hpadiff >= 5):
hpaSign = "+++"
elif (hpadiff <= -1) and (hpadiff > -3):
hpaSign = "-"
elif (hpadiff <= -3) and (hpadiff > -5):
hpaSign = "--"
elif (hpadiff <= -5):
hpaSign = "---"
# Extremwerte behandeln Tabelle hochtief -------------------
# Tabelle hochtief Tageshochtief lesen ---------------------
timestamp_ht = YY + MM + DD
sql = "SELECT temph, tempt, humh, humt, hpah, hpat, id FROM hochtief WHERE timestamp = %s"
cursor.execute(sql, (timestamp_ht,))
ergebnis = cursor.fetchone()
if not ergebnis:
sql = "INSERT INTO hochtief (timestamp, temph, tempt, humh, humt, hpah, hpat) \
VALUES ('%s', '%f', '%f', '%f', '%f', '%f', '%f')" % \
(timestamp_ht, temp, temp, hum, hum, hpa, hpa)
try:
cursor.execute(sql)
db.commit()
except:
log("E2: " + timestamp_ht + " SQL write to hochtief not ok!" +"\n")
db.rollback()
tempstrTh = "%.1f" % temp
tempstrTt = "%.1f" % temp
tempfloath = float(temp)
tempfloatt = float(temp)
humfloath = float(hum)
humfloatt = float(hum)
hpafloath = float(hpa)
hpafloatt = float(hpa)
hpastrTh = "%.1f" % hpa
hpastrTt = "%.1f" % hpa
else:
speichern = False
temph = ergebnis[0]
tempt = ergebnis[1]
tempstrTh = "%.1f" % temph
tempstrTt = "%.1f" % tempt
tempfloath = float(temph)
tempfloatt = float(tempt)
humh = ergebnis[2]
humt = ergebnis[3]
humfloath = float(humh)
humfloatt = float(humt)
hpah = ergebnis[4]
hpat = ergebnis[5]
hpafloath = float(hpah)
hpafloatt = float(hpat)
hpastrTh = "%.1f" % hpah
hpastrTt = "%.1f" % hpat
id = ergebnis[6]
if temp > temph:
temph = temp; speichern = True
tempstrTh = "%.1f" % temph
tempfloath = float(temph)
if temp < tempt:
tempt = temp; speichern = True
tempstrTt = "%.1f" % tempt
tempfloatt = float(tempt)
if hum > humh:
humh = hum; speichern = True
humfloath = float(humh)
if hum < humt:
humt = hum; speichern = True
humfloatt = float(humt)
if hpa > hpah:
hpah = hpa; speichern = True
hpastrTh = "%.1f" % hpah
hpafloath = float(hpah)
if hpa < hpat:
hpat = hpa; speichern = True
hpastrTt = "%.1f" % hpat
hpafloatt = float(hpat)
if speichern:
try:
cursor.execute("""
UPDATE hochtief
SET temph=%s, tempt=%s, humh=%s, humt=%s, hpah=%s, hpat=%s
WHERE id=%s
""", (temph, tempt, humh, humt, hpah, hpat, id))
db.commit()
except:
log("E3: " + timestamp_ht + " SQL write to hochtief not ok!" +"\n")
db.rollback()
# Tabelle hochtief Monatshochtief lesen --------------------
timestamp_ht = YY + MM + "00"
sql = "SELECT temph, tempt, humh, humt, hpah, hpat, id FROM hochtief WHERE timestamp = %s"
cursor.execute(sql, (timestamp_ht,))
ergebnis = cursor.fetchone()
if not ergebnis:
sql = "INSERT INTO hochtief (timestamp, temph, tempt, humh, humt, hpah, hpat) \
VALUES ('%s', '%f', '%f', '%f', '%f', '%f', '%f')" % \
(timestamp_ht, temp, temp, hum, hum, hpa, hpa)
try:
cursor.execute(sql)
db.commit()
except:
log("E4: " + timestamp_ht + " SQL write to hochtief not ok!" +"\n")
db.rollback()
tempstrMh = "%.1f" % temp
tempstrMt = "%.1f" % temp
else:
speichern = False
temph = ergebnis[0]
tempt = ergebnis[1]
tempstrMh = "%.1f" % temph
tempstrMt = "%.1f" % tempt
humh = ergebnis[2]
humt = ergebnis[3]
hpah = ergebnis[4]
hpat = ergebnis[5]
id = ergebnis[6]
if temp > temph:
temph = temp; speichern = True
tempstrMh = "%.1f" % temph
if temp < tempt:
tempt = temp; speichern = True
tempstrMt = "%.1f" % tempt
if hum > humh:
humh = hum; speichern = True
if hum < humt:
humt = hum; speichern = True
if hpa > hpah:
hpah = hpa; speichern = True
if hpa < hpat:
hpat = hpa; speichern = True
if speichern:
try:
cursor.execute("""
UPDATE hochtief
SET temph=%s, tempt=%s, humh=%s, humt=%s, hpah=%s, hpat=%s
WHERE id=%s
""", (temph, tempt, humh, humt, hpah, hpat, id))
db.commit()
except:
log("E5: " + timestamp_ht + " SQL write to hochtief not ok!" +"\n")
db.rollback()
# Tabelle hochtief Jahreshochtief lesen --------------------
timestamp_ht = YY + "0000"
sql = "SELECT temph, tempt, humh, humt, hpah, hpat, id FROM hochtief WHERE timestamp = %s"
cursor.execute(sql, (timestamp_ht,))
ergebnis = cursor.fetchone()
if not ergebnis:
sql = "INSERT INTO hochtief (timestamp, temph, tempt, humh, humt, hpah, hpat) \
VALUES ('%s', '%f', '%f', '%f', '%f', '%f', '%f')" % \
(timestamp_ht, temp, temp, hum, hum, hpa, hpa)
try:
cursor.execute(sql)
db.commit()
except:
log("E6: " + timestamp_ht + " SQL write to hochtief not ok!" +"\n")
db.rollback()
tempstrJh = "%.1f" % temp
tempstrJt = "%.1f" % temp
else:
speichern = False
temph = ergebnis[0]
tempt = ergebnis[1]
tempstrJh = "%.1f" % temph
tempstrJt = "%.1f" % tempt
humh = ergebnis[2]
humt = ergebnis[3]
hpah = ergebnis[4]
hpat = ergebnis[5]
id = ergebnis[6]
if temp > temph:
temph = temp; speichern = True
tempstrJh = "%.1f" % temph
if temp < tempt:
tempt = temp; speichern = True
tempstrJt = "%.1f" % tempt
if hum > humh:
humh = hum; speichern = True
if hum < humt:
humt = hum; speichern = True
if hpa > hpah:
hpah = hpa; speichern = True
if hpa < hpat:
hpat = hpa; speichern = True
if speichern:
try:
cursor.execute("""
UPDATE hochtief
SET temph=%s, tempt=%s, humh=%s, humt=%s, hpah=%s, hpat=%s
WHERE id=%s
""", (temph, tempt, humh, humt, hpah, hpat, id))
db.commit()
except:
log("E7: " + timestamp_ht + " SQL write to hochtief not ok!" +"\n")
db.rollback()
# disconnect from server
db.close()
# -------------------------------------------------------------------------
# PiCam
#--------------------------------------------------------------------------
# Directories festlegen, checken (und anlegen)
Jahr = time.strftime("%Y")
dirJahr = "/media/usbhdd/" + Jahr + "/"
try: os.stat(dirJahr)
except: os.mkdir(dirJahr)
# Ordner für Nachtbilder nicht mehr anlegen
# dirJahrN = "/media/usbhdd/" + Jahr + "N/"
# try: os.stat(dirJahrN)
# except: os.mkdir(dirJahrN)
# Foto machen --------------------------------
# Create the in-memory stream
stream = io.BytesIO()
with picamera.PiCamera() as camera:
camera.resolution = (1920, 1080)
camera.start_preview()
camera.meter_mode = 'matrix'
# camera.sharpness = 10
# camera.saturation = 5
# Camera warm-up time
time.sleep(2)
camera.capture(stream, format='jpeg')
# "Rewind" the stream to the beginning so we can read its content
camera.stop_preview()
stream.seek(0)
bild = Image.open(stream)
camera.close()
# Bild beschriften-------------------------------------------------------
#------------------------------------------------------------------------
draw = ImageDraw.Draw(bild, 'RGBA')
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",35)
fontk = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",30)
fontg = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",40)
draw.rectangle((0,991,1919,1079),fill=(80,80,80,144))
draw.rectangle((0,0,80,990),fill=(80,80,80,144))
draw.rectangle((1840,0,1919,990),fill=(80,80,80,144))
# Zeit schreiben --------------------------------------------------------
draw.text((800, 1035),ZeitPIC,(255,255,255),font=font)
# Temperatur schreiben --------------------------------------------------
# -----------------------------------------------------------------------
draw.text((3,994),chr(176)+"C",(255,255,255),font=font)
tempstr = "%.1f" % temp
draw.text((3,1035),tempstr,(255,255,255),font=font)
# Temperaturbalken schreiben --------------------
# oben=0, unten=990, Null Grad=660, 1 Grad=16,5
rot, gruen, blau = tempcolor(temp)
farbe = "rgb("+str(rot)+","+str(gruen)+","+str(blau)+")"
tempfloat = float(temp)
y = int(660 + 0.5 - tempfloat * 16.5)
if y < 0:
y = 0
if y > 990:
y = 990
coor = (0,y,30,990)
draw.rectangle(coor, fill=farbe)
coor = (0,0,30,990)
draw.rectangle(coor, outline="rgb(255,255,255)")
# Hoch- und Tiefmarkierung
y = int(660 + 0.5 - tempfloath * 16.5)
if y < 1: y = 1
if y > 989: y = 989
coor = (0,y-1,30,y+1)
draw.rectangle(coor, fill="rgb(255,255,255)")
y = int(660 + 0.5 - tempfloatt * 16.5)
if y < 1: y = 1
if y > 989: y = 989
coor = (0,y-1,30,y+1)
draw.rectangle(coor, fill="rgb(255,255,255)")
# Null-Grad Markierung
coor = (0,659,39,661)
draw.rectangle(coor, fill="rgb(255,255,255)")
draw.text((40,639),"0"+chr(176),(255,255,255),font=fontg)
# max/min schreiben -------------------------------
draw.text((110,1003),"max",(255,255,255),font=fontk)
draw.text((110,1039),"min",(255,255,255),font=fontk)
draw.text((195,1020),"D",(255,255,255),font=font)
draw.text((235,1003),tempstrTh,(255,255,255),font=fontk)
draw.text((235,1039),tempstrTt,(255,255,255),font=fontk)
draw.text((335,1020),"M",(255,255,255),font=font)
draw.text((375,1003),tempstrMh,(255,255,255),font=fontk)
draw.text((375,1039),tempstrMt,(255,255,255),font=fontk)
draw.text((475,1020),"Y",(255,255,255),font=font)
draw.text((515,1003),tempstrJh,(255,255,255),font=fontk)
draw.text((515,1039),tempstrJt,(255,255,255),font=fontk)
# Luftfeuchtigkeit ------------------------------------------------------
# -----------------------------------------------------------------------
humstr = str(int(float(hum) + 0.5))
draw.text ((1850,994),"rF%",(255,255,255),font=font)
draw.text ((1850,1035),humstr,(255,255,255), font=font)
# Luftfeuchtigkeitbalken schreiben ---------------
# oben=0, unten=990, 1 Prozent=9,9
rot, gruen, blau = humcolor(hum)
farbe = "rgb("+str(rot)+","+str(gruen)+","+str(blau)+")"
humfloat = float(hum)
y = int(990 + 0.5 - humfloat * 9.9)
coor = (1889,y,1919,990)
draw.rectangle(coor, fill=farbe)
coor = (1889,0,1919,990)
draw.rectangle(coor, outline="rgb(255,255,255)")
# Hoch- und Tiefmarkierung
y = int(990 + 0.5 - humfloath * 9.9)
if y < 1: y = 1
if y > 989: y = 989
coor = (1889,y-1,1919,y+1)
draw.rectangle(coor, fill="rgb(255,255,255)")
y = int(990 + 0.5 - humfloatt * 9.9)
if y < 1: y = 1
if y > 989: y = 989
coor = (1889,y-1,1919,y+1)
draw.rectangle(coor, fill="rgb(255,255,255)")
# Luftdruck -------------------------------------------------------------
#------------------------------------------------------------------------
draw.text((1700,994),"hPa",(255,255,255),font=font)
hpastr = "%.1f" % hpa
draw.text((1700, 1035),hpastr,(255,255,255),font=font)
# Luftdruckbalken schreiben ----------------------
# oben=0, unten=990, 1 hPa=16,5
# Farbe festlegen
farbe = "rgb(170,170,170)"
hpafloat = float(hpa)
hpafloat = hpafloat - 980.0
y = int(990 + 0.5 - hpafloat * 16.5)
if y < 0: y = 0
if y > 990: y = 990
coor = (1839,y,1869,990)
draw.rectangle(coor, fill=farbe)
coor = (1839,0,1869,990)
draw.rectangle(coor, outline="rgb(255,255,255)")
# Hoch- und Tiefmarkierung
y = int(990 + 0.5 - (hpafloath - 980.0) * 16.5)
if y < 1: y = 1
if y > 989: y = 989
coor = (1839,y-1,1869,y+1)
draw.rectangle(coor, fill="rgb(255,255,255)")
y = int(990 + 0.5 - (hpafloatt - 980.0) * 16.5)
if y < 1: y = 1
if y > 989: y = 989
coor = (1839,y-1,1869,y+1)
draw.rectangle(coor, fill="rgb(255,255,255)")
# Luftdruck steigend oder fallend markieren
if hpaSign == "=":
coor = (1772,1013,1816,1017)
draw.rectangle(coor, fill="rgb(255,225,0)")
elif hpaSign == "+":
draw.polygon(((1772,1025),(1792,1025),(1782,1005)),fill="rgb(0,255,0)")
elif hpaSign == "++":
draw.polygon(((1772,1025),(1792,1025),(1782,1005)),fill="rgb(0,255,0)")
draw.polygon(((1792,1025),(1812,1025),(1802,1005)),fill="rgb(0,255,0)")
elif hpaSign == "+++":
draw.polygon(((1772,1025),(1792,1025),(1782,1005)),fill="rgb(0,255,0)")
draw.polygon(((1792,1025),(1812,1025),(1802,1005)),fill="rgb(0,255,0)")
draw.polygon(((1812,1025),(1832,1025),(1822,1005)),fill="rgb(0,255,0)")
elif hpaSign == "-":
draw.polygon(((1772,1005),(1792,1005),(1782,1025)),fill="rgb(255,0,0)")
elif hpaSign == "--":
draw.polygon(((1772,1005),(1792,1005),(1782,1025)),fill="rgb(255,0,0)")
draw.polygon(((1792,1005),(1812,1005),(1802,1025)),fill="rgb(255,0,0)")
elif hpaSign == "---":
draw.polygon(((1772,1005),(1792,1005),(1782,1025)),fill="rgb(255,0,0)")
draw.polygon(((1792,1005),(1812,1005),(1802,1025)),fill="rgb(255,0,0)")
draw.polygon(((1812,1005),(1832,1005),(1822,1025)),fill="rgb(255,0,0)")
# max/min schreiben -------------------------------
draw.text((1530,1020),"D",(255,255,255),font=font)
draw.text((1570,1003),hpastrTh,(255,255,255),font=fontk)
draw.text((1570,1039),hpastrTt,(255,255,255),font=fontk)
# Eventtext schreiben -----------------------------
EventArray = [];
EventText = ""
# Datei Event.csv in Array EventArray einlesen
csvReader = csv.reader(open('/home/pi/Event.csv', 'r'), delimiter=';');
for row in csvReader:
EventArray.append(row);
# JJMMTT in Array EventArray suchen - mit 1 beginnen wegen Überschrift
for i in range(1, len(EventArray)):
if EventArray[i][0] == JJMMTT:
EventText = EventArray[i][1]
break
if EventText != "":
draw.rectangle((81,0,1838,55),fill=(80,80,80,144))
draw.text((38,3),EventText,(255,255,255),font=fontg)
# -----------------------------------------------------------------------
# Array mit Sonnenauf- und untergangszeiten (Minuten)
SonneAU = [];
# Datei YY.csv in Array SonneAU einlesen
csvReader = csv.reader(open('/home/pi/' + YY + '.csv', 'r'), delimiter=';');
for row in csvReader:
SonneAU.append(row);
# TTMM und Tagesminute TagMin in Array SonneAU suchen
for i in range(0, len(SonneAU)):
if SonneAU[i][0] == TTMM:
SonneAuf = int(SonneAU[i][3]) - OffsetAuf
SonneUnter = int (SonneAU[i][4]) + OffsetUnter
break
# Bild speichern
if (SonneAuf <= int(TagMin)) and (SonneUnter >= int(TagMin)):
# bild.save(dirJahr+'P'+Zeit+'.jpg', format='JPEG', subsampling=0, quality=100)
bild.save(dirJahr+'P'+Zeit+'.jpg')
# Nachtbild nicht mehr speichern
# else:
# bild.save(dirJahrN+'P'+Zeit+'.jpg')
bild.save('/media/usbhdd/webpic/weather.jpg')
#--------------------------------------------
# MQTT
#--------------------------------------------
client = mqtt.Client()
client.on_connect = on_connect
try:
client.connect("10.0.0.9", 1883, 60)
mqtt_string = {"time":ZeitPIC,"humidity_out":str(hum),"temp_out":str(temp),"pressure":str(hpa)}
data_out = json.dumps(mqtt_string)
client.publish("raspicam/weather/data", data_out)
except:
pass
#--------------------------------------------
# Bild resize 640
#--------------------------------------------
bild640 = bild.resize((640, 360), Image.ANTIALIAS)
bild640.save('/media/usbhdd/webpic/weather640.jpg')
# Programmende----------------------------------------------------------------