🎉 Improved Energy Monitoring Dashboard & Backend Integration 🌍

This commit is contained in:
2025-06-12 19:54:56 +02:00
parent 10423eb1e3
commit 33e3200523
4 changed files with 1241 additions and 0 deletions

View File

@@ -660,6 +660,204 @@ class TapoController:
tapo_logger.error(f"❌ Fehler beim Speichern der Steckdose {ip_address} in Datenbank: {str(e)}")
return False
def _collect_device_info(self, p110, device_info):
"""
Sammelt erweiterte Geräteinformationen einschließlich Energiedaten.
Args:
p110: PyP110 Instanz
device_info: Basis-Geräteinformationen
Returns:
Dict: Erweiterte Geräteinformationen
"""
extra_info = {}
try:
# Firmware-Version extrahieren
if 'fw_ver' in device_info.get('result', {}):
extra_info['firmware_version'] = device_info['result']['fw_ver']
# Energiedaten abrufen (nur für P110)
if 'P110' in device_info.get('result', {}).get('model', ''):
try:
energy_usage = p110.getEnergyUsage()
if energy_usage and 'result' in energy_usage:
energy_data = energy_usage['result']
# Aktuelle Leistungsdaten
extra_info['current_power'] = energy_data.get('current_power', 0) / 1000 # mW zu W
extra_info['power_consumption'] = extra_info['current_power']
# Historische Energiedaten
extra_info['today_energy'] = energy_data.get('today_energy', 0)
extra_info['month_energy'] = energy_data.get('month_energy', 0)
extra_info['today_runtime'] = energy_data.get('today_runtime', 0)
extra_info['month_runtime'] = energy_data.get('month_runtime', 0)
# 24h Verbrauchsdaten
extra_info['past24h'] = energy_data.get('past24h', [])
extra_info['past30d'] = energy_data.get('past30d', [])
extra_info['past1y'] = energy_data.get('past1y', [])
# Zusätzliche Metriken
if 'voltage' in energy_data:
extra_info['voltage'] = energy_data['voltage'] / 1000 # mV zu V
if 'current' in energy_data:
extra_info['current'] = energy_data['current'] / 1000 # mA zu A
hardware_logger.debug(f"Energiedaten erfolgreich abgerufen: {extra_info['current_power']}W")
except Exception as e:
hardware_logger.warning(f"Konnte Energiedaten nicht abrufen: {str(e)}")
except Exception as e:
hardware_logger.warning(f"Fehler beim Sammeln erweiterter Geräteinformationen: {str(e)}")
return extra_info
def get_energy_statistics(self) -> Dict[str, Any]:
"""
Sammelt Energiestatistiken von allen P110 Steckdosen.
Returns:
Dict: Aggregierte Energiestatistiken
"""
hardware_logger.info("🔋 Sammle Energiestatistiken von allen P110 Steckdosen...")
try:
db_session = get_db_session()
printers = db_session.query(Printer).filter(
Printer.active == True,
Printer.plug_ip.isnot(None)
).all()
statistics = {
'total_devices': 0,
'online_devices': 0,
'total_current_power': 0.0,
'total_today_energy': 0.0,
'total_month_energy': 0.0,
'devices': [],
'hourly_consumption': [0] * 24, # 24 Stunden
'daily_consumption': [0] * 30, # 30 Tage
'monthly_consumption': [0] * 12, # 12 Monate
'timestamp': datetime.now().isoformat()
}
for printer in printers:
device_stats = {
'id': printer.id,
'name': printer.name,
'location': printer.location,
'model': printer.model,
'ip': printer.plug_ip,
'online': False,
'current_power': 0.0,
'today_energy': 0.0,
'month_energy': 0.0,
'voltage': 0.0,
'current': 0.0,
'past24h': [],
'past30d': [],
'past1y': []
}
statistics['total_devices'] += 1
try:
# P110 Energiedaten abrufen
p110 = PyP100.P110(printer.plug_ip, self.username, self.password)
p110.handshake()
p110.login()
# Geräteinformationen
device_info = p110.getDeviceInfo()
if not device_info or 'result' not in device_info:
continue
# Nur P110 Geräte verarbeiten
if 'P110' not in device_info['result'].get('model', ''):
continue
# Energiedaten abrufen
energy_usage = p110.getEnergyUsage()
if energy_usage and 'result' in energy_usage:
energy_data = energy_usage['result']
device_stats['online'] = True
device_stats['current_power'] = energy_data.get('current_power', 0) / 1000 # mW zu W
device_stats['today_energy'] = energy_data.get('today_energy', 0)
device_stats['month_energy'] = energy_data.get('month_energy', 0)
device_stats['past24h'] = energy_data.get('past24h', [])
device_stats['past30d'] = energy_data.get('past30d', [])
device_stats['past1y'] = energy_data.get('past1y', [])
# Aggregierte Werte
statistics['online_devices'] += 1
statistics['total_current_power'] += device_stats['current_power']
statistics['total_today_energy'] += device_stats['today_energy']
statistics['total_month_energy'] += device_stats['month_energy']
# Stündliche Daten aggregieren (letzten 24h)
if device_stats['past24h']:
for i, hourly_value in enumerate(device_stats['past24h'][:24]):
if i < len(statistics['hourly_consumption']):
statistics['hourly_consumption'][i] += hourly_value
# Tägliche Daten aggregieren (letzten 30 Tage)
if device_stats['past30d']:
for i, daily_value in enumerate(device_stats['past30d'][:30]):
if i < len(statistics['daily_consumption']):
statistics['daily_consumption'][i] += daily_value
# Monatliche Daten aggregieren (letzten 12 Monate)
if device_stats['past1y']:
for i, monthly_value in enumerate(device_stats['past1y'][:12]):
if i < len(statistics['monthly_consumption']):
statistics['monthly_consumption'][i] += monthly_value
hardware_logger.debug(f"✅ Energiedaten für {printer.name}: {device_stats['current_power']}W")
except Exception as e:
hardware_logger.warning(f"⚠️ Konnte Energiedaten für {printer.name} nicht abrufen: {str(e)}")
statistics['devices'].append(device_stats)
db_session.close()
# Durchschnittswerte berechnen
if statistics['online_devices'] > 0:
statistics['avg_current_power'] = statistics['total_current_power'] / statistics['online_devices']
statistics['avg_today_energy'] = statistics['total_today_energy'] / statistics['online_devices']
statistics['avg_month_energy'] = statistics['total_month_energy'] / statistics['online_devices']
else:
statistics['avg_current_power'] = 0.0
statistics['avg_today_energy'] = 0.0
statistics['avg_month_energy'] = 0.0
hardware_logger.info(f"✅ Energiestatistiken erfolgreich gesammelt: {statistics['online_devices']}/{statistics['total_devices']} Geräte online")
hardware_logger.info(f"📊 Gesamtverbrauch: {statistics['total_current_power']:.1f}W aktuell, {statistics['total_today_energy']}Wh heute")
return statistics
except Exception as e:
hardware_logger.error(f"❌ Fehler beim Sammeln der Energiestatistiken: {str(e)}")
return {
'total_devices': 0,
'online_devices': 0,
'total_current_power': 0.0,
'total_today_energy': 0.0,
'total_month_energy': 0.0,
'devices': [],
'hourly_consumption': [0] * 24,
'daily_consumption': [0] * 30,
'monthly_consumption': [0] * 12,
'timestamp': datetime.now().isoformat(),
'error': str(e)
}
# ===== PRINTER MONITOR =====
class PrinterMonitor: