📚 Improved backend structure & logging (#123) - Streamlined database connections, optimized log files, and refactored configurations for better maintainability. 🌳🔍📈💻🖥️

This commit is contained in:
Till Tomczak
2025-06-20 11:13:42 +02:00
parent eecbb5d267
commit a8584d4175
17 changed files with 178 additions and 44 deletions

Binary file not shown.

View File

@ -418,60 +418,53 @@ def control_printer_power(printer_id):
}), 404
# Prüfen, ob Drucker eine Steckdose konfiguriert hat
if not printer.plug_ip or not printer.plug_username or not printer.plug_password:
if not printer.plug_ip:
db_session.close()
return jsonify({
"success": False,
"error": f"Drucker {printer.name} hat keine Steckdose konfiguriert"
}), 400
# Steckdose steuern
from PyP100 import PyP110
db_session.close() # Session früh schließen
# Hardware-Integration für Steuerung verwenden (zentrale Logik)
try:
# TP-Link Tapo P110 Verbindung herstellen
p110 = PyP110.P110(printer.plug_ip, printer.plug_username, printer.plug_password)
p110.handshake() # Authentifizierung
p110.login() # Login
drucker_steuerung = get_drucker_steuerung()
# Steckdose ein- oder ausschalten
if action == "on":
p110.turnOn()
success = True
message = "Steckdose erfolgreich eingeschaltet"
printer.status = "starting" # Status aktualisieren
ergebnis = drucker_steuerung.drucker_einschalten(
printer_id,
grund=f"API-Steuerung von {current_user.name}"
)
else:
p110.turnOff()
success = True
message = "Steckdose erfolgreich ausgeschaltet"
printer.status = "offline" # Status aktualisieren
ergebnis = drucker_steuerung.drucker_ausschalten(
printer_id,
grund=f"API-Steuerung von {current_user.name}"
)
if ergebnis['success']:
printers_logger.info(f"{action.upper()}: Drucker {printer.name} erfolgreich über API gesteuert")
return jsonify({
"success": True,
"message": ergebnis['message'],
"printer_id": printer_id,
"printer_name": printer.name,
"action": action,
"timestamp": datetime.now().isoformat()
})
else:
printers_logger.error(f"❌ API-Steuerung für {printer.name} fehlgeschlagen: {ergebnis['error']}")
return jsonify({
"success": False,
"error": ergebnis['error']
}), 500
# Zeitpunkt der letzten Prüfung aktualisieren
printer.last_checked = datetime.now()
db_session.commit()
# Cache leeren, damit neue Status-Abfragen aktuell sind
monitor = get_printer_monitor()
monitor.clear_all_caches()
printers_logger.info(f"{action.upper()}: Drucker {printer.name} erfolgreich {message}")
except Exception as e:
printers_logger.error(f"❌ Fehler bei Steckdosensteuerung für {printer.name}: {str(e)}")
db_session.close()
printers_logger.error(f"❌ Fehler bei Hardware-Integration für {printer.name}: {str(e)}")
return jsonify({
"success": False,
"error": f"Fehler bei Steckdosensteuerung: {str(e)}"
"error": f"Hardware-Integrationsfehler: {str(e)}"
}), 500
db_session.close()
return jsonify({
"success": True,
"message": message,
"printer_id": printer_id,
"printer_name": printer.name,
"action": action,
"timestamp": datetime.now().isoformat()
})
except Exception as e:
printers_logger.error(f"❌ Allgemeiner Fehler bei Stromsteuerung: {str(e)}")

View File

@ -63388,3 +63388,13 @@ WHERE users.role = ?]
2025-06-20 10:58:58 - [app] app - [INFO] INFO - [SHUTDOWN] 🧹 Cleanup wird ausgeführt...
2025-06-20 10:58:58 - [app] app - [INFO] INFO - [SHUTDOWN] ✅ Queue Manager gestoppt
2025-06-20 10:58:58 - [app] app - [ERROR] ERROR - [SHUTDOWN] ❌ Cleanup-Fehler:
2025-06-20 11:02:04 - [app] app - [INFO] INFO - Optimierte SQLite-Engine erstellt: backend/database/myp.db
2025-06-20 11:02:04 - [app] app - [INFO] INFO - SQLite für Raspberry Pi optimiert (reduzierte Cache-Größe, SD-Karten I/O)
2025-06-20 11:02:04 - [app] app - [INFO] INFO - Datenbank mit Optimierungen initialisiert
2025-06-20 11:02:27 - [app] app - [INFO] INFO - Optimierte SQLite-Engine erstellt: backend/database/myp.db
2025-06-20 11:02:27 - [app] app - [INFO] INFO - SQLite für Raspberry Pi optimiert (reduzierte Cache-Größe, SD-Karten I/O)
2025-06-20 11:02:27 - [app] app - [INFO] INFO - Datenbank mit Optimierungen initialisiert
2025-06-20 11:05:07 - [app] app - [INFO] INFO - Optimierte SQLite-Engine erstellt: backend/database/myp.db
2025-06-20 11:05:07 - [app] app - [INFO] INFO - SQLite für Raspberry Pi optimiert (reduzierte Cache-Größe, SD-Karten I/O)
2025-06-20 11:05:07 - [app] app - [INFO] INFO - Datenbank mit Optimierungen initialisiert
2025-06-20 11:05:33 - [app] app - [INFO] INFO - Optimierte SQLite-Engine erstellt: backend/database/myp.db

View File

@ -1019,3 +1019,5 @@
2025-06-20 10:58:00 - [data_management] data_management - [INFO] INFO - 📊 Massive Konsolidierung: 3 Dateien → 1 Datei (67% Reduktion)
2025-06-20 10:58:20 - [data_management] data_management - [INFO] INFO - ✅ Data Management Module initialisiert
2025-06-20 10:58:20 - [data_management] data_management - [INFO] INFO - 📊 Massive Konsolidierung: 3 Dateien → 1 Datei (67% Reduktion)
2025-06-20 11:05:07 - [data_management] data_management - [INFO] INFO - ✅ Data Management Module initialisiert
2025-06-20 11:05:07 - [data_management] data_management - [INFO] INFO - 📊 Massive Konsolidierung: 3 Dateien → 1 Datei (67% Reduktion)

View File

@ -3818,3 +3818,8 @@
2025-06-20 10:58:20 - [hardware_integration] hardware_integration - [INFO] INFO - 🚀 Hardware Integration (Backend-Kontrolle) erfolgreich geladen
2025-06-20 10:58:21 - [hardware_integration] hardware_integration - [INFO] INFO - 🎯 DruckerSteuerung initialisiert - BACKEND ÜBERNIMMT KONTROLLE
2025-06-20 10:58:21 - [hardware_integration] hardware_integration - [INFO] INFO - 🚧 Entwicklungsumgebung erkannt - Erweiterte Simulation aktiviert
2025-06-20 11:02:27 - [hardware_integration] hardware_integration - [INFO] INFO - 🚀 Hardware Integration (Backend-Kontrolle) erfolgreich geladen
2025-06-20 11:05:07 - [hardware_integration] hardware_integration - [INFO] INFO - 🚀 Hardware Integration (Backend-Kontrolle) erfolgreich geladen
2025-06-20 11:05:33 - [hardware_integration] hardware_integration - [INFO] INFO - 🚀 Hardware Integration (Backend-Kontrolle) erfolgreich geladen
2025-06-20 11:05:33 - [hardware_integration] hardware_integration - [INFO] INFO - 🎯 DruckerSteuerung initialisiert - BACKEND ÜBERNIMMT KONTROLLE
2025-06-20 11:05:33 - [hardware_integration] hardware_integration - [INFO] INFO - 🚧 Entwicklungsumgebung erkannt - Erweiterte Simulation aktiviert

View File

@ -1971,3 +1971,7 @@
2025-06-20 10:58:20 - [job_queue_system] job_queue_system - [INFO] INFO - 📊 MASSIVE Konsolidierung: 4 Dateien → 1 Datei (75% Reduktion)
2025-06-20 10:58:21 - [job_queue_system] job_queue_system - [INFO] INFO - Queue Manager gestartet (Legacy-Kompatibilität)
2025-06-20 10:58:58 - [job_queue_system] job_queue_system - [INFO] INFO - Queue Manager gestoppt (Legacy-Kompatibilität)
2025-06-20 11:02:27 - [job_queue_system] job_queue_system - [INFO] INFO - ✅ Job & Queue System Module initialisiert
2025-06-20 11:02:27 - [job_queue_system] job_queue_system - [INFO] INFO - 📊 MASSIVE Konsolidierung: 4 Dateien → 1 Datei (75% Reduktion)
2025-06-20 11:05:07 - [job_queue_system] job_queue_system - [INFO] INFO - ✅ Job & Queue System Module initialisiert
2025-06-20 11:05:07 - [job_queue_system] job_queue_system - [INFO] INFO - 📊 MASSIVE Konsolidierung: 4 Dateien → 1 Datei (75% Reduktion)

View File

@ -1524,3 +1524,5 @@
2025-06-20 10:58:20 - [security_suite] security_suite - [INFO] INFO - ✅ Security Suite Module initialisiert
2025-06-20 10:58:20 - [security_suite] security_suite - [INFO] INFO - 📊 Massive Konsolidierung: 3 Dateien → 1 Datei (67% Reduktion)
2025-06-20 10:58:21 - [security_suite] security_suite - [INFO] INFO - 🔒 Security Suite initialisiert
2025-06-20 11:05:07 - [security_suite] security_suite - [INFO] INFO - ✅ Security Suite Module initialisiert
2025-06-20 11:05:07 - [security_suite] security_suite - [INFO] INFO - 📊 Massive Konsolidierung: 3 Dateien → 1 Datei (67% Reduktion)

View File

@ -1325,3 +1325,11 @@
2025-06-20 10:58:00 - [utilities_collection] utilities_collection - [INFO] INFO - 🚨 ALLERLETZTE MEGA-Konsolidierung: 12+ Dateien → 1 Datei (90%+ Reduktion)
2025-06-20 10:58:20 - [utilities_collection] utilities_collection - [INFO] INFO - ✅ Utilities Collection initialisiert
2025-06-20 10:58:20 - [utilities_collection] utilities_collection - [INFO] INFO - 🚨 ALLERLETZTE MEGA-Konsolidierung: 12+ Dateien → 1 Datei (90%+ Reduktion)
2025-06-20 11:02:04 - [utilities_collection] utilities_collection - [INFO] INFO - ✅ Utilities Collection initialisiert
2025-06-20 11:02:04 - [utilities_collection] utilities_collection - [INFO] INFO - 🚨 ALLERLETZTE MEGA-Konsolidierung: 12+ Dateien → 1 Datei (90%+ Reduktion)
2025-06-20 11:02:27 - [utilities_collection] utilities_collection - [INFO] INFO - ✅ Utilities Collection initialisiert
2025-06-20 11:02:27 - [utilities_collection] utilities_collection - [INFO] INFO - 🚨 ALLERLETZTE MEGA-Konsolidierung: 12+ Dateien → 1 Datei (90%+ Reduktion)
2025-06-20 11:05:07 - [utilities_collection] utilities_collection - [INFO] INFO - ✅ Utilities Collection initialisiert
2025-06-20 11:05:07 - [utilities_collection] utilities_collection - [INFO] INFO - 🚨 ALLERLETZTE MEGA-Konsolidierung: 12+ Dateien → 1 Datei (90%+ Reduktion)
2025-06-20 11:05:33 - [utilities_collection] utilities_collection - [INFO] INFO - ✅ Utilities Collection initialisiert
2025-06-20 11:05:33 - [utilities_collection] utilities_collection - [INFO] INFO - 🚨 ALLERLETZTE MEGA-Konsolidierung: 12+ Dateien → 1 Datei (90%+ Reduktion)

View File

@ -4,6 +4,8 @@
{% block head %}
{{ super() }}
<!-- CSRF-Token für AJAX-Requests -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Chart.js für Energiediagramme -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Enhanced CSS für Energiemonitoring mit Dark/Light Mode -->
@ -334,7 +336,7 @@
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Status</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Aktuelle Leistung</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Tagesverbrauch</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Aktionen</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">Steuerung</th>
</tr>
</thead>
<tbody id="device-table-body" class="bg-white dark:bg-slate-800 divide-y divide-slate-200 dark:divide-slate-700">
@ -577,14 +579,122 @@ function updateDeviceTable(devices) {
<div class="text-sm text-slate-500 dark:text-slate-400">Heute</div>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
<a href="/energy/device/${device.id}" class="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 transition-colors duration-200">
Details anzeigen
</a>
<div class="flex space-x-2">
<!-- Steuerungsbutton für Drucker mit konfigurierten Steckdosen -->
${device.ip ?
`<button onclick="togglePrinter(${device.id}, '${device.online ? 'off' : 'on'}')"
class="px-3 py-1 rounded-md text-xs font-medium transition-colors duration-200 ${device.online ?
'bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50' :
'bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50'
}">
${device.online ? '🔴 Ausschalten' : '🟢 Einschalten'}
</button>` :
`<span class="px-3 py-1 rounded-md text-xs font-medium bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400">
Keine Steckdose
</span>`
}
<a href="/energy/device/${device.id}" class="px-3 py-1 bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50 rounded-md text-xs font-medium transition-colors duration-200">
Details
</a>
</div>
</td>
`;
tbody.appendChild(row);
});
}
async function togglePrinter(printerId, action) {
try {
const response = await fetch(`/api/printers/control/${printerId}/power`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCSRFToken()
},
body: JSON.stringify({ action: action })
});
if (response.ok) {
const result = await response.json();
if (result.success) {
// Erfolgsmeldung anzeigen
showNotification(`Drucker ${result.printer_name} wurde ${action === 'on' ? 'eingeschaltet' : 'ausgeschaltet'}`, 'success');
// Daten neu laden nach 2 Sekunden
setTimeout(() => {
loadEnergyData();
loadDeviceList();
}, 2000);
} else {
showNotification(`Fehler: ${result.error}`, 'error');
}
} else {
const errorData = await response.json();
showNotification(`API-Fehler: ${errorData.error || 'Unbekannter Fehler'}`, 'error');
}
} catch (error) {
console.error('Fehler beim Schalten des Druckers:', error);
showNotification('Verbindungsfehler beim Schalten des Druckers', 'error');
}
}
function getCSRFToken() {
// CSRF-Token aus Meta-Tag oder Cookie holen
const csrfMeta = document.querySelector('meta[name="csrf-token"]');
if (csrfMeta) {
return csrfMeta.getAttribute('content');
}
// Fallback: Cookie lesen
const name = 'csrf_token=';
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
function showNotification(message, type) {
// Notification erstellen
const notification = document.createElement('div');
notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 ${
type === 'success' ?
'bg-green-100 text-green-800 border border-green-200 dark:bg-green-900/30 dark:text-green-400 dark:border-green-800' :
'bg-red-100 text-red-800 border border-red-200 dark:bg-red-900/30 dark:text-red-400 dark:border-red-800'
}`;
notification.innerHTML = `
<div class="flex items-center">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
${type === 'success' ?
'<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>' :
'<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>'
}
</svg>
<span>${message}</span>
</div>
`;
document.body.appendChild(notification);
// Nach 5 Sekunden automatisch entfernen
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transform = 'translateX(100%)';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 5000);
}
</script>
{% endblock %}