252 lines
8.3 KiB
Python
252 lines
8.3 KiB
Python
#!/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()
|