import sqlite3 import logging from typing import Optional, Dict, List, Tuple from datetime import datetime import threading class NodeDatabase: """Database manager for storing and retrieving node information""" def __init__(self, db_path: str = "nodes.db"): self.db_path = db_path self.lock = threading.Lock() self._init_database() def _init_database(self): """Initialize the database and create tables if they don't exist""" with self.lock: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Create nodes table cursor.execute(''' CREATE TABLE IF NOT EXISTS nodes ( node_id INTEGER PRIMARY KEY, short_name TEXT, long_name TEXT, hw_model TEXT, role TEXT, last_heard INTEGER, created_at INTEGER, updated_at INTEGER ) ''') # Create index for faster lookups cursor.execute(''' CREATE INDEX IF NOT EXISTS idx_node_id ON nodes(node_id) ''') conn.commit() conn.close() def update_node(self, node_id: int, short_name: str = None, long_name: str = None, hw_model: str = None, role: str = None) -> bool: """Update or insert node information""" with self.lock: try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() now = int(datetime.now().timestamp()) # Check if node exists cursor.execute('SELECT node_id FROM nodes WHERE node_id = ?', (node_id,)) exists = cursor.fetchone() is not None if exists: # Update existing node updates = [] params = [] if short_name is not None: updates.append("short_name = ?") params.append(short_name) if long_name is not None: updates.append("long_name = ?") params.append(long_name) if hw_model is not None: updates.append("hw_model = ?") params.append(hw_model) if role is not None: updates.append("role = ?") params.append(role) updates.append("last_heard = ?") params.append(now) updates.append("updated_at = ?") params.append(now) params.append(node_id) query = f"UPDATE nodes SET {', '.join(updates)} WHERE node_id = ?" cursor.execute(query, params) else: # Insert new node cursor.execute(''' INSERT INTO nodes (node_id, short_name, long_name, hw_model, role, last_heard, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ''', (node_id, short_name, long_name, hw_model, role, now, now, now)) conn.commit() conn.close() logging.info(f"Node {node_id} {'updated' if exists else 'added'}: " f"short_name={short_name}, long_name={long_name}") return True except Exception as e: logging.error(f"Error updating node {node_id}: {e}") return False def get_node_name(self, node_id: int) -> str: """Get the best available name for a node, fallback to ID if not found""" with self.lock: try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(''' SELECT short_name, long_name FROM nodes WHERE node_id = ? ''', (node_id,)) result = cursor.fetchone() conn.close() if result: short_name, long_name = result # Prefer short_name, then long_name, then ID if short_name and short_name.strip(): return short_name.strip() elif long_name and long_name.strip(): return long_name.strip() # Fallback to ID as hex string (Meshtastic convention) return f"!{node_id:08x}" except Exception as e: logging.error(f"Error getting node name for {node_id}: {e}") return f"!{node_id:08x}" def get_node_info(self, node_id: int) -> Optional[Dict]: """Get complete information about a node""" with self.lock: try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(''' SELECT node_id, short_name, long_name, hw_model, role, last_heard, created_at, updated_at FROM nodes WHERE node_id = ? ''', (node_id,)) result = cursor.fetchone() conn.close() if result: return { 'node_id': result[0], 'short_name': result[1], 'long_name': result[2], 'hw_model': result[3], 'role': result[4], 'last_heard': result[5], 'created_at': result[6], 'updated_at': result[7] } return None except Exception as e: logging.error(f"Error getting node info for {node_id}: {e}") return None def get_all_nodes(self) -> List[Dict]: """Get information about all nodes in the database""" with self.lock: try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(''' SELECT node_id, short_name, long_name, hw_model, role, last_heard, created_at, updated_at FROM nodes ORDER BY last_heard DESC ''') results = cursor.fetchall() conn.close() nodes = [] for row in results: nodes.append({ 'node_id': row[0], 'short_name': row[1], 'long_name': row[2], 'hw_model': row[3], 'role': row[4], 'last_heard': row[5], 'created_at': row[6], 'updated_at': row[7] }) return nodes except Exception as e: logging.error(f"Error getting all nodes: {e}") return [] def cleanup_old_nodes(self, days: int = 30) -> int: """Remove nodes not heard from in the specified number of days""" with self.lock: try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cutoff_time = int(datetime.now().timestamp()) - (days * 24 * 60 * 60) cursor.execute('DELETE FROM nodes WHERE last_heard < ?', (cutoff_time,)) deleted = cursor.rowcount conn.commit() conn.close() if deleted > 0: logging.info(f"Cleaned up {deleted} old nodes (not heard in {days} days)") return deleted except Exception as e: logging.error(f"Error cleaning up old nodes: {e}") return 0 def get_statistics(self) -> Dict: """Get database statistics""" with self.lock: try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute('SELECT COUNT(*) FROM nodes') total_nodes = cursor.fetchone()[0] # Nodes heard in last 24 hours cutoff_24h = int(datetime.now().timestamp()) - (24 * 60 * 60) cursor.execute('SELECT COUNT(*) FROM nodes WHERE last_heard > ?', (cutoff_24h,)) active_24h = cursor.fetchone()[0] # Nodes heard in last 7 days cutoff_7d = int(datetime.now().timestamp()) - (7 * 24 * 60 * 60) cursor.execute('SELECT COUNT(*) FROM nodes WHERE last_heard > ?', (cutoff_7d,)) active_7d = cursor.fetchone()[0] conn.close() return { 'total_nodes': total_nodes, 'active_24h': active_24h, 'active_7d': active_7d } except Exception as e: logging.error(f"Error getting statistics: {e}") return { 'total_nodes': 0, 'active_24h': 0, 'active_7d': 0 }