import sqlite3 import logging from datetime import datetime, timedelta class TemperatureDB: def __init__(self, db_file='temperature_history.db'): self.db_file = db_file self.init_db() def get_connection(self): """Створення підключення до бази даних""" try: conn = sqlite3.connect(self.db_file) conn.row_factory = sqlite3.Row return conn except Exception as e: logging.error(f"Failed to connect to database: {e}") raise def init_db(self): """Ініціалізація бази даних""" try: conn = self.get_connection() c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS temperatures ( id INTEGER PRIMARY KEY AUTOINCREMENT, host TEXT NOT NULL, gpu_temp REAL, cpu_temp REAL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP ) ''') conn.commit() logging.info("Database initialized successfully") except Exception as e: logging.error(f"Failed to initialize database: {e}") raise finally: if 'conn' in locals(): conn.close() def add_temperature(self, host, gpu_temp, cpu_temp): """Додавання нового запису температури""" try: conn = self.get_connection() c = conn.cursor() c.execute(''' INSERT INTO temperatures (host, gpu_temp, cpu_temp, timestamp) VALUES (?, ?, ?, datetime('now', 'localtime')) ''', (host, gpu_temp, cpu_temp)) conn.commit() logging.debug(f"Added temperature record for {host}: GPU={gpu_temp}°C, CPU={cpu_temp}°C") except Exception as e: logging.error(f"Failed to add temperature record: {e}") raise finally: if 'conn' in locals(): conn.close() def get_history(self, host, minutes=30): """Отримання історії температур за останні N хвилин""" try: conn = self.get_connection() c = conn.cursor() time_threshold = (datetime.now() - timedelta(minutes=minutes)).strftime('%Y-%m-%d %H:%M:%S') c.execute(''' SELECT gpu_temp, cpu_temp, timestamp FROM temperatures WHERE host = ? AND timestamp > ? ORDER BY timestamp ASC ''', (host, time_threshold)) results = c.fetchall() return { 'gpu': [r['gpu_temp'] for r in results], 'cpu': [r['cpu_temp'] for r in results], 'timestamps': [r['timestamp'].split(' ')[1] for r in results] # Беремо тільки час } except Exception as e: logging.error(f"Failed to retrieve history: {e}") raise finally: if 'conn' in locals(): conn.close() def cleanup_old_records(self, minutes=30): """Видалення старих записів""" try: conn = self.get_connection() c = conn.cursor() time_threshold = (datetime.now() - timedelta(minutes=minutes)).strftime('%Y-%m-%d %H:%M:%S') c.execute('DELETE FROM temperatures WHERE timestamp < ?', (time_threshold,)) conn.commit() logging.info(f"Old records older than {minutes} minutes have been cleaned up") except Exception as e: logging.error(f"Failed to cleanup old records: {e}") raise finally: if 'conn' in locals(): conn.close()