From c0d21bf6ca8bbe09f859ee3659bb7bc58d65bcab Mon Sep 17 00:00:00 2001 From: Ilya Tolstenko Date: Mon, 18 Aug 2025 09:15:24 +0300 Subject: [PATCH] SQLite nodes database --- .gitignore | 3 + manage_nodes.py | 244 +++++++++++++++++++++++++++++++++++ node_db.py | 256 +++++++++++++++++++++++++++++++++++++ nodes.db | Bin 0 -> 12288 bytes nodes_example.csv | 11 ++ requirements.txt | 3 +- tg_meshtastic_forwarder.py | 48 +++++-- view_nodes.py | 251 ++++++++++++++++++++++++++++++++++++ 8 files changed, 806 insertions(+), 10 deletions(-) create mode 100644 manage_nodes.py create mode 100644 node_db.py create mode 100644 nodes.db create mode 100644 nodes_example.csv create mode 100644 view_nodes.py diff --git a/.gitignore b/.gitignore index b7faf40..4fc71fb 100644 --- a/.gitignore +++ b/.gitignore @@ -140,6 +140,7 @@ celerybeat.pid .venv env/ venv/ +config.py ENV/ env.bak/ venv.bak/ @@ -205,3 +206,5 @@ cython_debug/ marimo/_static/ marimo/_lsp/ __marimo__/ + +subscribers.txt diff --git a/manage_nodes.py b/manage_nodes.py new file mode 100644 index 0000000..05d2ddf --- /dev/null +++ b/manage_nodes.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +""" +Script for manual management of nodes in the database +""" + +import argparse +from node_db import NodeDatabase +import sys + +def add_node(db_path, node_id, short_name=None, long_name=None, hw_model=None, role=None): + """Manually add or update a node""" + db = NodeDatabase(db_path) + + # Convert hex string to integer if needed + if isinstance(node_id, str): + if node_id.startswith('!'): + node_id = int(node_id[1:], 16) + else: + try: + node_id = int(node_id, 16) + except ValueError: + print(f"Error: Invalid node ID format. Use hex format (e.g., 12345678 or !12345678)") + return False + + success = db.update_node( + node_id=node_id, + short_name=short_name, + long_name=long_name, + hw_model=hw_model, + role=role + ) + + if success: + print(f"Successfully added/updated node {node_id:08x}") + print(f" Short name: {short_name or 'N/A'}") + print(f" Long name: {long_name or 'N/A'}") + print(f" HW Model: {hw_model or 'N/A'}") + print(f" Role: {role or 'N/A'}") + else: + print(f"Failed to add/update node {node_id:08x}") + + return success + +def delete_node(db_path, node_id): + """Delete a node from the database""" + import sqlite3 + + # Convert hex string to integer if needed + if isinstance(node_id, str): + if node_id.startswith('!'): + node_id = int(node_id[1:], 16) + else: + try: + node_id = int(node_id, 16) + except ValueError: + print(f"Error: Invalid node ID format. Use hex format (e.g., 12345678 or !12345678)") + return False + + try: + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + + # Check if node exists + cursor.execute('SELECT short_name, long_name FROM nodes WHERE node_id = ?', (node_id,)) + result = cursor.fetchone() + + if not result: + print(f"Node {node_id:08x} not found in database") + conn.close() + return False + + short_name, long_name = result + + # Delete the node + cursor.execute('DELETE FROM nodes WHERE node_id = ?', (node_id,)) + conn.commit() + conn.close() + + print(f"Deleted node {node_id:08x} ({short_name or long_name or 'unnamed'})") + return True + + except Exception as e: + print(f"Error deleting node: {e}") + return False + +def cleanup_old(db_path, days): + """Remove nodes not heard from in specified days""" + db = NodeDatabase(db_path) + deleted = db.cleanup_old_nodes(days) + + if deleted > 0: + print(f"Removed {deleted} node(s) not heard from in {days} days") + else: + print(f"No nodes older than {days} days found") + + return deleted > 0 + +def import_from_csv(db_path, csv_file): + """Import nodes from CSV file""" + import csv + + db = NodeDatabase(db_path) + imported = 0 + failed = 0 + + try: + with open(csv_file, 'r') as f: + reader = csv.DictReader(f) + + for row in reader: + try: + # Try to get node_id from different possible column names + node_id = None + for col in ['node_id', 'Node ID', 'id', 'ID']: + if col in row and row[col]: + try: + node_id = int(row[col]) + break + except ValueError: + # Try hex format + if row[col].startswith('!'): + node_id = int(row[col][1:], 16) + else: + node_id = int(row[col], 16) + break + + if not node_id: + print(f"Warning: Skipping row without valid node_id: {row}") + failed += 1 + continue + + # Get other fields + short_name = None + long_name = None + hw_model = None + role = None + + for col in ['short_name', 'Short Name', 'shortname']: + if col in row and row[col]: + short_name = row[col] + break + + for col in ['long_name', 'Long Name', 'longname', 'name']: + if col in row and row[col]: + long_name = row[col] + break + + for col in ['hw_model', 'HW Model', 'hardware', 'model']: + if col in row and row[col]: + hw_model = row[col] + break + + for col in ['role', 'Role']: + if col in row and row[col]: + role = row[col] + break + + # Update database + success = db.update_node( + node_id=node_id, + short_name=short_name, + long_name=long_name, + hw_model=hw_model, + role=role + ) + + if success: + imported += 1 + print(f"Imported: {node_id:08x} - {short_name or long_name or 'unnamed'}") + else: + failed += 1 + print(f"Failed to import: {node_id:08x}") + + except Exception as e: + print(f"Error processing row: {e}") + failed += 1 + + print(f"\nImport complete: {imported} successful, {failed} failed") + return imported > 0 + + except FileNotFoundError: + print(f"Error: File '{csv_file}' not found") + return False + except Exception as e: + print(f"Error importing CSV: {e}") + return False + +def main(): + parser = argparse.ArgumentParser(description='Manage Meshtastic nodes database') + parser.add_argument('--db', default='nodes.db', help='Database file path (default: nodes.db)') + + subparsers = parser.add_subparsers(dest='command', help='Commands') + + # Add node command + add_parser = subparsers.add_parser('add', help='Add or update a node') + add_parser.add_argument('node_id', help='Node ID (hex format, e.g., 12345678 or !12345678)') + add_parser.add_argument('--short', help='Short name') + add_parser.add_argument('--long', help='Long name') + add_parser.add_argument('--hw', help='Hardware model') + add_parser.add_argument('--role', help='Node role') + + # Delete node command + del_parser = subparsers.add_parser('delete', help='Delete a node') + del_parser.add_argument('node_id', help='Node ID to delete') + + # Cleanup command + cleanup_parser = subparsers.add_parser('cleanup', help='Remove old nodes') + cleanup_parser.add_argument('--days', type=int, default=30, help='Remove nodes older than N days (default: 30)') + + # Import command + import_parser = subparsers.add_parser('import', help='Import nodes from CSV') + import_parser.add_argument('csv_file', help='CSV file to import') + + args = parser.parse_args() + + if args.command == 'add': + success = add_node( + args.db, + args.node_id, + args.short, + args.long, + args.hw, + args.role + ) + sys.exit(0 if success else 1) + + elif args.command == 'delete': + success = delete_node(args.db, args.node_id) + sys.exit(0 if success else 1) + + elif args.command == 'cleanup': + success = cleanup_old(args.db, args.days) + sys.exit(0 if success else 1) + + elif args.command == 'import': + success = import_from_csv(args.db, args.csv_file) + sys.exit(0 if success else 1) + + else: + parser.print_help() + sys.exit(1) + +if __name__ == "__main__": + main() diff --git a/node_db.py b/node_db.py new file mode 100644 index 0000000..f0ee01d --- /dev/null +++ b/node_db.py @@ -0,0 +1,256 @@ +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 + } diff --git a/nodes.db b/nodes.db new file mode 100644 index 0000000000000000000000000000000000000000..c3778591f92f427ab314c30b7ff8adcf2f884e8d GIT binary patch literal 12288 zcmeI#u}Z^07zgmXG*v9v6hty92VGi_BGkc6s|Kmos%gM>3eiLpNRyIAthfn|qR-&$ z1NZ>GgOA|qrlZ$3fvU02mH$V+%Z2;$CHLE|aaeOgi=FyG+Xz{i?+CL@&N$>2tWV=5P$##AOHafKmY<0CD0J2a-?Vhc?BBYnO;xFA3ai$)lqMTlW&3qDs3=6`#S9yX>kgfkWtrZrg~qXK z4JrqN5H-{)8#QIvffc^I8h45M@=t5ZwxY5FwYpbPTWnWpEhWCtwf!K}J)>{text}" - msg = f"{ts_str}\n{text_html}\n{from_id} to {to_id}\nRSSI: {rssi}\nHop(s): {hop_start}, away: {hops_away}" + msg = f"{ts_str}\n{text_html}\n{from_name} to {to_name}\nRSSI: {rssi}\nHop(s): {hop_start}, away: {hops_away}" return msg, 'HTML' except Exception as e: logging.warning(f"Protobuf parsing error: {e}") @@ -124,11 +159,6 @@ def on_mqtt_message(client, userdata, msg): logging.info(f"MQTT received: id={log_id}, from={log_from}, to={log_to}, portnum={log_portnum}, len={len(msg.payload)}") except Exception as e: logging.warning(f"Failed to log MQTT message meta: {e}") - # Filter: only forward broadcast messages - to_id = getattr(packet, 'to', None) - if to_id != 4294967295: - logging.info(f"MQTT message id={getattr(packet, 'id', None)} not sent: not broadcast (to={to_id})") - return # Check for duplicate by id packet_id = packet.id if hasattr(packet, 'id') else None if packet_id is not None and is_duplicate(packet_id): @@ -157,7 +187,7 @@ def on_mqtt_message(client, userdata, msg): if text: message_queue.put((text, parse_mode)) else: - logging.info(f"MQTT message id={getattr(packet, 'id', None)} not sent: not a text message or failed to format.") + logging.info(f"MQTT message id={packet_id} not sent: not a text message or failed to format.") except Exception as e: logging.warning(f"ServiceEnvelope parsing error: {e}") logging.info(f"MQTT message not sent: ServiceEnvelope parsing error.") @@ -232,4 +262,4 @@ def main(): app.run_polling() if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/view_nodes.py b/view_nodes.py new file mode 100644 index 0000000..1802b8d --- /dev/null +++ b/view_nodes.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +""" +Script to view and manage the nodes database +""" + +import sqlite3 +import argparse +from datetime import datetime +from tabulate import tabulate +import sys + +def format_timestamp(timestamp): + """Convert timestamp to human-readable format""" + if timestamp: + return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') + return "N/A" + +def format_node_id(node_id): + """Format node ID as hex string (Meshtastic convention)""" + return f"!{node_id:08x}" + +def view_all_nodes(db_path="nodes.db", sort_by="last_heard"): + """Display all nodes in the database""" + try: + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + + # Get all nodes + query = f''' + SELECT node_id, short_name, long_name, hw_model, role, + last_heard, created_at, updated_at + FROM nodes + ORDER BY {sort_by} DESC + ''' + cursor.execute(query) + results = cursor.fetchall() + conn.close() + + if not results: + print("No nodes found in the database.") + return + + # Prepare data for tabulate + headers = ["Node ID", "Short Name", "Long Name", "HW Model", "Role", "Last Heard", "Created", "Updated"] + table_data = [] + + for row in results: + table_data.append([ + format_node_id(row[0]), + row[1] or "-", + row[2] or "-", + row[3] or "-", + row[4] or "-", + format_timestamp(row[5]), + format_timestamp(row[6]), + format_timestamp(row[7]) + ]) + + print(f"\n=== Total nodes: {len(results)} ===\n") + print(tabulate(table_data, headers=headers, tablefmt="grid")) + + except Exception as e: + print(f"Error reading database: {e}") + sys.exit(1) + +def view_statistics(db_path="nodes.db"): + """Display database statistics""" + try: + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + + # Total nodes + 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] + + # Nodes heard in last 30 days + cutoff_30d = int(datetime.now().timestamp()) - (30 * 24 * 60 * 60) + cursor.execute('SELECT COUNT(*) FROM nodes WHERE last_heard > ?', (cutoff_30d,)) + active_30d = cursor.fetchone()[0] + + # Nodes with names + cursor.execute('SELECT COUNT(*) FROM nodes WHERE short_name IS NOT NULL OR long_name IS NOT NULL') + named_nodes = cursor.fetchone()[0] + + conn.close() + + print("\n=== Node Database Statistics ===\n") + print(f"Total nodes: {total_nodes}") + print(f"Named nodes: {named_nodes}") + print(f"Active (24 hours): {active_24h}") + print(f"Active (7 days): {active_7d}") + print(f"Active (30 days): {active_30d}") + print(f"Inactive (>30 days): {total_nodes - active_30d}") + + except Exception as e: + print(f"Error getting statistics: {e}") + sys.exit(1) + +def search_node(db_path="nodes.db", search_term=""): + """Search for nodes by ID or name""" + try: + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + + # Try to parse as hex ID + node_id = None + if search_term.startswith('!'): + try: + node_id = int(search_term[1:], 16) + except ValueError: + pass + + if node_id: + # Search by exact node ID + 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,)) + else: + # Search by name (partial match) + search_pattern = f'%{search_term}%' + cursor.execute(''' + SELECT node_id, short_name, long_name, hw_model, role, + last_heard, created_at, updated_at + FROM nodes + WHERE short_name LIKE ? OR long_name LIKE ? + ORDER BY last_heard DESC + ''', (search_pattern, search_pattern)) + + results = cursor.fetchall() + conn.close() + + if not results: + print(f"No nodes found matching '{search_term}'") + return + + # Display results + headers = ["Node ID", "Short Name", "Long Name", "HW Model", "Role", "Last Heard", "Created", "Updated"] + table_data = [] + + for row in results: + table_data.append([ + format_node_id(row[0]), + row[1] or "-", + row[2] or "-", + row[3] or "-", + row[4] or "-", + format_timestamp(row[5]), + format_timestamp(row[6]), + format_timestamp(row[7]) + ]) + + print(f"\n=== Found {len(results)} node(s) ===\n") + print(tabulate(table_data, headers=headers, tablefmt="grid")) + + except Exception as e: + print(f"Error searching database: {e}") + sys.exit(1) + +def export_csv(db_path="nodes.db", output_file="nodes_export.csv"): + """Export database to CSV file""" + try: + import csv + + conn = sqlite3.connect(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() + + with open(output_file, 'w', newline='') as csvfile: + writer = csv.writer(csvfile) + writer.writerow(['Node ID', 'Node ID (Hex)', 'Short Name', 'Long Name', + 'HW Model', 'Role', 'Last Heard', 'Created', 'Updated']) + + for row in results: + writer.writerow([ + row[0], + format_node_id(row[0]), + row[1] or "", + row[2] or "", + row[3] or "", + row[4] or "", + format_timestamp(row[5]), + format_timestamp(row[6]), + format_timestamp(row[7]) + ]) + + print(f"Exported {len(results)} nodes to {output_file}") + + except Exception as e: + print(f"Error exporting to CSV: {e}") + sys.exit(1) + +def main(): + parser = argparse.ArgumentParser(description='View and manage Meshtastic nodes database') + parser.add_argument('--db', default='nodes.db', help='Database file path (default: nodes.db)') + + subparsers = parser.add_subparsers(dest='command', help='Commands') + + # List command + list_parser = subparsers.add_parser('list', help='List all nodes') + list_parser.add_argument('--sort', choices=['last_heard', 'created_at', 'short_name', 'node_id'], + default='last_heard', help='Sort by field') + + # Stats command + stats_parser = subparsers.add_parser('stats', help='Show database statistics') + + # Search command + search_parser = subparsers.add_parser('search', help='Search for nodes') + search_parser.add_argument('term', help='Search term (name or !nodeID)') + + # Export command + export_parser = subparsers.add_parser('export', help='Export to CSV') + export_parser.add_argument('--output', default='nodes_export.csv', help='Output CSV file') + + args = parser.parse_args() + + if args.command == 'list': + view_all_nodes(args.db, args.sort) + elif args.command == 'stats': + view_statistics(args.db) + elif args.command == 'search': + search_node(args.db, args.term) + elif args.command == 'export': + export_csv(args.db, args.output) + else: + # Default action: show all nodes + view_all_nodes(args.db) + print("\n") + view_statistics(args.db) + print("\nUse --help to see available commands") + +if __name__ == "__main__": + main()