Problem:
Auf einem Raspberry Pi 4B werden die DHT22 Daten für Luftfeuchtigkeit und Raumtemperatur auf dem 20x4 Display ausgegeben. Zusätzlich wird jede 10. Messung in einer externen Datenbank gespeichert. Aus dieser Datenbank werden auch die DHT Daten von anderen Räumen ausgelesen und auf dem Display dargestellt. Der Datenbankserver ist auch ein Pi 4B mit DHT22 Sensor.
Falls der Datenbankserver unerreichbar ist, bricht das Skript mit Exception during handling Exception ab, (entweder mit no route to host oder timed out). Das Skript soll aber unendlich weiterlaufen, auch wenn die Datenbank unerreichbar ist. Muss ich mehrere Excepts ineinander verschachteln oder wie bekomme ich das hin?
Quellcode
Python
#!/usr/bin/env python3
from time import sleep
from datetime import timedelta, datetime
from gpiozero import CPUTemperature, Button
from picamera import PiCamera
import mysql.connector as mc
from Adafruit_CharLCD import Adafruit_CharLCD
import Adafruit_GPIO.PCF8574 as PCF
import psutil
import board
import adafruit_dht
dhtDevice = adafruit_dht.DHT22(board.D26)
GPIO = PCF.PCF8574(address=0x27)
GPIO.setup(5,0)
GPIO.output(5,0)
lcd_rs = 4
lcd_en = 7
d4,d5,d6,d7 = 0,1,2,3
cols,lines = 20,4
lcd = Adafruit_CharLCD(lcd_rs, lcd_en, d4, d5, d6, d7,cols, lines, gpio=GPIO)
lcd.clear()
#...
# while Schleife
while Ausgabe.get_modus()==0:
lcd.message("SYSYTEM \n MONITORING\n")
sleep(4)
lcd.clear()
lcd.message(datetime.now().strftime("%a %H:%M\n%d.%m.%Y"))
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_string = str(timedelta(seconds = uptime_seconds))
cut_string = uptime_string.split('.')
uptimeserver = cut_string[0]
lcd.message(f"\n\nUptime\n{uptimeserver}")
sleep(10)
lcd.clear()
cpu = CPUTemperature()
cputemperatur=str(cpu.temperature)
cpufreq = cpu_auslesen()
lcd.message(f"CPU Temperature\n{cputemperatur} C \nCPU Speed\n{cpufreq.current} MHz")
sleep(10)
lcd.clear()
try:
raumtemperatur = dhtDevice.temperature
luftfeuchtigkeit = dhtDevice.humidity
lcd.message(f"Raumtemperatur\n{raumtemperatur} C\nLuftfeuchtigkeit\n{luftfeuchtigkeit}%")
print(f"Raumtemperatur:\n{raumtemperatur} C\nLuftfeuchtigkeit:\n{luftfeuchtigkeit}%")
sleep(10)
lcd.clear()
except:
print("Auslesefehler")
if (Durchlauf % 10 == 0):
try:
print(f"CPU Temperatur: {cpu.temperature} °C")
uhrzeit = str(datetime.now().strftime("%d.%m.%Y - %H:%M"))
connection = mc.connect (host = "192.168.1.20",
user = "dhtuser",
passwd = "abc",
db = "messungen")
cursor = connection.cursor(prepared=True)
sql_command = """
INSERT INTO dht11 (uhrzeit,luftfeuchtigkeit,raumtemperatur,cputemperatur)
VALUES(%s,%s,%s,%s);"""
eintrag = (uhrzeit,luftfeuchtigkeit,raumtemperatur,cputemperatur)
cursor.execute(sql_command,eintrag)
connection.commit()
cursor.close()
connection.close()
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
try:
connection = mc.connect (host = "192.168.1.20",
user = "dhtuser",
passwd = "abc",
db = "messungen")
cursor = connection.cursor()
sql_command = """
SELECT uhrzeit, luftfeuchtigkeit, raumtemperatur FROM dht22 WHERE id ORDER by id DESC LIMIT 1"""
cursor.execute(sql_command)
for (uhrzeit, luftfeuchtigkeit, raumtemperatur) in cursor:
lcd.message(f"Wohnzimmer\n{raumtemperatur} C\n{uhrzeit}\n{luftfeuchtigkeit}%")
cursor.close()
connection.close()
sleep(10)
lcd.clear()
except RuntimeError as error:
print(error.args[0])
Durchlauf+=1
lcd.clear()
Alles anzeigen
Exception
Code
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/mysql/connector/network.py", line 529, in open_connection
self.sock.connect(sockaddr)
TimeoutError: [Errno 110] Connection timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/Breadboard/joyitdisplay/dht22.py", line 292, in <module>
main()
File "/home/pi/Breadboard/joyitdisplay/dht22.py", line 258, in main
db = "messstation")
File "/usr/lib/python3/dist-packages/mysql/connector/__init__.py", line 173, in connect
return MySQLConnection(*args, **kwargs)
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 102, in __init__
self.connect(**kwargs)
File "/usr/lib/python3/dist-packages/mysql/connector/abstracts.py", line 735, in connect
self._open_connection()
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 248, in _open_connection
self._socket.open_connection()
File "/usr/lib/python3/dist-packages/mysql/connector/network.py", line 532, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '192.168.1.20:3306' (110 Connection timed out)
Alles anzeigen