# Project

Created with RDM

## 📁 File: meshtastic_dashboard.py

---

### 📋 **Purpose**
This file implements a **Meshtastic Dashboard** web application using FastAPI. It serves as a comprehensive interface for interacting with Meshtastic radio devices, providing:
- **Real-time monitoring** of mesh network packets, nodes, positions, and telemetry.
- **User authentication** and role-based access control.
- **Configuration management** for both the dashboard and Meshtastic device connections.
- **Initial setup flow** for first-time users.
- **Integration with external APIs** (e.g., community maps, version checks).
- **Background tasks** for periodic data processing (e.g., stats, pruning, auto-replies).
- **SSE (Server-Sent Events)** for live updates to the frontend.
- **RESTful API** for frontend interaction and external integrations.

The dashboard supports multiple connection types (serial, TCP, BLE) and provides a user-friendly web interface for managing and visualizing mesh network data.

---

### 🏗️ **Structure**

#### **1. Imports & Configuration (Lines 0–129)**
- Standard library and third-party imports (FastAPI, Meshtastic, SQLite, JWT, etc.).
- **Dynamic Pydantic version handling** (V1/V2 compatibility).
- **Optional module imports** (tasks, auto-reply, system config) with graceful fallbacks.
- **Default configuration values** (connection, web server, database, auth, privacy).
- **File paths** for static assets (HTML, JS, CSS, favicon).

#### **2. Configuration Loading (`load_configuration` function, Lines 129–218)**
- Loads settings from a `.mesh-dash_config` file.
- Supports **type-safe parsing** (booleans, integers, floats, strings).
- Falls back to defaults if the config file is missing or malformed.

#### **3. Database Management (`DatabaseManager` class, Lines 352–570)**
- **SQLite-based data storage** for packets, nodes, messages, positions, telemetry, and metrics.
- **Schema initialization** (tables for packets, nodes, messages, positions, telemetry, users, etc.).
- **CRUD operations** for saving packets, nodes, and querying historical data.
- **Metrics calculation** (average SNR, RSSI, node counts).

#### **4. Global State (`MeshtasticData` class, Lines 575–796)**
- **In-memory state** for packets, nodes, connection status, and statistics.
- **Packet processing** (normalization, classification, stats tracking).
- **Node management** (updates, local node info, channel mapping).
- **SSE broadcasting** for real-time updates.

#### **5. Authentication & Security (Lines 259–348, 895–904)**
- **User model** (`User`, `TokenData`).
- **Password hashing** (bcrypt).
- **JWT-based authentication** (token creation, verification).
- **Dependency injection** for protected routes (`get_current_active_user`).
- **Serializable data conversion** (`ensure_serializable` function).

#### **6. Callbacks & Helpers (Lines 822–894)**
- **Meshtastic event callbacks** (`on_receive`, `on_connection`, `on_node_updated`).
- **SSE broadcasting** (`broadcast_data`, `broadcast_stats`).
- **Periodic tasks** (`update_stats_periodically`, `prune_history_periodically`).
- **Auto-reply logic** (integration with `auto_reply` module).

#### **7. FastAPI Lifespan & Initialization (Lines 905–991)**
- **Lifespan management** for background tasks, connection manager, and cleanup.
- **Initial admin user creation** (from config file).
- **Database initialization** (tasks, auto-reply).
- **Connection manager setup** (`MeshtasticConnectionManager`).
- **Network analyzer integration** (optional).

#### **8. API Routes (Lines 995–1870)**
- **Static file serving** (HTML, JS, CSS).
- **Authentication routes** (`/login`, `/logout`).
- **Dashboard pages** (`/`, `/map`, `/dmes`, `/settings`, `/channels`, etc.).
- **API endpoints** for:
  - Status, stats, nodes, packets, messages, metrics.
  - Sending messages, monitoring websites, extracting text.
  - System actions (restart, config management, setup).
- **SSE endpoint** (`/sse`) for real-time updates.
- **Proxy routes** for external APIs (version check, community maps).

#### **9. Setup & Configuration APIs (Lines 1405–1850)**
- **Initial setup** (`/api/system/config/initial-setup`):
  - Creates the first admin user.
  - Writes the initial config file.
  - Updates global variables in memory (hot reload).
  - Deletes the `.new` file to finalize setup.
- **Config management** (`/api/system/config`, `/api/system/config/update`):
  - Loads and updates configuration settings.
  - Supports hot reloading of critical settings (e.g., auth, connection).

#### **10. Main Entry Point (Lines 1859–1869)**
- **Argument parsing** (port, host, db-path, log-level).
- **Uvicorn server startup**.

---

### 🚀 **Usage**

#### **1. Running the Dashboard**
```bash
python meshtastic_dashboard.py --port 8000 --host 0.0.0.0 --db-path meshtastic_data.db --log-level INFO
```

#### **2. Accessing the Dashboard**
- Open `http://<host>:<port>` in a web browser.
- **First-time setup**: Redirects to `/setup` if no users exist.
- **Login**: Authenticate with admin credentials (created during setup).

#### **3. Key Features**
- **Real-time monitoring**: View packets, nodes, and telemetry via SSE.
- **Message sending**: Send text messages to nodes or channels.
- **Configuration**: Adjust settings via the web UI (hot reload supported).
- **Community integration**: Share node locations with external maps (if enabled).
- **Auto-reply**: Configure automated responses to messages (if enabled).
- **Tasks**: Schedule periodic actions (if enabled).

#### **4. API Examples**
- **Get nodes**: `GET /api/nodes`
- **Send message**: `POST /api/messages` (with JSON payload)
- **Get stats**: `GET /api/stats`
- **Update config**: `POST /api/system/config/update` (with JSON payload)
- **Real-time updates**: Connect to `/sse` via EventSource.

#### **5. Configuration File**
- Default location: `.mesh-dash_config` in the script directory.
- Example:
  ```ini
  MESHTASTIC_HOST=192.168.1.100
  MESHTASTIC_PORT=4403
  WEBSERVER_PORT=8000
  AUTH_SECRET_KEY=my_very_secret_key
  COMMUNITY_API=True
  COMMUNITY_API_KEY=my_api_key
  ```

---
