Compare commits

..
24 Commits
Author SHA1 Message Date
iv3jdv 93fc177911 feat(release): v6.0.0 - Major C2 platform evolution
- Calendar Profile Scheduler: pianificazione temporizzata con switch automatico e rollback del profilo a fine evento
- Tactical APRS Map: tracciamento stazioni in mobilità, filtro dei nodi di flotta e garbage collection dopo 2h
- Dynamic Timeframe Analytics: filtri temporali 12H, 24H, 48H, 7D sui grafici Chart.js con etichette intelligenti
- Time Machine & Visual Diff: storico backup configurazioni .ini con visualizzatore differenze semantico
- Header UX Refactor: riorganizzazione a tre righe compatte con integrazione badge operatori online in tempo reale
- Complete i18n: allineamento del dizionario bilingue (IT/EN) su tutta la piattaforma
2026-11-08 15:27:42 +01:00
iv3jdv c7c95d877c fix 2026-11-07 10:46:39 +01:00
iv3jdv a06e5cd7b7 update README.md 2026-11-03 20:33:16 +01:00
iv3jdv e7bbd080b0 Release v5.3.7: Implementato bypass cache per check aggiornamenti 2026-11-03 20:02:33 +01:00
iv3jdv 019e518534 Release v5.3.6: Strict RBAC e separazione permessi Admin/Nodi 2026-11-03 19:45:38 +01:00
iv3jdv e199fb8f29 Release v5.3.4: Ripristino permessi Global Override per Operator 2026-11-03 18:30:17 +01:00
iv3jdv 43e0e77790 Release v5.3.3: Sync fix per il controllo aggiornamenti backend 2026-11-03 18:14:57 +01:00
iv3jdv 1bb1c2cc99 Release v5.3.2: Fix propagazione Service Alerts e completamento UI i18n 2026-11-03 17:56:10 +01:00
iv3jdv 5fabe68944 Release v5.3.1: Hotfix API server update e prevenzione SyntaxError JSON 2026-11-03 16:56:34 +01:00
iv3jdv 3064dc035f Release v5.3.0: The Borderless Executive Update ed espansione i18n 2026-11-03 16:47:02 +01:00
iv3jdv 8fc08f1c23 reaorganize home header 2026-11-03 15:04:19 +01:00
iv3jdv 66cd63a181 feat(ui,api): layout mini-card fisso, nominativo tx pulito, cache-busting index e check Gitea asincrono 2026-11-03 13:03:55 +01:00
iv3jdv 36def1e201 fix mini-card width v2 2026-11-02 22:52:27 +01:00
iv3jdv a6c24244bd fix mini-card width 2026-11-02 22:43:47 +01:00
iv3jdv 502dcc2f65 Restyling badge 2026-11-02 22:31:44 +01:00
iv3jdv d4e83364e2 add time/date 2026-11-02 22:01:51 +01:00
iv3jdv fa4b3d8df2 fix mode spacing 2026-11-01 20:09:40 +01:00
iv3jdv a67ddd582c feat(ui): aggiunto supporto per i modi FM e M17 nei toggle operativi 2026-11-01 18:57:06 +01:00
iv3jdv 7ee7b00b37 fix(ui): restyling chip gateway ad alto contrasto e parsing aprs raw 2026-11-01 14:28:25 +01:00
iv3jdv ebaefeeedf fix(aprs): parsing stringhe raw ax25 e mapping colonna path 2026-11-01 11:41:45 +01:00
iv3jdv 2e8b75c384 feat(ui): implementazione multi-layout (Blueprint, Tactical, Light, Glass) e fix visivi 2026-11-01 10:52:20 +01:00
iv3jdv a56da30330 restored interactive map 2026-11-01 09:42:44 +01:00
iv3jdv 9b7c76c801 fix(telemetry): allineamento stati hangtime e risoluzione falsi positivi sui beacon
- Backend (mqtt_service.py): Aggiunta logica per intercettare i pacchetti beacon in assenza di traffico voce. Il sistema ora pulisce la memoria dei modi alternativi (es. D-Star/YSF) se il beacon è DMR, prevenendo il blocco dell'interfaccia su un vecchio protocollo.
- Frontend (app.js): La memorizzazione del colore e del modo per la gestione dell'hangtime (Hold) ora scatta con la condizione `!isIdle` anziché solo con il PTT voce (`isTx`).
- I badge della dashboard Home ora mostrano coerentemente il protocollo corretto per tutta la durata dell'hangtime, sia dopo un passaggio voce che dopo un beacon di rete.
2026-11-01 09:31:40 +01:00
iv3jdv bf4a669446 fix badge color 2026-10-31 21:42:26 +01:00
15 changed files with 2248 additions and 412 deletions
+53 -180
View File
@@ -1,4 +1,4 @@
# 📡 Fleet Control Console - Server (Central Hub)
# 📡 Fleet Control Console - Server (Central Hub) v6.0.0
🌍 *[Read in English](#english) | 🇮🇹 [Leggi in Italiano](#italiano)*
@@ -14,58 +14,49 @@
> ℹ️ **Note:** This is the Central Server repository. To monitor remote repeaters, you must install the [Fleet Control Agent](https://git.arifvg.it/iv3jdv/fleet-node-agent.git) on each node.
### 🏗️ Architecture & Technology Stack
The server acts as the brain of the network, built on a highly scalable foundation (v5.0+):
The server acts as the brain of the network, built on a highly scalable foundation (v6.0.0):
* **Modular Backend:** Completely decoupled architecture (`core/`, `services/`, `routes/`) for high maintainability and robust background task handling.
* **Core Engine:** Flask (Python) with `gevent` for high-concurrency WebSocket handling.
* **Database:** SQLite (WAL mode) for robust User Management, Audit Logs, and Radio Traffic storage.
* **Database:** SQLite (WAL mode) for robust User Management, Audit Logs, Schedules, and Radio Traffic storage.
* **Communication:** MQTT for instant data routing + WebSockets (SocketIO) for zero-latency UI updates.
* **Frontend:** Vanilla JS with a modern *Glassmorphism* NOC (Network Operations Center) design and separated logic (`app.js`, `modals.js`).
* **Frontend:** Vanilla JS with a modern *Glassmorphism Borderless Executive* NOC (Network Operations Center) design. Full i18n (Internationalization) support for English and Italian.
### ✨ Ultimate Features
### ✨ Ultimate Features (v6.0.0)
#### 🛡️ Proactive Diagnostics (Watchdog)
* **Hardware Monitoring:** Continuous analysis of remote CPU temperatures and disk space saturation. Automatically triggers Push Notifications before critical failures (e.g., CPU throttling or log overflow) occur.
* **RF Anomaly Detection:** Real-time monitoring of local RF BER (Bit Error Rate). Detects hardware RF degradation on local transits and alerts admins instantly.
#### 🗓️ Calendar Profile Scheduler [NEW]
* Plan automated profile switches (e.g., Regional Nets, Contests, Civil Defense drills) across multiple nodes.
* Seamless background execution: the system automatically triggers the `Target Profile` at the specified start time and gracefully falls back to the `Restore Profile` once the event ends.
#### ⚡ Zero-Latency Real-Time Dashboard
* **WebSocket Powered:** The dashboard updates instantly upon radio traffic or telemetry changes. No heavy HTTP polling, no page reloads.
* **Live MQTT Status:** A real-time badge continuously monitors the connection to the MQTT broker, instantly alerting you if the backend loses connectivity.
* **PWA Ready v6:** Install the dashboard as a Progressive Web App on iOS/Android for a native, full-screen mobile experience with offline asset caching.
#### 🗺️ Tactical APRS Map [NEW]
* Real-time GIS map showing both your fixed repeater locations and **roaming APRS stations**.
* Automatically extracts and parses APRS payloads from gateway logs.
* Features a smart Garbage Collector that automatically cleans up roaming pins after 2 hours of inactivity.
#### 🔔 Web Push Notifications
* Get instant, native alerts directly on your desktop or mobile device when:
* A node goes offline or comes back online.
* A critical system daemon crashes (Auto-healing failed).
* The Watchdog detects thermal warnings, disk full alerts, or high RF BER.
* Works securely even when the web app is closed or in the background.
#### 🛠️ Advanced Remote Control & Visual Diff [NEW]
* **Time Machine Config Editor:** Edit daemon configuration files (e.g., MMDVMHost.ini) directly from the web interface, with the ability to rollback to previous historical backups.
* **Semantic Visual Diff:** Compare your local unsaved edits against the running config with a rich Green/Red semantic diff viewer before safely committing changes to the node.
* **OTA Server Updates:** Apply server-side Git updates directly from the admin dashboard without SSH access.
* **Service Management & Hardware:** Start/Stop/Restart remote daemons, trigger physical OS reboots, or hard GPIO resets of the MMDVM HAT.
#### 🛠️ Advanced Remote Control & Maintenance
* **OTA Server Updates:** Apply server-side Git updates with a single click directly from the admin dashboard (Over-The-Air) without SSH access.
* **Remote .INI Editor:** Edit daemon configuration files (e.g., MMDVMHost.ini) directly from the web interface.
* **Service Management:** Start, Stop, or Restart remote system daemons.
* **Global Overrides:** Switch profiles (e.g., Profile A/B) or force updates simultaneously on all nodes in the fleet.
* **Hardware Interventions:** Trigger a physical OS reboot or a hard GPIO reset of the MMDVM HAT directly from the web panel.
#### 📈 Dynamic Analytics & Monitoring [NEW]
* **Timeframe Analytics:** Interactive historical charts (Chart.js) for CPU/Temp and RF Transits/BER. Zoom dynamically across 12H, 24H, 48H, or 7D timeframes with smart axis labeling.
* **Live WebSocket Console:** Zero-latency terminal streams for node daemons. Real-time active operator tracking (see who is logged in and managing the dashboard).
* **Proactive Diagnostics (Watchdog):** Continuous analysis of remote CPU temperatures, disk space, and RF BER. Triggers automated Web Push Notifications.
#### 📊 Unified Monitoring & Statistics
* **Interactive Fleet Map:** Real-time GIS map showing repeater locations, online/offline status, active TX states (pulsing pins), and active watchdog warnings.
* **Live Heard Log:** A centralized view of radio traffic across the entire network, auto-resolving DMR and NXDN IDs into callsigns.
* **Software & Firmware Tracking:** Instantly view MMDVM firmware versions and Pi-Star/Gateway component versions for each node.
* **Daily Analytics:** Automatically tracks Top Talkgroups, Top Callsigns, Average duration, and daily transit counts.
#### 🔐 Security & Access Control
* **Role-Based Access Control (RBAC):** Create `admin` and `operator` accounts.
* **Granular Permissions:** Restrict operators to view/control only specific repeaters.
* **Audit Trail:** Every critical action (reboots, config edits, daemon restarts) is logged with the username, timestamp, and target node.
#### 🔐 Strict Security & Access Control
* **Role-Based Access Control (RBAC):** True Zero-Trust architecture. Node management is bound to explicitly assigned nodes (`allowed_nodes`) for both *Operators* and *Node Admins*.
* **System Administration:** Admins retain exclusive rights to global server settings, schedules, and user management.
* **Security Audit Trail:** Every critical action (reboots, config edits, schedules) is securely logged with username, timestamp, and target node.
### ⚠️ Security Requirement: HTTPS
Please note that **Web Push Notifications** and the **Service Worker** require a secure connection to function. For security reasons, modern browsers only enable these features over **HTTPS**. If you are accessing the console via HTTP (outside of `localhost`), the "Push" button and notification registration will not work. We recommend using a reverse proxy (like Nginx, Caddy, or Traefik) with an SSL certificate.
**Web Push Notifications** and the **Service Worker** require a secure connection. Modern browsers only enable these features over **HTTPS**. We recommend using a reverse proxy (like Nginx, Caddy, or Apache) with an SSL certificate.
### ⚠️ Reverse Proxy & WebSocket Configuration
If you expose the Fleet Console through a reverse proxy like **Apache** on a public IP (HTTPS), standard HTTP proxying will drop Socket.IO real-time connections. You must enable the WebSocket tunnel in Apache:
If using a reverse proxy like **Apache** on HTTPS, you must enable WebSocket tunneling:
```bash
sudo a2enmod proxy_wstunnel rewrite headers
```
And insert the **Rewrite** rules *before* the `ProxyPass` directives inside your `<VirtualHost *:443>` block:
Insert the **Rewrite** rules *before* the `ProxyPass` directives in your `<VirtualHost *:443>`:
```apache
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
@@ -80,164 +71,46 @@ ProxyPass / http://127.0.0.1:9000/
ProxyPassReverse / http://127.0.0.1:9000/
```
### 🚀 Installation Guide
#### 0. Root Privileges
All installation steps must be executed as the `root` user.
```bash
apt update
apt install build-essential python3-dev libssl-dev libffi-dev python3-pip python3-venv
```
#### 1. Clone Repository
Clone the repository into the /opt directory to ensure all systemd paths work correctly:
```bash
git clone https://git.arifvg.it/iv3jdv/fleet-control-server.git /opt/fleet-control-server
cd /opt/fleet-control-server
```
#### 2. Virtual Environment Setup (Recommended)
To prevent conflicts with OS packages (PEP 668), create an isolated environment:
```bash
cd /opt/fleet-control-server
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip setuptools wheel
pip install -r requirements.txt
```
#### 3. Configuration
1. Copy `config.example.json` to `config.json`.
2. Configure your MQTT broker credentials.
3. Define your repeaters in `clients.json`.
4. Generate VAPID keys at [vapidkeys.com](https://vapidkeys.com/) and add them to `config.json` to enable Web Push notifications. *(Note: Push notifications require HTTPS).*
5. Configure dynamic log rotation sizes (`log_max_mb` and `log_backup_count`) directly in `config.json` to manage disk space.
#### 4. Running as a Service
To run the server continuously in production using Gunicorn:
```bash
cp fleet-console.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable fleet-console
systemctl start fleet-console
```
*(Ensure the `.service` file points to the `gunicorn` executable inside your `venv`)*.
---
<a name="italiano"></a>
## 🇮🇹 Italiano
**Fleet Control Console** è una dashboard di comando e controllo (C2) professionale in tempo reale, progettata per le reti di ripetitori radioamatoriali (MMDVM). Questo repository contiene il **Server (Central Hub)**, che fornisce un'interfaccia web centralizzata per monitorare e gestire una flotta di nodi digitali remoti (DMR, NXDN, YSF, P25).
**Fleet Control Console** è una dashboard di comando e controllo (C2) professionale in tempo reale, progettata per le reti di ripetitori radioamatoriali (MMDVM). Questo repository contiene il **Server (Central Hub)**, che fornisce un'interfaccia web centralizzata per monitorare e gestire una flotta di nodi digitali remoti.
> ℹ️ **Nota:** Questo è il repository del Server Centrale. Per monitorare i ripetitori, devi installare il [Fleet Control Agent](https://git.arifvg.it/iv3jdv/fleet-node-agent.git) su ciascun nodo remoto.
### 🏗️ Architettura e Tecnologie
Il server agisce da cervello della rete, basato su fondamenta altamente scalabili (v5.0+):
* **Backend Modulare:** Architettura completamente disaccoppiata (`core/`, `services/`, `routes/`) per un'elevata manutenibilità e gestione robusta dei task in background.
### 🏗️ Architettura e Tecnologie (v6.0.0)
* **Backend Modulare:** Architettura completamente disaccoppiata (`core/`, `services/`, `routes/`) per un'elevata manutenibilità e gestione asincrona.
* **Motore Core:** Flask (Python) con `gevent` per la gestione ad alta concorrenza dei WebSocket.
* **Database:** SQLite (in modalità WAL) per gestire in sicurezza Utenti, Log operativi e traffico radio.
* **Comunicazione:** MQTT per il routing istantaneo dei dati + WebSockets (SocketIO) per aggiornare la UI a latenza zero.
* **Frontend:** Vanilla JS con un moderno design *Glassmorphism* in stile NOC (Network Operations Center) e logica completamente separata (`app.js`, `modals.js`).
* **Database:** SQLite (in modalità WAL) per gestire Utenti, Log Sicurezza, Schedulazioni e traffico radio.
* **Frontend Bilingue:** Vanilla JS con layout *Borderless Executive* in stile NOC. Traduzioni dinamiche (Inglese/Italiano) attivabili in tempo reale.
### ✨ Funzionalità Principali
### ✨ Funzionalità Principali v6.0.0
#### 🛡️ Diagnostica Proattiva (Watchdog)
* **Monitoraggio Hardware:** Analisi continua delle temperature CPU e della saturazione disco da remoto. Innesca automaticamente notifiche Push prima che si verifichino guasti critici (es. thermal throttling o blocco log MMDVM).
* **Rilevamento Anomalie RF:** Monitoraggio in tempo reale del BER (Bit Error Rate) sul traffico RF locale. Rileva il degrado hardware in radiofrequenza avvisando istantaneamente gli amministratori.
#### 🗓️ Calendario Pianificazione Profili [NUOVO]
* Schedula i cambi di profilo automatici (es. Net Regionali, Contest, Esercitazioni) su nodi multipli.
* Esecuzione in background: il sistema innesca il `Profilo Target` all'orario di inizio e ripristina automaticamente il `Profilo di Ritorno` alla scadenza della finestra temporale.
#### ⚡ Dashboard Real-Time a Latenza Zero
* **Motore WebSocket:** La dashboard scatta all'istante al passaggio di traffico radio o ai cambi di telemetria. Nessun polling HTTP pesante, nessun refresh della pagina.
* **Stato MQTT Live:** Un badge in tempo reale monitora continuamente la connessione al broker MQTT, avvisandoti istantaneamente in caso di problemi di rete.
* **PWA Ready v6:** Installabile su smartphone Android e iOS come Progressive Web App per un'esperienza nativa a schermo intero con cache offline intelligente.
#### 🗺️ Mappa Tattica APRS [NUOVO]
* Mappa GIS in tempo reale che mostra sia i ripetitori fissi che i **passanti APRS in mobilità**.
* Intercetta e formatta istantaneamente i payload APRS dai log dei gateway.
* Include un sistema di pulizia automatica (Garbage Collector) che rimuove i pin mobili dopo 2 ore di inattività.
#### 🔔 Notifiche Web Push
* Ricevi avvisi nativi e immediati su PC o smartphone quando:
* Un nodo va offline o torna operativo.
* Un demone di sistema remoto si blocca (fallimento auto-healing).
* Il Watchdog rileva allarmi termici, disco pieno o anomalie BER.
* Funzionano in modo sicuro anche quando la web app è chiusa o in background.
#### 🛠️ Editor Avanzato & Visual Diff [NUOVO]
* **Editor Config .INI "Macchina del Tempo":** Modifica i file operativi direttamente dal pannello web, con possibilità di ripristinare i backup storici salvati automaticamente nel database.
* **Visual Diff Semantico:** Controlla visivamente le differenze (in verde le aggiunte, in rosso le rimozioni) tra le tue modifiche in bozza e la configurazione attualmente in esecuzione prima di salvare.
* **Interventi Hardware & Servizi:** Avvia/arresta demoni, forza il riavvio del SO o esegui un reset hardware GPIO sulla scheda MMDVM.
#### 🛠️ Controllo Remoto & Manutenzione Avanzata
* **Aggiornamenti Server OTA:** Applica gli aggiornamenti del server tramite Git direttamente dalla dashboard di amministrazione (Over-The-Air) con un clic, senza usare SSH.
* **Editor .INI Remoto:** Modifica i file di configurazione (es. MMDVMHost.ini) direttamente dal pannello web.
* **Gestione Demoni:** Avvia, arresta o riavvia i servizi di sistema remoti.
* **Override Globali:** Cambia i profili operativi (es. Profilo A/B) simultaneamente su tutta la rete.
* **Interventi Hardware:** Innesca un riavvio del sistema operativo o un reset fisico (tramite pin GPIO) della scheda MMDVM.
#### 📊 Monitoraggio & Statistiche
* **Mappa Interattiva di Flotta:** Mappa GIS in tempo reale che mostra la posizione dei ripetitori, stato online/offline, trasmissione attiva (pin lampeggianti) e allarmi diagnostici in corso.
* **Log Ascolti Live:** Vista unificata in tempo reale del traffico radio di tutta la rete, con traduzione automatica degli ID DMR e NXDN in nominativi.
* **Tracciamento Versioni:** Controlla all'istante le versioni firmware MMDVM e software (Pi-Star/Gateway) a bordo di ciascun nodo.
* **Analisi Giornaliera:** Statistiche automatiche su Top Talkgroups, Top Callsign, durata media e numero totale di transiti.
#### 📈 Analitiche Dinamiche & Console Live [NUOVO]
* **Grafici Temporali:** Analizza l'andamento di CPU/Temp e Transiti/BER esplorando finestre temporali dinamiche da 12 Ore fino a 7 Giorni, con rendering fluido via Chart.js.
* **Console WebSocket:** Terminale a latenza zero per analizzare i log dei demoni.
* **Tracciamento Operatori:** Visualizza in tempo reale quali amministratori sono connessi e operativi sulla dashboard.
* **Watchdog Proattivo:** Analisi continua di surriscaldamenti e degrado RF, con avvisi inviati via notifiche Web Push.
#### 🔐 Sicurezza e Controllo Accessi
* **Gestione Ruoli (RBAC):** Creazione di account `admin` e `operator`.
* **Permessi Granulari:** Limita un operatore al controllo e alla visualizzazione di specifici ripetitori.
* **Audit Trail:** Ogni azione critica (riavvii, modifiche file, gestione demoni) viene registrata con data, ora, utente e nodo di destinazione.
* **Role-Based Access Control (RBAC):** Gestione nodi limitata esclusivamente ai ripetitori assegnati (`allowed_nodes`) per Operatori e `node_admin`.
* **Audit Trail di Sicurezza:** Ogni comando operativo e configurazione viene tracciato con timestamp, utente e obiettivo.
### ⚠️ Sicurezza Richiesta: HTTPS
Si prega di notare che le **Notifiche Web Push** e il **Service Worker** richiedono una connessione sicura per funzionare. Per motivi di sicurezza, i browser moderni abilitano queste funzionalità solo su **HTTPS**. Se accedi alla console via HTTP (al di fuori di `localhost`), il tasto "Push" e la registrazione delle notifiche non saranno attivi. Si consiglia l'uso di un reverse proxy (come Nginx, Caddy o Traefik) con certificato SSL.
### ⚠️ Configurazione Reverse Proxy & WebSocket
Se esponi la Fleet Console tramite un reverse proxy come **Apache** su IP pubblico (HTTPS), il proxy HTTP standard farà cadere continuamente la connessione in tempo reale di Socket.IO.
Devi abilitare il tunnel WebSocket in Apache:
```bash
sudo a2enmod proxy_wstunnel rewrite headers
```
E inserire le regole di **Rewrite** *prima* del `ProxyPass` all'interno del tuo blocco `<VirtualHost *:443>`:
```apache
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) ws://127.0.0.1:9000/$1 [P,L]
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
RewriteRule /(.*) http://127.0.0.1:9000/$1 [P,L]
ProxyPass /socket.io/ ws://127.0.0.1:9000/socket.io/
ProxyPassReverse /socket.io/ ws://127.0.0.1:9000/socket.io/
ProxyPass / http://127.0.0.1:9000/
ProxyPassReverse / http://127.0.0.1:9000/
```
### 🚀 Guida all'Installazione
#### 0. Privilegi di Root
Tutti i passaggi di installazione devono essere eseguiti come utente `root`.
```bash
apt update
apt install build-essential python3-dev libssl-dev libffi-dev python3-pip python3-venv
```
#### 1. Clonazione dei Repository
Clona il repository nella cartella /opt per assicurarti che tutti i percorsi dei servizi systemd siano corretti:
```bash
git clone https://git.arifvg.it/iv3jdv/fleet-control-server.git /opt/fleet-control-server
cd /opt/fleet-control-server
```
#### 2. Setup Ambiente Virtuale (Consigliato)
Per evitare conflitti con i pacchetti di sistema (regola PEP 668), crea una "bolla" isolata:
```bash
cd /opt/fleet-control-server
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip setuptools wheel
pip install -r requirements.txt
```
#### 3. Configurazione Base
1. Copia `config.example.json` in `config.json`.
2. Inserisci le credenziali del broker MQTT.
3. Definisci i ripetitori nel file `clients.json`.
4. Genera le chiavi VAPID su [vapidkeys.com](https://vapidkeys.com/) e inseriscile in `config.json` per attivare le notifiche Push. *(Attenzione: le notifiche Push richiedono obbligatoriamente un certificato HTTPS).*
5. Configura le dimensioni della rotazione dei log (`log_max_mb` e `log_backup_count`) direttamente nel `config.json` per gestire lo spazio su disco.
#### 4. Esecuzione come Servizio (systemd)
Per eseguire il server in produzione in modo continuo e stabile con Gunicorn:
```bash
cp fleet-console.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable fleet-console
systemctl start fleet-console
```
*(Assicurati che il file `.service` punti all'eseguibile `gunicorn` situato all'interno della cartella `venv`).*
---
*Created by IV3JDV @ ARIFVG - 2026*
Le **Notifiche Web Push** e il **Service Worker** richiedono obbligatoriamente una connessione HTTPS per funzionare. Si consiglia l'uso di un reverse proxy (come Apache o Nginx) con certificato SSL Let's Encrypt.
+21
View File
@@ -64,10 +64,31 @@ SERVER_COMMIT = get_git_commit()
def index():
return render_template('index.html', git_commit=SERVER_COMMIT)
from flask import session
@state.socketio.on('connect')
def handle_connect():
state.connected_web_clients.add(request.sid)
# Se l'utente è loggato (session), associamo il suo username al SID
user = session.get('user')
if user:
state.active_logged_users[request.sid] = user
emit('mqtt_status', {'connected': mqtt_svc.mqtt_connected_status})
# Prepariamo la lista unica degli utenti loggati attivi (togliendo i duplicati se un utente ha più tab aperti)
logged_names = list(set(state.active_logged_users.values()))
state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
@state.socketio.on('disconnect')
def handle_disconnect():
state.connected_web_clients.discard(request.sid)
state.active_logged_users.pop(request.sid, None)
logged_names = list(set(state.active_logged_users.values()))
state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
# --- INIZIALIZZAZIONE SISTEMA & THREAD ---
init_db()
state.seed_last_seen()
+27
View File
@@ -51,6 +51,24 @@ def init_db():
(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, username TEXT,
client_id TEXT, command TEXT)''')
c.execute('''CREATE TABLE IF NOT EXISTS config_backups
(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, client_id TEXT,
service TEXT, config_text TEXT, username TEXT)''')
c.execute('''CREATE TABLE IF NOT EXISTS telemetry_logs
(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, client_id TEXT,
cpu REAL, temp REAL, ram REAL, disk REAL)''')
c.execute("CREATE INDEX IF NOT EXISTS idx_telemetry_logs_client_ts ON telemetry_logs(client_id, timestamp)")
c.execute('''CREATE TABLE IF NOT EXISTS profile_schedules
(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, target_nodes TEXT,
target_profile TEXT, restore_profile TEXT, start_time DATETIME,
end_time DATETIME, status TEXT DEFAULT 'SCHEDULED', created_by TEXT,
created_at DATETIME DEFAULT (datetime('now', 'localtime')))''')
c.execute("CREATE INDEX IF NOT EXISTS idx_sched_status_time ON profile_schedules(status, start_time, end_time)")
c.execute("CREATE INDEX IF NOT EXISTS idx_radio_logs_ts ON radio_logs(timestamp)")
c.execute("CREATE INDEX IF NOT EXISTS idx_radio_logs_client_ts ON radio_logs(client_id, timestamp)")
c.execute("CREATE INDEX IF NOT EXISTS idx_audit_logs_ts ON audit_logs(timestamp)")
@@ -120,3 +138,12 @@ def prune_old_data():
logger.info(f"🧹 Pulizia DB: {n1} ascolti e {n2} audit rimossi.")
except Exception as e:
logger.error(f"❌ Errore pulizia DB: {e}")
def save_telemetry_to_sqlite(client_id, health_data):
try:
with closing(db_connect()) as conn:
conn.execute("INSERT INTO telemetry_logs (timestamp, client_id, cpu, temp, ram, disk) VALUES (datetime('now', 'localtime'), ?, ?, ?, ?, ?)",
(client_id, health_data.get('cpu', 0), health_data.get('temp', 0), health_data.get('ram', 0), health_data.get('disk', 0)))
conn.commit()
except Exception as e:
logger.error(f"Errore salvataggio telemetria: {e}")
+3
View File
@@ -48,6 +48,9 @@ gateway_states = {}
active_warnings = {}
active_calls = {}
operating_modes = {}
node_logs = {} # In-memory circular buffer for live logs
connected_web_clients = set()
active_logged_users = {}
# Caricamento iniziale cache telemetria
if os.path.exists(CACHE_FILE):
+2 -2
View File
@@ -1,5 +1,5 @@
============================================================
INSTALLATION GUIDE - FLEET CONTROL CONSOLE (SERVER)
INSTALLATION GUIDE - FLEET CONTROL CONSOLE (v6.0.0)
============================================================
------------------------------------------------------------
@@ -74,7 +74,7 @@ Configuration:
4. Start service: systemctl start fleet-console
============================================================
GUIDA ALL'INSTALLAZIONE - SERVER (ITALIANO)
GUIDA ALL'INSTALLAZIONE - SERVER v6.0.0 (ITALIANO)
============================================================
------------------------------------------------------------
+310 -15
View File
@@ -15,6 +15,10 @@ from services.mqtt_service import mqtt_publish
from services.push_service import node_allowed
from routes.auth_routes import get_auth, json_body, err
# --- AGGIUNTE PER GITEA BACKGROUND CHECK ---
GLOBAL_SERVER_UPDATE_AVAILABLE = False
LAST_GITEA_CHECK_TIME = 0
api_bp = Blueprint('api', __name__)
# --- REGEX & COSTANTI COMANDI ---
@@ -105,7 +109,9 @@ def get_states():
"versions": clean_versions,
"gateway_states": enriched_gateway_states,
"warnings": state.active_warnings,
"modes": getattr(state, "operating_modes", {})
"modes": getattr(state, "operating_modes", {}),
"web_users": len(getattr(state, "connected_web_clients", [])),
"logged_users": list(set(getattr(state, "active_logged_users", {}).values()))
})
@api_bp.route('/api/stats')
@@ -129,6 +135,7 @@ def get_stats():
c.execute(f"""SELECT source_id, COUNT(*) as cnt FROM radio_logs
WHERE source_id NOT LIKE '🌐%'
AND source_id NOT LIKE '%'
AND timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}
GROUP BY source_id ORDER BY cnt DESC LIMIT 5""", params)
top_calls = [{"call": row[0], "count": row[1]} for row in c.fetchall()]
@@ -181,8 +188,9 @@ def cmd():
if not mqtt_publish(f"servizi/{cid}/cmnd", cmd_type):
return err("Broker MQTT non raggiungibile - comando non inviato", 503)
audit(auth['username'], cid, cmd_type)
state.client_telemetry[cid] = {"ts1": "🔄 Inviato...", "ts2": "🔄 Inviato...", "alt": ""}
audit_label = f"SWITCH_PROFILE_{cmd_type.upper()}" if cmd_type in known_profile_keys(cid) else cmd_type
audit(auth['username'], cid, audit_label)
state.client_telemetry[cid] = {"ts1": "[>] Inviato...", "ts2": "[>] Inviato...", "alt": ""}
return jsonify({"success": True})
@api_bp.route('/api/global_command', methods=['POST'])
@@ -217,11 +225,14 @@ def global_cmd():
@api_bp.route('/api/service_control', methods=['POST'])
def service_control():
auth = get_auth()
if not auth or auth['role'] != 'admin':
if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'):
return err("Non autorizzato", 403)
d = json_body()
cid = str(d.get('clientId', '')).strip().lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
action = str(d.get('action', '')).strip().lower()
service = str(d.get('service', '')).strip()
if not CID_RE.match(cid):
@@ -243,7 +254,7 @@ def update_nodes():
return err("Non autorizzato", 403)
if not mqtt_publish("devices/control/request", "update"):
return err("Broker MQTT non raggiungibile", 503)
logger.info(f"📢 REQ CONFIG inviata a tutta la flotta da {auth['username']}")
logger.info(f"討 REQ CONFIG inviata a tutta la flotta da {auth['username']}")
audit(auth['username'], '*', 'REQ_CONFIG_ALL')
return jsonify({"success": True})
@@ -316,9 +327,11 @@ def save_config_api():
@api_bp.route('/api/config_file/<cid>/<service>', methods=['GET'])
def get_config_file(cid, service):
auth = get_auth()
if not auth or auth['role'] != 'admin':
if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'):
return err("Non autorizzato", 403)
cid = cid.lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
service = service.lower()
if not CID_RE.match(cid) or not SERVICE_RE.match(service):
return err("Parametri non validi")
@@ -330,11 +343,14 @@ def get_config_file(cid, service):
@api_bp.route('/api/config_file', methods=['POST'])
def save_config_file():
auth = get_auth()
if not auth or auth['role'] != 'admin':
if not auth or (auth['role'] != 'admin' and auth['role'] != 'node_admin'):
return err("Non autorizzato", 403)
d = json_body()
cid = str(d.get('clientId', '')).strip().lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
service = str(d.get('service', '')).strip().lower()
new_config = d.get('config_data')
if not CID_RE.match(cid) or not SERVICE_RE.match(service):
@@ -348,6 +364,15 @@ def save_config_file():
return err("Broker MQTT non raggiungibile", 503)
audit(auth['username'], cid, f"EDIT_CONFIG_{service.upper()}")
# Salva Backup
try:
with closing(db_connect()) as conn:
conn.execute("INSERT INTO config_backups (timestamp, client_id, service, config_text, username) VALUES (datetime('now', 'localtime'), ?, ?, ?, ?)",
(cid, service, new_config['raw_text'], auth['username']))
conn.commit()
except Exception as e:
logger.error(f"Errore salvataggio backup config: {e}")
if cid not in state.device_configs:
state.device_configs[cid] = {}
state.device_configs[cid][service] = new_config
@@ -357,20 +382,29 @@ def save_config_file():
# --- AGGIORNAMENTO SERVER OTA ---
@api_bp.route('/api/server_update/check', methods=['GET'])
def check_server_update():
def get_server_update_status():
global LAST_GITEA_CHECK_TIME, GLOBAL_SERVER_UPDATE_AVAILABLE
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
force_check = request.args.get('force') == '1'
# Eseguiamo il controllo sincrono se è passata 1 ora OPPURE se forzato dal client
if force_check or (time.time() - LAST_GITEA_CHECK_TIME > 3600):
try:
subprocess.run(['git', 'fetch'], timeout=10, cwd=BASE_DIR)
local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip()
remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR).decode('utf-8').strip()
update_available = local_hash != remote_hash
return jsonify({"success": True, "update_available": update_available})
# Timeout molto basso per evitare di killare il worker Gunicorn
subprocess.run(['git', 'fetch'], timeout=2, cwd=BASE_DIR)
local_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=BASE_DIR, timeout=1).decode('utf-8').strip()
remote_hash = subprocess.check_output(['git', 'rev-parse', '@{u}'], cwd=BASE_DIR, timeout=1).decode('utf-8').strip()
GLOBAL_SERVER_UPDATE_AVAILABLE = (local_hash != remote_hash)
LAST_GITEA_CHECK_TIME = time.time()
except subprocess.TimeoutExpired:
logger.warning("Gitea check andato in timeout, ignorato per non bloccare Gunicorn.")
except Exception as e:
logger.error(f"Errore controllo aggiornamenti server: {e}")
return jsonify({"success": False, "error": "Impossibile verificare aggiornamenti"})
logger.error(f"Errore controllo Gitea: {e}")
return jsonify({"success": True, "update_available": GLOBAL_SERVER_UPDATE_AVAILABLE})
@api_bp.route('/api/server_update/apply', methods=['POST'])
def apply_server_update():
@@ -431,3 +465,264 @@ def serve_sw():
@api_bp.route('/icon-512.png')
def serve_icon():
return send_from_directory(BASE_DIR, 'icon-512.png')
@api_bp.route('/api/logs/<cid>', methods=['GET'])
def get_node_logs(cid):
auth = get_auth()
if not auth:
return err("Non autorizzato", 401)
cid = cid.strip().lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
logs = list(state.node_logs.get(cid, []))
return jsonify({"success": True, "logs": logs})
@api_bp.route('/api/config_backups/<cid>/<service>', methods=['GET'])
def get_config_backups(cid, service):
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
cid = cid.strip().lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
try:
with closing(db_connect()) as conn:
c = conn.cursor()
c.execute("SELECT id, timestamp, username FROM config_backups WHERE client_id = ? AND service = ? ORDER BY id DESC LIMIT 20", (cid, service))
rows = [{"id": r[0], "timestamp": r[1], "username": r[2]} for r in c.fetchall()]
return jsonify({"success": True, "backups": rows})
except Exception as e:
return err(str(e))
@api_bp.route('/api/config_backups/<int:backup_id>', methods=['GET'])
def get_config_backup_content(backup_id):
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
try:
with closing(db_connect()) as conn:
c = conn.cursor()
c.execute("SELECT client_id, config_text FROM config_backups WHERE id = ?", (backup_id,))
row = c.fetchone()
if not row:
return err("Backup non trovato", 404)
if not node_allowed(auth['role'], auth['allowed_nodes'], row[0]):
return err("Permesso negato", 403)
return jsonify({"success": True, "text": row[1]})
except Exception as e:
return err(str(e))
import zipfile
import io
from flask import send_file
@api_bp.route('/api/fleet_backup', methods=['GET'])
def get_fleet_backup():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
memory_file = io.BytesIO()
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf:
for cid, configs in state.device_configs.items():
for service, conf in configs.items():
if isinstance(conf, dict) and 'raw_text' in conf:
zf.writestr(f"{cid}/{service.upper()}.ini", conf['raw_text'])
memory_file.seek(0)
audit(auth['username'], '-', "DOWNLOAD_FLEET_BACKUP")
return send_file(memory_file, download_name=f"fleet_configs_{time.strftime('%Y%m%d')}.zip", as_attachment=True)
@api_bp.route('/api/analytics/<cid>', methods=['GET'])
def get_analytics(cid):
auth = get_auth()
if not auth:
return err("Non autorizzato", 401)
cid = cid.strip().lower()
if not node_allowed(auth['role'], auth['allowed_nodes'], cid):
return err("Permesso negato per questo nodo", 403)
try:
hours = int(request.args.get('hours', 24))
except ValueError:
hours = 24
try:
with closing(db_connect()) as conn:
c = conn.cursor()
# Telemetria: aggreghiamo per ora
c.execute(f"""SELECT strftime('%Y-%m-%d %H:00:00', timestamp) as hr,
AVG(cpu), MAX(temp), AVG(ram)
FROM telemetry_logs
WHERE client_id = ? AND timestamp >= datetime('now', 'localtime', ?)
GROUP BY hr ORDER BY hr""", (cid, f"-{hours} hours"))
telemetry_data = [{"time": r[0], "cpu": round(r[1], 1) if r[1] else 0, "temp": round(r[2], 1) if r[2] else 0, "ram": round(r[3], 1) if r[3] else 0} for r in c.fetchall()]
# RF BER & Transiti (ignoriamo rete e beacon, prendiamo solo traffico vero locale)
c.execute(f"""SELECT strftime('%Y-%m-%d %H:00:00', timestamp) as hr,
COUNT(*), AVG(ber), AVG(rssi)
FROM radio_logs
WHERE LOWER(client_id) = ? AND timestamp >= datetime('now', 'localtime', ?)
AND source_id NOT LIKE '🌐%'
AND source_id NOT LIKE '%'
AND (LOWER(source_conn) = 'rf' OR source_conn = '')
GROUP BY hr ORDER BY hr""", (cid, f"-{hours} hours"))
rf_data = [{"time": r[0], "count": r[1], "ber": round(r[2], 2) if r[2] else 0, "rssi": round(r[3], 1) if r[3] else 0} for r in c.fetchall()]
return jsonify({"success": True, "telemetry": telemetry_data, "rf": rf_data})
except Exception as e:
logger.error(f"Analytics query error: {e}")
return err(str(e))
@api_bp.route('/api/audit_logs', methods=['GET'])
def get_audit_logs():
auth = get_auth()
if not auth or auth['role'] != 'admin':
return err("Non autorizzato", 403)
try:
with closing(db_connect()) as conn:
c = conn.cursor()
c.execute("SELECT timestamp, username, client_id, command FROM audit_logs ORDER BY id DESC LIMIT 50")
rows = [{"time": r[0], "user": r[1], "node": r[2], "cmd": r[3]} for r in c.fetchall()]
return jsonify({"success": True, "logs": rows})
except Exception as e:
return err(str(e))
@api_bp.route('/api/aprs', methods=['GET'])
def get_aprs():
auth = get_auth()
if not auth:
return err("Non autorizzato", 401)
msgs = list(getattr(state, 'aprs_msgs', []))
# msgs è una lista di dizionari dal più vecchio al più nuovo, la restituiamo direttamente
return jsonify(msgs)
# --- SCHEDULAZIONE PROFILI (CALENDAR SCHEDULER) ---
@api_bp.route('/api/schedules', methods=['GET'])
def get_schedules():
auth = get_auth()
if not auth or auth['role'] not in ('admin', 'node_admin'):
return err("Non autorizzato", 403)
try:
with closing(db_connect(row=True)) as conn:
c = conn.cursor()
c.execute("""SELECT id, title, target_nodes, target_profile, restore_profile,
start_time, end_time, status, created_by, created_at
FROM profile_schedules
ORDER BY id DESC LIMIT 50""")
rows = [dict(r) for r in c.fetchall()]
# Filtro per node_admin se non ha 'all'
if auth['role'] == 'node_admin' and 'all' not in auth['allowed_nodes'].split(','):
allowed_set = set(x.strip().lower() for x in auth['allowed_nodes'].split(','))
filtered = []
for r in rows:
t_nodes = set(x.strip().lower() for x in r['target_nodes'].split(','))
if t_nodes.issubset(allowed_set):
filtered.append(r)
rows = filtered
return jsonify({"success": True, "schedules": rows})
except Exception as e:
logger.error(f"Errore caricamento schedulazioni: {e}")
return err(str(e))
@api_bp.route('/api/schedules', methods=['POST'])
def add_schedule():
auth = get_auth()
if not auth or auth['role'] not in ('admin', 'node_admin'):
return err("Non autorizzato", 403)
d = json_body()
title = str(d.get('title', '')).strip()
target_nodes = str(d.get('target_nodes', '')).strip().lower()
target_profile = str(d.get('target_profile', '')).strip().upper()
restore_profile = str(d.get('restore_profile', 'NONE')).strip().upper()
start_time = str(d.get('start_time', '')).strip()
end_time = str(d.get('end_time', '')).strip()
if not title:
return err("Titolo evento obbligatorio")
if not target_nodes:
return err("Nodi target obbligatori")
if not target_profile:
return err("Profilo target obbligatorio")
if not start_time or not end_time:
return err("Date di inizio e fine obbligatorie")
# Verifica permessi per node_admin
if auth['role'] == 'node_admin':
allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(','))
if 'all' not in allowed:
if target_nodes == 'all':
return err("Come Node Admin non puoi schedulare su tutta la flotta", 403)
req_nodes = set(x.strip().lower() for x in target_nodes.split(','))
if not req_nodes.issubset(allowed):
return err("Non hai i permessi per tutti i nodi selezionati", 403)
# Normalizza formati orari (accetta 'YYYY-MM-DDTHH:MM' o 'YYYY-MM-DD HH:MM')
st_norm = start_time.replace('T', ' ')
if len(st_norm) == 16: st_norm += ':00'
end_norm = end_time.replace('T', ' ')
if len(end_norm) == 16: end_norm += ':00'
if st_norm >= end_norm:
return err("L'orario di fine deve essere successivo a quello di inizio")
try:
with closing(db_connect()) as conn:
conn.execute("""INSERT INTO profile_schedules
(title, target_nodes, target_profile, restore_profile, start_time, end_time, status, created_by)
VALUES (?, ?, ?, ?, ?, ?, 'SCHEDULED', ?)""",
(title, target_nodes, target_profile, restore_profile, st_norm, end_norm, auth['username']))
conn.commit()
audit(auth['username'], target_nodes, f"CREATE_SCHED_{title}_{target_profile}")
return jsonify({"success": True})
except Exception as e:
logger.error(f"Errore salvataggio schedulazione: {e}")
return err(str(e))
@api_bp.route('/api/schedules/<int:sid>', methods=['DELETE'])
def cancel_schedule(sid):
auth = get_auth()
if not auth or auth['role'] not in ('admin', 'node_admin'):
return err("Non autorizzato", 403)
try:
with closing(db_connect(row=True)) as conn:
c = conn.cursor()
c.execute("SELECT id, title, target_nodes, status, restore_profile FROM profile_schedules WHERE id = ?", (sid,))
row = c.fetchone()
if not row:
return err("Schedulazione non trovata", 404)
# Controllo permessi node_admin
if auth['role'] == 'node_admin' and 'all' not in auth['allowed_nodes'].split(','):
allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(','))
t_nodes = set(x.strip().lower() for x in row['target_nodes'].split(','))
if not t_nodes.issubset(allowed):
return err("Non autorizzato per questa schedulazione", 403)
# Se era attiva, ripristina subito il profilo
if row['status'] == 'ACTIVE' and row['restore_profile'] and row['restore_profile'] != 'NONE':
from services.scheduler_service import apply_scheduled_profile
apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE")
conn.execute("UPDATE profile_schedules SET status = 'CANCELLED' WHERE id = ?", (sid,))
conn.commit()
audit(auth['username'], row['target_nodes'], f"CANCEL_SCHED_{sid}_{row['title']}")
return jsonify({"success": True})
except Exception as e:
logger.error(f"Errore annullamento schedulazione: {e}")
return err(str(e))
+1 -1
View File
@@ -12,7 +12,7 @@ from core.database import db_connect, audit
auth_bp = Blueprint('auth', __name__)
# --- COSTANTI & REGEX VALIDAZIONE ---
VALID_ROLES = ('admin', 'operator')
VALID_ROLES = ('admin', 'node_admin', 'operator')
USERNAME_RE = re.compile(r'^[A-Za-z0-9_.@\-]{3,32}$')
MIN_PASSWORD_LEN = 8
+115 -37
View File
@@ -1,9 +1,9 @@
import json
import re
import datetime
import time
from paho.mqtt import client as mqtt_client
from core.config import config, logger
from core.database import save_to_sqlite
from core.database import save_to_sqlite, save_telemetry_to_sqlite
import core.state as state
from services.push_service import broadcast_push_notification
@@ -19,12 +19,15 @@ def on_connect(client, userdata, flags, reason_code, properties=None):
default_topics = [
"servizi/+/stat", "dmr-gateway/+/json", "devices/+/services",
"nxdn-gateway/+/json", "ysf-gateway/+/json", "p25-gateway/+/json",
"dstar-gateway/+/json", "mmdvm/+/json", "data/#", "aprs-gateway/aprs"
"dstar-gateway/+/json", "mmdvm/+/json", "data/#"
]
topics_list = config.get('mqtt', {}).get('topics', default_topics)
subscribe_list = [(topic, 0) for topic in topics_list]
subscribe_list.append(("+/+/log", 0))
subscribe_list.append(("/+/+/log", 0))
subscribe_list.append(("+/+/Log", 0))
subscribe_list.append(("/+/+/Log", 0))
client.subscribe(subscribe_list)
logger.info(f"Sottoscritto a {len(subscribe_list)} topic MQTT.")
@@ -41,37 +44,8 @@ def on_disconnect(client, userdata, disconnect_flags, reason_code, properties=No
def on_message(client, userdata, msg):
try:
topic = msg.topic
topic = msg.topic.strip('/')
payload = msg.payload.decode('utf-8', errors='replace').strip()
# NUOVO BLOCCO APRS
if topic == "aprs-gateway/aprs":
try:
raw_aprs = payload
# Formato atteso: SOURCE>DEST,PATH:PAYLOAD
if ">" in raw_aprs and ":" in raw_aprs:
header, aprs_payload = raw_aprs.split(":", 1)
source, rest = header.split(">", 1)
if "," in rest:
dest, path = rest.split(",", 1)
else:
dest = rest
path = ""
aprs_data = {
"time": datetime.datetime.now().strftime("%H:%M:%S"),
"source": source.strip(),
"dest": dest.strip(),
"path": path.strip(),
"payload": aprs_payload.strip()
}
state.socketio.emit('aprs_msg', aprs_data)
except Exception as e:
logger.error(f"Errore decodifica APRS: {e}")
return # Esci per non processare il resto della logica su questo topic
parts = topic.split('/')
if len(parts) < 2:
return
@@ -80,8 +54,26 @@ def on_message(client, userdata, msg):
p0 = parts[0].lower().replace('-', '')
p2 = parts[2].lower().replace('-', '') if len(parts) > 2 else ""
# --- 1. LOG SOFTWARE & FIRMWARE ---
# --- 1. LOG SOFTWARE, FIRMWARE & LIVE STREAM ---
if len(parts) >= 3 and parts[2].lower() == 'log':
svc_name = p0
# A) Salva in memoria per il Live Log
if cid not in state.node_logs:
from collections import deque
state.node_logs[cid] = deque(maxlen=100)
log_entry = {
"time": time.strftime("%H:%M:%S"),
"service": svc_name,
"text": payload
}
state.node_logs[cid].append(log_entry)
# Inoltra in tempo reale via WebSocket
state.socketio.emit(f"live_log_{cid}", log_entry)
# B) Parsa le versioni
if cid not in state.node_versions:
state.node_versions[cid] = {}
@@ -114,6 +106,38 @@ def on_message(client, userdata, msg):
if "GitID" not in state.node_versions[cid][last_prog]:
state.node_versions[cid][last_prog] += f" (GitID #{git_id})"
state.notify_update()
# C) Estrazione APRS/DPRS raw dai log dei Gateway
if ('DPRS' in payload or 'APRS' in payload) and '>' in payload and ':' in payload:
# Es: I: 2026-11-08 12:30:58.615 DPRS IV3JDV /ID51 IV3JDV-9 IV3JDV-9>API51,DSTAR*:/115922h4503.75N/00731.49E[034/002/
m_aprs = re.search(r'([A-Z0-9\-]{3,9})>([^:]+):(.+)', payload)
if m_aprs:
src_part = m_aprs.group(1).strip()
header_part = m_aprs.group(2).strip()
pld_part = m_aprs.group(3).strip()
header_tokens = header_part.split(",")
dest_part = header_tokens[0]
path_str = ",".join(header_tokens[1:]) if len(header_tokens) > 1 else ""
aprs_data = {
"source": src_part,
"dest": dest_part,
"path": path_str,
"payload": pld_part,
"time": time.strftime("%H:%M:%S")
}
if not hasattr(state, 'aprs_msgs'):
from collections import deque
state.aprs_msgs = deque(maxlen=100)
state.aprs_msgs.append(aprs_data)
logger.info(f"📍 APRS (da log {svc_name}): {src_part} -> {dest_part}")
state.socketio.emit('aprs_msg', aprs_data)
# NOTA: Rimosso il return incondizionato qui, perché il log deve completare la sua corsa
# e non bloccare eventuali altre logiche!
return
# Aggiornamento timestamp last_seen
@@ -190,6 +214,16 @@ def on_message(client, userdata, msg):
health_changed = state.device_health.get(cid) != new_health
state.device_health[cid] = new_health
# Salvataggio storico nel DB (campionamento max 1 volta ogni 15 minuti)
now_ts = time.time()
last_save = getattr(state, 'last_telemetry_save', {}).get(cid, 0)
if now_ts - last_save >= 900: # 15 minuti (900 secondi)
save_telemetry_to_sqlite(cid, new_health)
if not hasattr(state, 'last_telemetry_save'):
state.last_telemetry_save = {}
state.last_telemetry_save[cid] = now_ts
if health_changed:
state.notify_update()
@@ -334,12 +368,46 @@ def on_message(client, userdata, msg):
if m and "running" not in m.lower():
save_to_sqlite(cid, {'src_id': f"🌐 {m}", 'dst_id': 'NET'}, protocol=proto)
# --- LETTURA STATO MODI DA TOPIC data/+/MMDVM ---
# --- 7.5 EVENTI APRS ---
elif p0 == 'aprsgateway' and len(parts) >= 2 and parts[1].lower() == 'aprs':
try:
if not payload:
return
# Payload RAW APRS: CALLSIGN>DEST,PATH:PAYLOAD
data = {"source": "---", "dest": "---", "path": "", "payload": payload, "time": ""}
if ">" in payload and ":" in payload:
src_part, rest = payload.split(">", 1)
header_part, pld_part = rest.split(":", 1)
header_tokens = header_part.split(",")
dest_part = header_tokens[0]
path_str = ",".join(header_tokens[1:]) if len(header_tokens) > 1 else ""
data["source"] = src_part.strip()
data["dest"] = dest_part.strip()
data["path"] = path_str.strip()
data["payload"] = pld_part.strip()
else:
logger.warning(f"Formato APRS non decodificato: {payload}")
logger.info(f"📍 Inoltro pacchetto APRS al frontend: {data['source']} -> {data['dest']} via [{data['path']}]")
if not hasattr(state, 'aprs_msgs'):
from collections import deque
state.aprs_msgs = deque(maxlen=100)
state.aprs_msgs.append(data)
state.socketio.emit('aprs_msg', data)
except Exception as e:
logger.error(f"Errore parsing APRS: {e}")
# --- MODI OPERATIVI MMDVM ---
elif len(parts) == 3 and p0 == 'data' and p2 == 'mmdvm':
try:
cid = parts[1].lower()
data = json.loads(payload)
state.operating_modes[cid] = data
state.operating_modes[cid] = json.loads(payload)
state.notify_update()
except Exception as e:
logger.error(f"Errore parsing MMDVM modes per {cid}: {e}")
@@ -359,6 +427,16 @@ def on_message(client, userdata, msg):
state.client_telemetry[cid]["idle"] = False
# --- ALLINEAMENTO MODI PER BEACON ---
curr_mode = data.get('MMDVM', {}).get('mode', '')
if curr_mode:
if curr_mode.upper() == 'DMR':
state.client_telemetry[cid]["alt"] = ""
else:
old_alt = state.client_telemetry[cid].get("alt", "")
if not any(i in old_alt for i in ['🟢','🟣','🔵','🟠']):
state.client_telemetry[cid]["alt"] = f"📡 {curr_mode.upper()} BEACON"
if 'DMR' in data:
d = data['DMR']
act = d.get('action')
+85 -2
View File
@@ -45,6 +45,89 @@ def auto_update_ids():
download_logic()
prune_old_data()
time.sleep(65)
# Controllo schedulazioni profili
check_profile_schedules()
except Exception as e:
logger.error(f"⚠️ Errore nel thread update: {e}")
time.sleep(30)
logger.error(f"⚠️ Errore nel thread scheduler: {e}")
time.sleep(15)
from contextlib import closing
from core.database import db_connect, audit
def apply_scheduled_profile(target_nodes, profile, action_type="SWITCH"):
from services.mqtt_service import mqtt_publish
from core.config import CLIENTS_PATH
import json
import re
CID_RE = re.compile(r'^[a-z0-9][a-z0-9_\-]{0,63}$')
nodes = []
if target_nodes.strip().lower() == 'all':
if os.path.exists(CLIENTS_PATH):
try:
with open(CLIENTS_PATH, 'r') as f:
clist = json.load(f)
nodes = [str(c.get('id', '')).lower() for c in clist if CID_RE.match(str(c.get('id', '')).lower())]
except Exception as e:
logger.error(f"Errore lettura clients per schedule: {e}")
else:
nodes = [x.strip().lower() for x in target_nodes.split(',') if CID_RE.match(x.strip().lower())]
logger.info(f"📅 Scheduler applica profilo [{profile}] su {len(nodes)} nodi ({target_nodes})")
for cid in nodes:
mqtt_publish(f"servizi/{cid}/cmnd", profile)
if cid in state.client_telemetry and isinstance(state.client_telemetry[cid], dict):
state.client_telemetry[cid]["alt"] = f"📅 SCHED: {profile}"
state.notify_update()
def check_profile_schedules():
try:
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
with closing(db_connect(row=True)) as conn:
c = conn.cursor()
c.execute("""SELECT id, title, target_nodes, target_profile, restore_profile,
start_time, end_time, status, created_by
FROM profile_schedules
WHERE status IN ('SCHEDULED', 'ACTIVE')""")
rows = c.fetchall()
for row in rows:
sid = row['id']
title = row['title']
nodes = row['target_nodes']
target_prof = row['target_profile']
restore_prof = row['restore_profile']
st_time = row['start_time']
end_time = row['end_time']
status = row['status']
# Formattiamo le date nel caso abbiano una 'T' (input HTML5 datetime-local)
st_norm = st_time.replace('T', ' ')
if len(st_norm) == 16: st_norm += ':00'
end_norm = end_time.replace('T', ' ')
if len(end_norm) == 16: end_norm += ':00'
if status == 'SCHEDULED':
if st_norm <= now_str < end_norm:
logger.info(f"▶️ Avvio schedulazione ID {sid} - '{title}' -> Profilo {target_prof}")
apply_scheduled_profile(nodes, target_prof, "START")
conn.execute("UPDATE profile_schedules SET status = 'ACTIVE' WHERE id = ?", (sid,))
conn.commit()
audit("SCHEDULER", nodes, f"START_SCHED_{sid}_{target_prof}")
elif now_str >= end_norm:
# Scaduta prima di iniziare
logger.warning(f"⌛ Schedulazione ID {sid} - '{title}' scaduta senza esecuzione.")
conn.execute("UPDATE profile_schedules SET status = 'EXPIRED' WHERE id = ?", (sid,))
conn.commit()
elif status == 'ACTIVE':
if now_str >= end_norm:
logger.info(f"⏹️ Fine schedulazione ID {sid} - '{title}' -> Ripristino {restore_prof}")
if restore_prof and restore_prof.upper() != 'NONE':
apply_scheduled_profile(nodes, restore_prof, "RESTORE")
conn.execute("UPDATE profile_schedules SET status = 'COMPLETED' WHERE id = ?", (sid,))
conn.commit()
audit("SCHEDULER", nodes, f"RESTORE_SCHED_{sid}_{restore_prof}")
except Exception as e:
logger.error(f"Errore controllo schedulazioni profili: {e}")
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+279
View File
@@ -0,0 +1,279 @@
/* =========================================
LAYOUT 2: TACTICAL (Ispirato alla versione dark/ambra)
========================================= */
body.layout-tactical {
--bg-main: #111318;
--card-bg: #1c2128;
--primary: #f5b041; /* Giallo/Ambra */
--accent: #c0392b; /* Rosso scuro */
--success: #2ecc71; /* Verde */
--danger: #e74c3c;
--text-main: #e6edf3;
--text-muted: #7d8590;
--border-main: #444c56;
--border-light: #30363d;
background-color: var(--bg-main);
}
body.layout-tactical .card, body.layout-tactical .modal-content {
background: var(--card-bg) !important;
border: 1px solid var(--border-light) !important;
border-radius: 4px !important;
box-shadow: 0 4px 10px rgba(0,0,0,0.4) !important;
}
body.layout-tactical .title-brand {
color: var(--primary);
}
body.layout-tactical .tactical-led {
border-radius: 2px !important; /* LED quadrati e rigidi */
}
body.layout-tactical .terminal-log {
background: #0d1117;
border-color: var(--border-light);
}
/* =========================================
LAYOUT 3: LIGHT (Clean & Bright - Modalità diurna)
========================================= */
body.layout-light {
--bg-main: #f8fafc;
--card-bg: #ffffff;
--primary: #0ea5e9; /* Azzurro pulito */
--accent: #8b5cf6;
--success: #10b981;
--danger: #ef4444;
--text-main: #1e293b;
--text-muted: #64748b;
--border-main: #cbd5e1;
--border-light: #e2e8f0;
background-color: var(--bg-main) !important;
background-image: none !important; /* Rimozione della griglia blueprint! */
color: var(--text-main);
}
/* --- Override for the main layout grid from original style.css --- */
body.layout-light div.card,
body.layout-light div.modal-content,
body.layout-light div.mini-card {
background: #ffffff !important;
border: 1px solid var(--border-main) !important;
border-radius: 8px !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important;
}
body.layout-light .filter-bar {
background: #ffffff !important;
border: 1px solid var(--border-main) !important;
}
body.layout-light .filter-pill {
color: var(--text-muted) !important;
border-color: var(--border-main) !important;
}
body.layout-light .filter-pill.active {
color: var(--primary) !important;
border-color: var(--primary) !important;
background: #f0f9ff !important;
}
body.layout-light .filter-pill:hover {
background: #f8fafc !important;
}
/* Fix per la mappa */
body.layout-light .dark-tiles {
filter: none !important;
-webkit-filter: none !important;
}
body.layout-light .custom-map-pin.pin-online {
background: var(--success);
border-color: #059669;
box-shadow: 0 0 10px rgba(16, 185, 129, 0.4);
color: white;
}
body.layout-light .custom-map-pin.pin-offline {
background: var(--danger);
border-color: #b91c1c;
box-shadow: 0 0 10px rgba(239, 68, 68, 0.4);
color: white;
}
/* --- Top Bar --- */
body.layout-light #top-bar-container,
body.layout-light #top-bar {
background: #ffffff !important;
border-bottom: 1px solid var(--border-main) !important;
box-shadow: 0 2px 10px rgba(0,0,0,0.03);
}
body.layout-light .title-brand {
color: var(--primary) !important;
text-shadow: none !important;
}
/* Testi scuri sulle mini card */
body.layout-light .mini-card-name {
color: var(--text-main) !important;
font-weight: 600;
}
body.layout-light .mini-card[style*="grayscale"] {
opacity: 0.5 !important;
background: #f1f5f9 !important;
}
/* Bottoni, Tab e Navigazione */
body.layout-light .nav-tab { color: var(--text-muted); }
body.layout-light .nav-tab.active {
color: var(--primary) !important;
border-bottom: 2px solid var(--primary) !important;
background: transparent !important;
}
body.layout-light .theme-switch {
border: 1px solid var(--border-main) !important;
color: var(--text-muted) !important;
background: transparent !important;
}
body.layout-light .btn-cmd {
color: var(--text-main) !important;
border-color: var(--border-main) !important;
background: #ffffff;
}
body.layout-light .btn-cmd:hover {
background: #f1f5f9;
}
/* Fix per i pannelli informativi a bordo */
body.layout-light .freq-bar,
body.layout-light .node-meta,
body.layout-light .health-bar {
border-color: var(--border-light) !important;
color: var(--text-muted) !important;
}
body.layout-light .health-bar span {
border-right-color: var(--border-light) !important;
}
body.layout-light .seen-bar {
border-color: var(--border-light) !important;
}
/* Testo interno delle Card dei Nodi */
body.layout-light .client-name {
color: var(--text-main) !important;
}
body.layout-light .badge-id {
color: var(--text-muted) !important;
}
body.layout-light .type-badge.type-repeater {
color: var(--primary) !important;
border-color: var(--primary) !important;
background: transparent;
}
body.layout-light .status-display {
color: var(--text-main) !important;
border-color: var(--border-light) !important;
}
/* Fix tabelle */
body.layout-light table { background: transparent; }
body.layout-light thead th, body.layout-light thead tr {
background: #f1f5f9 !important;
color: var(--text-muted) !important;
border-bottom: 2px solid var(--border-main) !important;
font-weight: 600;
}
body.layout-light tbody tr, body.layout-light td {
background: #ffffff !important;
border-bottom: 1px solid var(--border-light) !important;
color: var(--text-main) !important;
}
body.layout-light tbody tr:nth-child(even), body.layout-light tbody tr:nth-child(even) td {
background: #f8fafc !important;
}
body.layout-light tbody tr:hover, body.layout-light tbody tr:hover td {
background: #f1f5f9 !important;
}
/* Input */
body.layout-light select, body.layout-light input, body.layout-light textarea {
background: #ffffff !important;
color: var(--text-main) !important;
border: 1px solid var(--border-main) !important;
}
body.layout-light .terminal-log {
background: #f1f5f9 !important;
color: #334155 !important;
border-color: var(--border-main) !important;
}
/* Fix visibilità dei pin mappa nel tema chiaro */
body.layout-light .custom-map-pin {
color: #ffffff !important;
font-weight: bold !important;
font-size: 16px !important;
line-height: 24px !important;
}
body.layout-light .custom-map-pin.pin-online {
background-color: var(--success) !important;
border: 2px solid #059669 !important;
box-shadow: 0 0 12px rgba(16, 185, 129, 0.6) !important;
}
body.layout-light .custom-map-pin.pin-offline {
background-color: var(--danger) !important;
border: 2px solid #b91c1c !important;
box-shadow: 0 0 12px rgba(239, 68, 68, 0.6) !important;
}
body.layout-light .custom-map-pin.pin-tx {
background-color: var(--primary) !important;
border: 2px solid #0284c7 !important;
box-shadow: 0 0 15px rgba(2, 132, 199, 0.8) !important;
}
body.layout-light .custom-map-pin.pin-warn {
background-color: var(--accent) !important;
border: 2px solid #7c3aed !important;
}
/* Fix per i container delle popup di Leaflet */
body.layout-light .leaflet-popup-content-wrapper,
body.layout-light .leaflet-popup-tip {
background: #ffffff !important;
color: var(--text-main) !important;
box-shadow: 0 4px 15px rgba(0,0,0,0.1) !important;
}
body.layout-light .leaflet-popup-content div {
color: var(--text-main);
}
/* =========================================
LAYOUT 4: GLASSMORPHISM & NEON
Layout moderno, traslucido con sfocature
========================================= */
body.layout-glass {
--bg-main: #0f172a;
--primary: #38bdf8;
--accent: #c084fc;
--success: #34d399;
--danger: #fb7185;
--card-bg: rgba(255, 255, 255, 0.03);
--border-light: rgba(255,255,255,0.1);
background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
background-attachment: fixed;
}
body.layout-glass .card, body.layout-glass .modal-content {
background: var(--card-bg) !important;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255,255,255,0.08) !important;
border-radius: 24px !important;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5) !important;
}
body.layout-glass .btn-cmd, body.layout-glass .filter-pill {
border-radius: 12px;
}
body.layout-glass .card-header {
border-bottom: 1px solid rgba(255,255,255,0.05);
padding-bottom: 15px;
}
body.layout-glass input, body.layout-glass select, body.layout-glass textarea {
background: rgba(0,0,0,0.3);
border-radius: 8px;
border: 1px solid rgba(255,255,255,0.1);
}
+3 -3
View File
@@ -31,8 +31,8 @@ body {
#top-bar { padding: 12px 20px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 15px; border: 1px solid var(--border-main); width: 100%; max-width: 1400px; background: rgba(6, 36, 111, 0.5); }
.title-brand { font-size: 1.2rem; font-weight: 300; letter-spacing: 4px; color: var(--text-main); text-transform: uppercase; white-space: nowrap; flex-shrink: 0; margin-right: 10px;}
.nav-tabs { display: flex; gap: 10px; flex: 1 1 auto; min-width: 250px; flex-wrap: wrap; justify-content: flex-start; margin-left: 0;}
.nav-tab { background: transparent; border: 1px solid transparent; color: var(--text-muted); font-size: 0.85rem; font-weight: 300; letter-spacing: 2px; cursor: pointer; padding: 6px 16px; transition: all 0.2s ease; text-transform: uppercase; white-space: nowrap;}
.nav-tabs { display: flex; gap: 10px; flex-wrap: nowrap; justify-content: flex-start; margin-left: 0;}
.nav-tab { background: transparent; border: 1px solid transparent; color: var(--text-muted); font-size: 0.85rem; font-weight: 300; letter-spacing: 2px; cursor: pointer; padding: 6px 14px; transition: all 0.2s ease; text-transform: uppercase; white-space: nowrap;}
.nav-tab:hover { color: var(--text-main); border: 1px solid var(--border-light); }
.nav-tab.active { color: var(--text-main); border: 1px solid var(--border-main); }
@@ -40,7 +40,7 @@ body {
.theme-switch:hover { background: rgba(255,255,255,0.1); }
/* Container for right side items (auth and other buttons) */
.top-bar-right { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: flex-end; flex: 1 1 auto; }
.top-bar-right { display: flex; align-items: center; gap: 8px; flex-wrap: nowrap; justify-content: flex-end; flex: none; }
/* FILTRI E CONTROLLI VIEW */
.filter-bar { background: rgba(6, 36, 111, 0.90); border: 1px solid var(--border-main); padding: 10px 20px; display: flex; gap: 15px; flex-wrap: wrap; align-items: center; justify-content: space-between; margin-bottom: 20px; }
+418 -54
View File
@@ -1,5 +1,16 @@
function updateClock() {
const clockEl = document.getElementById('live-clock');
if (clockEl) {
const now = new Date();
const dateStr = now.toLocaleDateString('it-IT', { day: '2-digit', month: '2-digit', year: 'numeric' });
const timeStr = now.toLocaleTimeString('it-IT', { hour12: false, hour: '2-digit', minute:'2-digit', second:'2-digit' });
clockEl.innerHTML = `<span style="color:var(--primary);">SYS_TIME:</span> ${dateStr} // <b style="color:var(--text-main);">${timeStr}</b> LOC`;
}
}
// --- VARIABILI GLOBALI E UI VIEW ---
let clients = [];
let activeLoggedUsers = [];
let me = { logged_in: false, user: '', role: '', allowed_nodes: '' };
let isAuthenticated = false;
let usersCache = {};
@@ -14,19 +25,48 @@ let searchQuery = '';
let viewMode = localStorage.getItem('fleetViewMode') || 'grid';
let fleetMap = null;
let mapMarkers = {};
let aprsMarkers = {};
let currentFocusedNode = null;
let currentMmdvmConfig = "";
let currentMmdvmConfigAlias = "";
let currentMmdvmServiceName = "";
// --- LAYOUT SWITCHER ---
const layouts = ['layout-blueprint', 'layout-tactical', 'layout-light', 'layout-glass'];
const layoutLabels = ['[ L: BLU ]', '[ L: TAC ]', '[ L: LGT ]', '[ L: GLASS ]'];
let currentLayoutIdx = 0;
function initLayout() {
const saved = localStorage.getItem('fleetLayout') || 'layout-blueprint';
currentLayoutIdx = layouts.indexOf(saved) > -1 ? layouts.indexOf(saved) : 0;
applyLayout();
}
function cycleLayout() {
currentLayoutIdx = (currentLayoutIdx + 1) % layouts.length;
localStorage.setItem('fleetLayout', layouts[currentLayoutIdx]);
applyLayout();
}
function applyLayout() {
document.body.classList.remove(...layouts);
if (layouts[currentLayoutIdx] !== 'layout-blueprint') {
document.body.classList.add(layouts[currentLayoutIdx]);
}
const btn = document.getElementById('layout-btn');
if (btn) btn.innerText = layoutLabels[currentLayoutIdx];
}
// Mappatura Modo -> Gateway service name
const MODE_GATEWAYS = {
'DMR': ['dmrgateway'],
'NXDN': ['nxdngateway'],
'System Fusion': ['ysfgateway'],
'D-Star': ['dstargateway', 'dstar-gateway'],
'P25': ['p25gateway']
'P25': ['p25gateway'],
'M17': ['m17gateway', 'm17-gateway']
};
function switchView(viewName) {
@@ -67,11 +107,14 @@ function openNodeFocus(clientId) {
document.getElementById('tab-aprs').classList.remove('active');
document.getElementById('view-focus').style.display = 'block';
window.scrollTo({ top: 0, behavior: 'smooth' });
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
const modesCard = document.getElementById('focus-modes-card');
if (modesCard) {
@@ -85,6 +128,7 @@ function openNodeFocus(clientId) {
refreshStates();
refreshLogs();
setTimeout(loadNodeAnalytics, 300);
}
function closeNodeFocus() {
@@ -98,13 +142,16 @@ function closeNodeFocus() {
window.addEventListener('DOMContentLoaded', () => {
const savedView = localStorage.getItem('fleetDefaultView') || 'home';
switchView(savedView);
initLayout();
initUI();
checkPushStatus();
setInterval(updateClock, 1000); updateClock();
setInterval(refreshStates, 15000);
setInterval(() => { refreshLogs(); refreshStats(); }, 60000);
checkServerUpdate();
setInterval(checkServerUpdate, 3600000);
refreshAprs();
setInterval(cleanupAprsMarkers, 60000);
});
// --- FUNZIONI FILTRO E LAYOUT ---
@@ -128,10 +175,10 @@ function applyViewMode() {
const btnToggle = document.getElementById('view-toggle-btn');
if (viewMode === 'list') {
gridDiv.className = 'list-view';
btnToggle.innerText = '[ LIST ]';
btnToggle.innerText = t('btnList') || '[ LIST ]';
} else {
gridDiv.className = 'grid';
btnToggle.innerText = '[ GRID ]';
btnToggle.innerText = t('btnGrid') || '[ GRID ]';
}
}
@@ -165,6 +212,16 @@ function applyFilters() {
});
}
function showActiveUsers() {
if (!activeLoggedUsers || activeLoggedUsers.length === 0) {
customAlert("[ USERS ]", "Nessun operatore attualmente loggato.");
return;
}
const html = activeLoggedUsers.map(u => `<div style="padding: 5px; border-bottom: 1px dashed var(--border-light); color: var(--success); font-family: 'JetBrains Mono'; font-size: 0.9rem;">🟢 ${esc(u.toUpperCase())}</div>`).join('');
customAlert("[ SYS_OPS_ONLINE ]", html);
}
function fmtAge(sec) {
sec = Math.max(0, Math.round(sec));
if (sec < 60) return sec + 's';
@@ -247,7 +304,7 @@ function sendTgCommand(clientId, comando) {
async function fetchNodeConfigForModes(clientId) {
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
const modesCard = document.getElementById('focus-modes-card');
if (!canControl) {
if (modesCard) modesCard.style.display = 'none';
@@ -306,7 +363,7 @@ async function fetchNodeConfigForModes(clientId) {
function renderModeToggles(clientId, statusMsg = "") {
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(clientId.toLowerCase()));
const modesCard = document.getElementById('focus-modes-card');
if (modesCard) {
@@ -326,7 +383,9 @@ function renderModeToggles(clientId, statusMsg = "") {
{ id: 'D-Star', label: 'D-STAR', color: '#f97316' },
{ id: 'System Fusion', label: 'YSF', color: '#8b5cf6' },
{ id: 'NXDN', label: 'NXDN', color: 'var(--success)' },
{ id: 'P25', label: 'P25', color: 'var(--accent)' }
{ id: 'P25', label: 'P25', color: 'var(--accent)' },
{ id: 'FM', label: 'FM', color: '#14b8a6' },
{ id: 'M17', label: 'M17', color: '#ec4899' } // Aggiunto modo M17 (Rosa/Pink)
];
let html = "";
@@ -357,14 +416,20 @@ function renderModeToggles(clientId, statusMsg = "") {
? `border-color: ${m.color}; color: ${m.color} !important; box-shadow: inset 0 0 8px ${m.color}; font-weight: bold;`
: `border-color: var(--border-light); color: var(--text-muted) !important; opacity: 0.4;`;
html += `<button class="btn-cmd" style="padding: 10px 15px; font-size: 1.1rem; width: auto; flex: 1; min-width: 80px; transition: all 0.2s ease; ${btnStyle}" onclick="toggleOperatingMode('${clientId}', '${m.id}', ${!enabled})">${m.label}</button>`;
// Rimosso flex:1 per evitare che l'ultimo bottone si allarghi al 100% sulla riga vuota
html += `<button class="btn-cmd" style="padding: 10px; font-size: 1.1rem; width: 100%; transition: all 0.2s ease; ${btnStyle}" onclick="toggleOperatingMode('${clientId}', '${m.id}', ${!enabled})">${m.label}</button>`;
}
});
if (html === "") html = '<span style="color:var(--text-muted); font-size: 0.9rem;">NO MODES FOUND IN CONFIG</span>';
if (html === "") {
html = '<span style="color:var(--text-muted); font-size: 0.9rem;">NO MODES FOUND IN CONFIG</span>';
} else {
// Avvolgiamo i bottoni in una CSS Grid per un allineamento perfetto e proporzionato
html = `<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(75px, 1fr)); gap: 10px; width: 100%;">${html}</div>`;
}
if (statusMsg) {
html += `<div style="width: 100%; margin-top: 8px; font-family: 'JetBrains Mono', monospace;">${statusMsg}</div>`;
html += `<div style="width: 100%; margin-top: 12px; font-family: 'JetBrains Mono', monospace;">${statusMsg}</div>`;
}
container.innerHTML = html;
@@ -479,23 +544,28 @@ async function initUI() {
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
if (isAuthenticated) {
let adminBtn = role === 'admin' ? `
<button id="server-update-btn" onclick="confirmServerUpdate()" class="auth-btn" style="border-color:var(--danger); color:var(--danger) !important; display:none;" title="Aggiornamento Server Disponibile">[ UPD_SERVER ]</button>
<button onclick="sendGlobalUpdate()" class="auth-btn" style="color:var(--accent);" data-i18n-title="ttReqCfg" title="${t('ttReqCfg')}">[ ${t('btnReqCfg')} ]</button>
<button onclick="triggerGlobalEmergency()" class="auth-btn" style="color:var(--danger);" data-i18n-title="ttGlobal" title="${t('ttGlobal')}">[ ${t('btnGlobal')} ]</button>
<button onclick="openAdmin()" class="auth-btn" style="color:var(--primary);" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">[ ${t('btnAdmin')} ]</button>` : '';
const hasAllNodes = allowedList.includes('all');
const canOverride = hasAllNodes;
authContainer.innerHTML = `${adminBtn}
<span style="font-weight:300; font-size:0.85rem; margin: 0 10px; font-family:'JetBrains Mono', monospace; color:var(--primary);">USR: ${esc(String(me.user).toUpperCase())}</span>
<button onclick="changeMyPassword()" class="auth-btn" data-i18n-title="ttPass" title="${t('ttPass')}">[ ${t('btnPass')} ]</button>
<button onclick="logout()" class="auth-btn" data-i18n-title="ttLogout" title="${t('ttLogout')}">[ ${t('btnLogout')} ]</button>`;
// 1. Nella barra principale in alto teniamo SOLO [ SYS_ADM ], UTENTE e CONTROLLI SESSIONE
let topBarAdminBtn = '';
if (role === 'admin' || role === 'node_admin') {
topBarAdminBtn = `<button onclick="openAdmin()" class="auth-btn" style="color:var(--primary);" data-i18n-title="ttAdmin" title="${t('ttAdmin')}">[ ${t('btnAdmin')} ]</button>`;
}
authContainer.innerHTML = `<div style="display:flex; align-items:center; gap:8px; justify-content:flex-end; flex-wrap:nowrap; width:100%;">
${topBarAdminBtn}
<span style="font-weight:400; font-size:0.75rem; margin: 0 4px; font-family:'JetBrains Mono', monospace; color:var(--primary); white-space:nowrap; letter-spacing: 1px;">USR: ${esc(String(me.user).toUpperCase())}</span>
<button onclick="changeMyPassword()" class="auth-btn" data-i18n-title="ttPass" title="${t('ttPass')}" style="padding:4px 10px; font-size:0.75rem;">[ ${t('btnPass')} ]</button>
<button onclick="logout()" class="auth-btn" data-i18n-title="ttLogout" title="${t('ttLogout')}" style="padding:4px 10px; font-size:0.75rem;">[ ${t('btnLogout')} ]</button>
</div>`;
} else {
authContainer.innerHTML = `<button onclick="openLoginModal()" class="auth-btn" style="color:var(--success);">[ AUTH ]</button>`;
}
grid.innerHTML = clients.map(c => {
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
let showReboot = (role === 'admin');
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
let showReboot = (role === 'admin' || role === 'node_admin') && canControl;
return `
<div class="card" id="card-${c.id}" data-status="offline" data-gateways="" data-loc="" data-has-warn="false">
@@ -559,6 +629,7 @@ async function initUI() {
<button class="btn-cmd" style="border-color: var(--primary); color: var(--primary) !important;" title="Versioni Software" onclick="openVersionsModal('${c.id}')">INFO</button>
<button id="btn-svc-${c.id}" class="btn-cmd" style="border-color: var(--text-main);" title="${t('ttSvc')}" onclick="openServicesModal('${c.id}')">${t('btnSvc')}</button>
<button class="btn-cmd" style="border-color: var(--accent); color: var(--accent) !important;" title="${t('ttFile')}" onclick="openConfigsModal('${c.id}')">${t('btnFile')}</button>
<button class="btn-cmd" style="border-color: var(--success); color: var(--success) !important;" title="${t('liveTerminal')}" onclick="openLogModal('${c.id}')">LOG</button>
<button class="btn-cmd" style="border-color: var(--danger); color: var(--danger) !important;" title="${t('ttHat')}" onclick="confirmHatReset('${c.id}')">${t('btnHat')}</button>
<button class="btn-cmd" style="border-color: var(--danger); color: var(--danger) !important;" title="${t('ttBoot')}" onclick="confirmReboot('${c.id}')">${t('btnBoot')}</button>
<button id="btn-ota-${c.id}" class="btn-cmd" style="border-color: var(--primary); color: var(--primary) !important;" title="Update OTA" onclick="confirmUpdateAgent('${c.id}')">OTA</button>
@@ -571,12 +642,13 @@ async function initUI() {
const miniGrid = document.getElementById('home-mini-nodes');
if (miniGrid) {
miniGrid.innerHTML = clients.map(c => `
<div id="mini-card-${c.id}" class="mini-card" onclick="openNodeFocus('${c.id}')">
<div class="mini-card-content">
<div id="mini-card-${c.id}" class="mini-card" onclick="openNodeFocus('${c.id}')" style="width: 180px !important; min-width: 180px !important; height: 125px !important; display: flex; flex-direction: column; justify-content: space-between; padding-bottom: 12px; box-sizing: border-box;">
<div class="mini-card-content" style="flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center;">
<div id="mini-name-${c.id}" class="mini-card-name" title="${esc(c.name)}">${esc(c.name)}</div>
<div id="mini-id-${c.id}" style="font-family: 'JetBrains Mono', monospace; font-size: 0.65rem; color: var(--text-muted); margin-top: 2px;">ID: ${c.id.toUpperCase()}</div>
<div id="mini-caller-${c.id}" style="font-family: 'JetBrains Mono', monospace; font-size: 0.9rem; font-weight: bold; margin-top: 6px; display: none; text-align: center; line-height: 1.1;"></div>
</div>
<div id="mini-status-${c.id}" class="mini-card-status" title="OFFLINE">OFFLINE</div>
<div id="mini-status-${c.id}" class="mini-card-status" title="OFFLINE" style="position: relative !important; bottom: auto !important; left: auto !important; transform: none !important; width: 90%; margin: 0 auto; flex-shrink: 0;">OFFLINE</div>
</div>
`).join('');
}
@@ -622,7 +694,10 @@ function initOrUpdateMap() {
const isOnline = !state.toUpperCase().includes("OFF") && state !== "";
const health = latestStatesData.health && latestStatesData.health[cid];
const card = document.getElementById(`card-${c.id}`);
const isTx = card && card.dataset.lastTx && (Date.now() - parseInt(card.dataset.lastTx) < 3000);
// Recupariamo lo stato calcolato in refreshStates()
const isTx = card && card.dataset.isTx === 'true';
const isHold = card && card.dataset.isHold === 'true';
const warns = (latestStatesData.warnings && latestStatesData.warnings[cid]) || [];
if (info && info.lat && info.lon && parseFloat(info.lat) !== 0 && parseFloat(info.lon) !== 0) {
@@ -631,7 +706,7 @@ function initOrUpdateMap() {
bounds.push([lat, lon]);
let pinClass = isOnline ? (warns.length > 0 ? 'pin-warn' : 'pin-online') : 'pin-offline';
if (isTx) pinClass += ' pin-tx';
if (isTx || isHold) pinClass += ' pin-tx';
let iconSymbol = "+";
if (warns.length > 0 && !isTx) iconSymbol = "!";
@@ -678,6 +753,13 @@ function initOrUpdateMap() {
fleetMap.fitBounds(bounds, { padding: [40, 40] });
fleetMap._hasFitted = true;
}
// Assicurati che i marker APRS siano renderizzati
for (const [src, data] of Object.entries(aprsMarkers)) {
if (!fleetMap.hasLayer(data.marker)) {
data.marker.addTo(fleetMap);
}
}
}
async function refreshStates() {
@@ -685,6 +767,18 @@ async function refreshStates() {
const res = await fetch('/api/states'); const data = await res.json();
latestStatesData = data;
globalVersionsData = data.versions || {};
if (data.web_users !== undefined) {
const uEl = document.getElementById('active-users-count');
if (uEl) uEl.innerText = data.web_users;
const uBadge = document.getElementById('users-badge');
if (uBadge) {
uBadge.style.cursor = 'pointer';
uBadge.onclick = showActiveUsers;
}
}
if (data.logged_users !== undefined) {
activeLoggedUsers = data.logged_users;
}
clients.forEach(c => {
try {
@@ -701,8 +795,8 @@ async function refreshStates() {
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
let showReboot = (role === 'admin');
let canControl = isAuthenticated && (allowedList.includes('all') || allowedList.includes(c.id.toLowerCase()));
let showReboot = (role === 'admin' || role === 'node_admin') && canControl;
let isTx = false;
let activeModeColor = "var(--primary)";
@@ -734,7 +828,22 @@ async function refreshStates() {
cardDiv.dataset.status = isOnline ? 'online' : 'offline';
renderSeen(c, data, isOnline);
const warns = (data.warnings && data.warnings[c.id.toLowerCase()]) || [];
let warns = (data.warnings && data.warnings[c.id.toLowerCase()]) ? [...data.warnings[c.id.toLowerCase()]] : [];
let hasOfflineService = false;
if (healthObj && healthObj.processes) {
for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) {
let s = svcStatus.toLowerCase();
if (s !== 'online' && s !== 'standby') {
hasOfflineService = true;
warns.push(`SVC KO: ${svcName.toUpperCase()}`);
}
}
}
if (!latestStatesData.warnings) latestStatesData.warnings = {};
latestStatesData.warnings[c.id.toLowerCase()] = warns;
cardDiv.dataset.hasWarn = (warns.length > 0) ? 'true' : 'false';
const diagDiv = document.getElementById(`diag-warn-${c.id}`);
if (diagDiv) {
@@ -831,9 +940,26 @@ async function refreshStates() {
else if (action === 'unlinked') { badgeColor = 'var(--text-muted)'; badgeBorder = 'var(--border-light)'; suffix = ' [UNL]'; }
else { badgeColor = gw.color; badgeBorder = gw.color; }
const chipBase = "display:inline-flex; align-items:center; gap:5px; font-size:0.75rem; font-family:'JetBrains Mono',monospace; padding:2px 6px; margin:2px 4px 2px 0; border-radius:3px; background:rgba(0,0,0,0.5); border:1px solid ";
if (gw.proto === 'DMR' && gwData['DMR_NETS'] && gwData['DMR_NETS'].length > 0) {
gwData['DMR_NETS'].forEach(netName => { let netSuffix = (action === 'linking') ? ' [LNK]' : (action === 'failed' ? ' [ERR]' : (dest && action !== 'status' ? `:${dest}` : '')); gwHtml += `<span style="font-size:0.65rem; font-family:'JetBrains Mono', monospace; font-weight:400; padding:2px 4px; border:1px dashed ${badgeBorder}; background:transparent; color:${badgeColor} !important; margin-right: 4px; display: inline-block;">DMR:${esc(netName)}${esc(netSuffix)}</span>`; });
} else { gwHtml += `<span style="font-size:0.65rem; font-family:'JetBrains Mono', monospace; font-weight:400; padding:2px 4px; border:1px dashed ${badgeBorder}; background:transparent; color:${badgeColor} !important; margin-right: 4px; display: inline-block;">${gw.label}${esc(suffix)}</span>`; }
gwData['DMR_NETS'].forEach(netName => {
let tagStatus = (action === 'linking') ? '<span style="color:#f59e0b;font-weight:700;">LNK</span>' : (action === 'failed' ? '<span style="color:var(--danger);font-weight:700;">ERR</span>' : (dest && action !== 'status' ? `<span style="color:#ffffff;font-weight:600;">${esc(dest)}</span>` : ''));
gwHtml += `<span style="${chipBase}${badgeBorder};"><b style="color:${gw.color};">DMR</b><span style="color:#e2e8f0;">${esc(netName)}</span>${tagStatus ? '<span style="color:var(--text-muted);opacity:0.6;">·</span>' + tagStatus : ''}</span>`;
});
} else {
let destText = dest ? `<span style="color:#ffffff; font-weight:600;">${esc(dest)}</span>` : '';
let statusPill = '';
if (action === 'linking') statusPill = '<span style="color:#f59e0b; font-weight:700;">LNK</span>';
else if (action === 'failed') statusPill = '<span style="color:var(--danger); font-weight:700;">ERR</span>';
else if (action === 'unlinked') statusPill = '<span style="color:var(--text-muted);">UNL</span>';
let content = `<b style="color:${gw.color};">${gw.label}</b>`;
if (destText) content += `<span style="color:var(--text-muted);opacity:0.6;">·</span>${destText}`;
if (statusPill) content += `<span style="color:var(--text-muted);opacity:0.6;">·</span>${statusPill}`;
gwHtml += `<span style="${chipBase}${badgeBorder};">${content}</span>`;
}
}
});
}
@@ -864,16 +990,7 @@ async function refreshStates() {
if (healthContainer) healthContainer.style.display = 'none';
}
// Logica tollerante per i Gateway in standby (spenti dalla UI)
let hasOfflineService = false;
if (healthObj && healthObj.processes) {
for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) {
let s = svcStatus.toLowerCase();
if (s !== 'online' && s !== 'standby') {
hasOfflineService = true; break;
}
}
}
// Logica tollerante per i Gateway in standby (hasOfflineService calcolato in alto)
const warnBadge = document.getElementById(`svc-warn-${c.id}`); const btnSvc = document.getElementById(`btn-svc-${c.id}`);
if (warnBadge) warnBadge.style.display = hasOfflineService ? 'block' : 'none';
if (btnSvc) { if (hasOfflineService) { btnSvc.style.borderColor = 'var(--danger)'; btnSvc.style.color = 'var(--danger)'; } else { btnSvc.style.borderColor = 'var(--text-main)'; btnSvc.style.color = 'var(--text-main)'; } }
@@ -892,8 +1009,8 @@ async function refreshStates() {
}
// --- NESSUN TIMER LOCALE: COMANDA MQTT ---
// Memorizza l'ultimo modo in trasmissione per usarlo durante l'Hangtime
if (isTx && isOnline) {
// Memorizza l'ultimo modo dedotto per usarlo durante l'Hangtime o i Beacon
if (!isIdle && isOnline) {
cardDiv.dataset.lastMode = txModeStr.replace("TX ", "").trim();
cardDiv.dataset.lastColor = activeModeColor;
}
@@ -901,6 +1018,10 @@ async function refreshStates() {
// Se non è in TX e MMDVM NON ha ancora dichiarato 'idle' -> siamo in Hold
let isHold = (!isTx && !isIdle && isOnline);
// Salviamo lo stato sul DOM per la mappa
cardDiv.dataset.isTx = isTx ? 'true' : 'false';
cardDiv.dataset.isHold = isHold ? 'true' : 'false';
let holdMode = cardDiv.dataset.lastMode || "DMR";
let holdColor = cardDiv.dataset.lastColor || "var(--primary)";
@@ -957,6 +1078,7 @@ async function refreshStates() {
const miniStatus = document.getElementById(`mini-status-${c.id}`);
const miniName = document.getElementById(`mini-name-${c.id}`);
const miniId = document.getElementById(`mini-id-${c.id}`);
const miniCaller = document.getElementById(`mini-caller-${c.id}`);
if (miniCard && miniStatus) {
if (genObj && isOnline) {
@@ -968,12 +1090,35 @@ async function refreshStates() {
miniCard.style.opacity = "1";
miniCard.style.filter = "none";
if (miniCaller) {
let activeCaller = "";
if (isTx) {
let rawStr = (telemetryObj.alt && telemetryObj.alt !== "") ? telemetryObj.alt : ((String(telemetryObj.ts1 ?? '').includes("🎙️") || String(telemetryObj.ts1 ?? '').includes("TX")) ? String(telemetryObj.ts1) : String(telemetryObj.ts2 ?? ''));
// Rimuove emoji, prefissi come "D-Star:", "YSF:" e pulisce
let cleaned = rawStr.replace(/[^\x00-\x7F]/g, '')
.replace(/(TX)?\s*(D-STAR|YSF|NXDN|P25|DMR|FM|M17)\s*:/ig, '')
.replace(/TX/ig, '')
.trim();
if (cleaned) activeCaller = cleaned.split(' ')[0];
}
if (isTx && activeCaller) {
miniCaller.innerText = activeCaller;
miniCaller.style.display = "block";
miniCaller.style.color = activeModeColor;
} else {
miniCaller.style.display = "none";
miniCaller.innerText = "";
}
}
if (warns.length > 0 && !isTx && !isHold) {
miniCard.style.borderColor = "var(--accent)";
miniStatus.innerText = "(!) ALERT";
miniStatus.title = warns.join(" | ");
miniStatus.style.color = "var(--accent)";
miniStatus.style.borderColor = "var(--accent)";
miniCard.style.boxShadow = 'none';
} else {
let mcBorder = "var(--border-main)";
let mStatus = stateValue;
@@ -985,11 +1130,15 @@ async function refreshStates() {
mStatus = `( ${txModeStr} )`;
mColor = activeModeColor;
mBorderColor = activeModeColor;
miniCard.style.boxShadow = `0 0 12px ${activeModeColor}60`; // GLOW in TX
} else if (isHold) {
mcBorder = holdColor;
mcBorder = "var(--border-main)"; // Bordo grigio per non confonderlo con TX
mStatus = `[ ${holdMode} ]`;
mColor = holdColor;
mBorderColor = holdColor;
mColor = holdColor; // Solo testo colorato
mBorderColor = "var(--border-light)";
miniCard.style.boxShadow = 'none'; // Nessun glow in hold
} else {
miniCard.style.boxShadow = 'none';
}
miniCard.style.borderColor = mcBorder;
@@ -1006,6 +1155,7 @@ async function refreshStates() {
miniStatus.title = "OFFLINE";
miniStatus.style.color = "var(--danger)";
miniStatus.style.borderColor = "var(--border-light)";
miniCard.style.boxShadow = 'none';
}
}
@@ -1085,6 +1235,7 @@ async function refreshStates() {
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--primary); color: var(--primary) !important;" onclick="openVersionsModal('${c.id}')">[ INFO ]</button>`;
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--text-main);" onclick="openServicesModal('${c.id}')">[ SVC ]</button>`;
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--accent); color: var(--accent) !important;" onclick="openConfigsModal('${c.id}')">[ CFG ]</button>`;
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--success); color: var(--success) !important;" onclick="openLogModal('${c.id}')">[ LOG ]</button>`;
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--danger); color: var(--danger) !important;" onclick="confirmHatReset('${c.id}')">[ HAT ]</button>`;
btnHtml += `<button class="btn-cmd" style="padding: 12px 25px; font-size: 1.1rem; flex: none; width: auto; border-color: var(--danger); color: var(--danger) !important;" onclick="confirmReboot('${c.id}')">[ RBT ]</button>`;
let otaColor = (healthObj && healthObj.agent_update_available) ? 'var(--danger)' : 'var(--primary)';
@@ -1122,11 +1273,98 @@ async function refreshAprs() {
let html = "";
logs.forEach(msg => {
html += formatAprsRow(msg);
plotAprsOnMap(msg); // Popola mappa all'avvio
});
tbody.innerHTML = html;
} catch (e) { console.error(e); }
}
function parseAprsPosition(payload) {
// Cerca pattern standard APRS (es. 4603.25N/01315.60E)
const posRegex = /([0-9]{2})([0-9]{2}\.[0-9]{1,2})([NS])(.)([0-1][0-9]{2})([0-9]{2}\.[0-9]{1,2})([EOW])/i;
const match = payload.match(posRegex);
if (match) {
let latDeg = parseInt(match[1], 10);
let latMin = parseFloat(match[2]);
let lat = latDeg + (latMin / 60.0);
if (match[3].toUpperCase() === 'S') lat = -lat;
let lonDeg = parseInt(match[5], 10);
let lonMin = parseFloat(match[6]);
let lon = lonDeg + (lonMin / 60.0);
if (match[7].toUpperCase() === 'W' || match[7].toUpperCase() === 'O') lon = -lon;
return { lat, lon };
}
return null;
}
function plotAprsOnMap(msg) {
const pos = parseAprsPosition(msg.payload);
if (!pos) return;
const source = msg.source;
const sourceBase = source.split('-')[0].toLowerCase();
// Escludiamo dalla mappa i pacchetti provenienti dai nodi della flotta
let isFleetNode = false;
for (let i = 0; i < clients.length; i++) {
let cid = clients[i].id.toLowerCase();
let cname = (clients[i].name || "").split('-')[0].toLowerCase();
let ccall = "";
if (latestStatesData && latestStatesData.general && latestStatesData.general[cid]) {
ccall = (latestStatesData.general[cid].callsign || "").split('-')[0].toLowerCase();
}
if (sourceBase === cid || sourceBase === cname || (ccall && sourceBase === ccall)) {
isFleetNode = true;
break;
}
}
if (isFleetNode) return;
if (aprsMarkers[source] && fleetMap) {
fleetMap.removeLayer(aprsMarkers[source].marker);
}
const customIcon = L.divIcon({
className: 'custom-div-icon',
html: `<div style="width: 14px; height: 14px; background-color: #f97316; border-radius: 50%; border: 2px solid #04102e; box-shadow: 0 0 10px rgba(249, 115, 22, 0.8);"></div>`,
iconSize: [14, 14],
iconAnchor: [7, 7]
});
const popupContent = `
<div style="font-family: 'JetBrains Mono', monospace; min-width: 150px;">
<div style="font-weight: bold; color: #f97316; margin-bottom: 5px;">${esc(source)} <span style="font-size:0.7rem; color:var(--text-muted);">(APRS)</span></div>
<div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 5px;">${esc(msg.time)} via ${esc(msg.path.split(',')[0])}</div>
<div style="font-size: 0.75rem; color: var(--text-main); word-wrap: break-word; margin-bottom: 8px;">${esc(msg.payload)}</div>
<a href="https://aprs.fi/info/a/${encodeURIComponent(source)}" target="_blank" class="btn-cmd" style="padding: 2px 6px; font-size: 0.7rem; width: 100%; border-color: #f97316; color: #f97316 !important; text-align: center; text-decoration: none; display: block; box-sizing: border-box;">[ APRS.FI ]</a>
</div>
`;
const marker = L.marker([pos.lat, pos.lon], { icon: customIcon }).bindPopup(popupContent);
aprsMarkers[source] = {
marker: marker,
timestamp: Date.now()
};
if (fleetMap) {
marker.addTo(fleetMap);
}
}
function cleanupAprsMarkers() {
const now = Date.now();
for (const [src, data] of Object.entries(aprsMarkers)) {
if (now - data.timestamp > 7200000) { // 2 ore
if (fleetMap) fleetMap.removeLayer(data.marker);
delete aprsMarkers[src];
}
}
}
function formatAprsRow(msg) {
const time = msg.time || new Date().toLocaleTimeString('it-IT', { hour12: false });
const srcHtml = `<a href="https://aprs.fi/info/a/${encodeURIComponent(msg.source)}" target="_blank" style="color: var(--success); text-decoration: none;">${esc(msg.source)}</a>`;
@@ -1149,6 +1387,7 @@ function addLiveAprs(msg) {
if (tbody.children.length > 100) {
tbody.removeChild(tbody.lastChild);
}
plotAprsOnMap(msg);
}
async function refreshLogs() {
@@ -1265,9 +1504,18 @@ async function checkPushStatus() {
function urlB64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i); return outputArray; }
async function checkServerUpdate() {
async function checkServerUpdate(force = false) {
if (!isAuthenticated || me.role !== 'admin') return;
try { const res = await fetch('/api/server_update/check'); const data = await res.json(); const btn = document.getElementById('server-update-btn'); if (btn) { btn.style.display = data.update_available ? 'inline-block' : 'none'; } } catch (e) { console.error(e); }
try {
const url = force ? '/api/server_update/check?force=1' : '/api/server_update/check';
const res = await fetch(url);
if (!res.ok) return;
const data = await res.json();
const btn = document.getElementById('server-update-btn');
if (btn) {
btn.style.display = data.update_available ? 'inline-block' : 'none';
}
} catch (e) { console.error(e); }
}
function confirmServerUpdate() {
@@ -1281,10 +1529,126 @@ const refreshStatesSoon = debounce(refreshStates, 300);
const refreshLogsSoon = debounce(() => { refreshLogs(); refreshStats(); }, 500);
if (typeof io !== 'undefined') {
const socket = io();
socket.on('mqtt_status', function(data) { const badge = document.getElementById('mqtt-badge'); if (badge) { if (data.connected) { badge.innerText = "MQTT: OK"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: ERR"; badge.className = "mqtt-badge mqtt-offline"; } } });
socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); });
socket.on('dati_aggiornati', refreshStatesSoon);
socket.on('log_aggiornato', refreshLogsSoon);
socket.on('aprs_msg', function(data) { addLiveAprs(data); });
window.socket = io();
window.socket.on('mqtt_status', function(data) { const badge = document.getElementById('mqtt-badge'); if (badge) { if (data.connected) { badge.innerText = "MQTT: OK"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: ERR"; badge.className = "mqtt-badge mqtt-offline"; } } });
window.socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); });
window.socket.on('dati_aggiornati', refreshStatesSoon);
window.socket.on('log_aggiornato', refreshLogsSoon);
window.socket.on('aprs_msg', function(data) { addLiveAprs(data); });
window.socket.on('web_users_count', function(data) {
const el = document.getElementById('active-users-count');
if (el && data && data.count !== undefined) {
el.innerText = data.count;
}
if (data && data.users) {
activeLoggedUsers = data.users;
}
});
}
// --- LOGICA ANALYTICS E CHART.JS ---
let hwChart = null;
let rfChart = null;
let currentAnalyticsHours = 24;
Chart.defaults.color = 'rgba(255, 255, 255, 0.6)';
Chart.defaults.font.family = "'JetBrains Mono', monospace";
function setAnalyticsTimeframe(hours) {
currentAnalyticsHours = hours;
// Update active class on pills
[12, 24, 48, 168].forEach(h => {
const btn = document.getElementById('btn-ana-' + h);
if (btn) {
if (h === hours) btn.classList.add('active');
else btn.classList.remove('active');
}
});
// Update label text
const labelEl = document.getElementById('analytics-time-label');
if (labelEl) {
labelEl.innerText = hours === 168 ? '7D' : hours + 'H';
}
// Reload data
loadNodeAnalytics();
}
async function loadNodeAnalytics() {
if (!currentFocusedNode) return;
try {
const res = await fetch(`/api/analytics/${currentFocusedNode}?hours=${currentAnalyticsHours}`);
const data = await res.json();
if (!data.success) return;
// Dati Telemetria (Ore o Giorni/Ore)
const formatLabel = (dTime) => {
if (currentAnalyticsHours > 48) {
const parts = dTime.split(' ');
const dateParts = parts[0].split('-'); // YYYY-MM-DD
return `${dateParts[2]}/${dateParts[1]} ${parts[1].substring(0, 5)}`;
}
return dTime.split(' ')[1].substring(0, 5);
};
const hwLabels = data.telemetry.map(d => formatLabel(d.time));
const tempD = data.telemetry.map(d => d.temp);
const cpuD = data.telemetry.map(d => d.cpu);
if (hwChart) hwChart.destroy();
const ctxHw = document.getElementById('chart-hw').getContext('2d');
hwChart = new Chart(ctxHw, {
type: 'line',
data: {
labels: hwLabels,
datasets: [
{ label: t('chartTemp'), data: tempD, borderColor: '#ef4444', backgroundColor: 'rgba(239,68,68,0.1)', fill: true, tension: 0.3, yAxisID: 'y' },
{ label: t('chartCpu'), data: cpuD, borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.1)', fill: true, tension: 0.3, yAxisID: 'y1' }
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: true, position: 'top' } },
scales: {
x: { grid: { color: 'rgba(255,255,255,0.05)' } },
y: { type: 'linear', display: true, position: 'left', grid: { color: 'rgba(255,255,255,0.05)' }, min: 20 },
y1: { type: 'linear', display: true, position: 'right', grid: { drawOnChartArea: false }, min: 0, max: 100 }
}
}
});
// Dati RF
const rfLabels = data.rf.map(d => formatLabel(d.time));
const countD = data.rf.map(d => d.count);
const berD = data.rf.map(d => d.ber);
if (rfChart) rfChart.destroy();
const ctxRf = document.getElementById('chart-rf').getContext('2d');
rfChart = new Chart(ctxRf, {
type: 'bar',
data: {
labels: rfLabels,
datasets: [
{ label: t('chartTransits'), data: countD, backgroundColor: '#10b981', yAxisID: 'y' },
{ label: t('chartBer'), data: berD, type: 'line', borderColor: '#f59e0b', backgroundColor: 'transparent', tension: 0.3, yAxisID: 'y1' }
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: true, position: 'top' } },
scales: {
x: { grid: { color: 'rgba(255,255,255,0.05)' } },
y: { type: 'linear', display: true, position: 'left', grid: { color: 'rgba(255,255,255,0.05)' }, min: 0 },
y1: { type: 'linear', display: true, position: 'right', grid: { drawOnChartArea: false }, min: 0 }
}
}
});
} catch (e) { console.error("Error loading analytics:", e); }
}
+667 -41
View File
@@ -2,6 +2,17 @@
const i18n = {
en: {
lblLogLimit: "Rows:",
btnSched: "SCHED", ttSchedule: "Calendar Profile Scheduler", schedTitle: "CALENDAR PROFILE SCHEDULER",
schedNew: "NEW SCHEDULED EVENT", lblSchedTitle: "Event Name:", lblSchedNodes: "Target Nodes:",
lblSchedTargetProf: "Target Profile:", lblSchedRestoreProf: "Restore Profile:",
lblSchedStart: "Start Date/Time:", lblSchedEnd: "End Date/Time:", btnAddSched: "CREATE SCHEDULE",
thSchedTitle: "Title", thSchedNodes: "Nodes", thSchedProf: "Profile", thSchedStart: "Start",
thSchedEnd: "End", thSchedStatus: "Status", thSchedActs: "Actions",
statusScheduled: "SCHEDULED", statusActive: "ACTIVE", statusCompleted: "COMPLETED", statusCancelled: "CANCELLED", statusExpired: "EXPIRED",
confCancelSched: "Cancel this scheduled event?", msgSchedCreated: "SCHEDULE CREATED", msgSchedCancelled: "SCHEDULE CANCELLED",
errSchedDates: "End date must be after start date!", errMissingSchedData: "Please fill all required fields!",
optAllNodes: "ALL NODES (FLEET)", optNone: "NONE (Leave current)",
lastTransits: "Lastheard", loginTitle: "SYSTEM_LOGIN",
thTime: "Time", thRep: "Repeater", thMode: "Mode", thCall: "Callsign", thDur: "Duration",
thUser: "User", thRole: "Role", thNodes: "Nodes", thActs: "Actions",
@@ -30,39 +41,72 @@ const i18n = {
ttSwitchTo: "SW_TO: ", ttSvcStart: "START", ttSvcRestart: "RST", ttSvcEdit: "EDIT", ttSvcStop: "STOP", ttLang: "LANG",
statTopTG: "TOP_TG", statTopCall: "TOP_CALL", statLoading: "LOADING...", statAvgDur: "AVG_DUR", statTodayTx: "TX_TODAY", statNoData: "NO_DATA",
statTitle: "DAILY_STATS", statAllNodes: "ALL_NODES", modVersions: "SW_VERSIONS",
filtAll: "ALL_NODES", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "ALERTS"
filtAll: "ALL_NODES", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "ALERTS",
fleetStatus: "[ FLEET_STATUS ]", aprsTraffic: "[ APRS_TRAFFIC ]", btnClear: "[ CLEAR ]", btnReturn: "[ < RETURN TO OVERVIEW ]",
hwTelemetry: "[ HARDWARE_TELEMETRY ]", rfConfig: "[ RF_CONFIGURATION ]", opModes: "[ OPERATING_MODES ]", actGateways: "[ ACTIVE_GATEWAYS ]",
tsModes: "[ TIMESLOTS_MODES ]", liveTerminal: "[ LIVE_TERMINAL ]", nodeLastheard: "[ NODE_LASTHEARD ]", adminControls: "[ ADMIN_CONTROLS ]",
cpuLoad: "CPU_LOAD:", sysTemp: "SYS_TEMP:", ramUsage: "RAM_USAGE:", diskSpace: "DISK_SPACE:", sysUptime: "UPTIME:",
txFreq: "TX_FREQ:", rxFreq: "RX_FREQ:", nodeLoc: "LOCATION:",
statusOffline: "OFFLINE", statusAlert: "(!) ALERT", awaitingStream: "> AWAITING_STREAM...", focusNode: "FOCUS_NODE", noActiveGw: "NO_ACTIVE_GATEWAYS",
lblSysUptime: "System Uptime", lblSwVersions: "Software Versions", lblOtaUpdate: "OTA Update", waitConfig: "WAITING FOR CONFIG...",
noDaemonData: "NO DAEMON DATA YET. RETRYING...", cfgEmpty: "[!] CFG MEMORY EMPTY", netError: "NETWORK ERROR", noModesFound: "NO MODES FOUND IN CONFIG",
accessDenied: "[ ACCESS DENIED ]", savingRestart: "⏳ SAVING & RESTARTING...", stateUpdated: "✅ STATE UPDATED SUCCESSFULLY!",
phSearch: "SEARCH ID/CALL...", btnGrid: "[ GRID ]", btnList: "[ LIST ]"
},
it: {
lblLogLimit: "Righe:",
lastTransits: "Ultimi ascolti", loginTitle: "SYSTEM_LOGIN",
btnSched: "SCHED", ttSchedule: "Pianificazione Calendario Profili", schedTitle: "CALENDARIO PIANIFICAZIONE PROFILI",
schedNew: "NUOVO EVENTO PROGRAMMATO", lblSchedTitle: "Nome Evento:", lblSchedNodes: "Nodi Coinvolti:",
lblSchedTargetProf: "Profilo Attivazione:", lblSchedRestoreProf: "Profilo Ripristino:",
lblSchedStart: "Data/Ora Inizio:", lblSchedEnd: "Data/Ora Fine:", btnAddSched: "CREA PIANIFICAZIONE",
thSchedTitle: "Titolo", thSchedNodes: "Nodi", thSchedProf: "Profilo", thSchedStart: "Inizio",
thSchedEnd: "Fine", thSchedStatus: "Stato", thSchedActs: "Azioni",
statusScheduled: "PROGRAMMATO", statusActive: "ATTIVO", statusCompleted: "COMPLETATO", statusCancelled: "ANNULLATO", statusExpired: "SCADUTO",
confCancelSched: "Annullare questo evento programmato?", msgSchedCreated: "PIANIFICAZIONE CREATA", msgSchedCancelled: "PIANIFICAZIONE ANNULLATA",
errSchedDates: "La data di fine deve essere successiva a quella di inizio!", errMissingSchedData: "Compilare tutti i campi obbligatori!",
optAllNodes: "TUTTI I NODI (FLOTTA)", optNone: "NESSUNO (Mantieni attivo)",
lastTransits: "Ultimi ascolti", loginTitle: "ACCESSO SISTEMA",
thTime: "Ora", thRep: "Ripetitore", thMode: "Modo", thCall: "Nominativo", thDur: "Durata",
thUser: "Utente", thRole: "Ruolo", thNodes: "Nodi", thActs: "Azioni",
btnReqCfg: "REQ_CFG", btnGlobal: "GBL_OVR", btnAdmin: "SYS_ADM", btnPass: "CHG_PWD", btnLogout: "LOGOUT",
btnSvc: "SVC", btnFile: "CFG", btnBoot: "REBOOT", btnAdd: "ADD",
waitNet: "> Attesa rete...", waitData: "In attesa dei dati dal nodo...", forceUpdate: "FORCE_UPD",
adminTitle: "SYS_ADMIN", adminDBSync: "DB_SYNC_CFG", adminTime: "Orario Aggiornamento:", adminSave: "SAVE_CFG", roleOp: "Operatore",
modSvcTitle: "DAEMONS:", modFileTitle: "CFG_FILES", modEditTitle: "EDIT:",
warnEdit: "[WARN] DIRECT EDIT ACTIVE",
btnEdit: "EDIT", btnStart: "START", btnRestart: "RST", btnStop: "STOP", btnSave: "WRITE_FILE",
btnHat: "RST_HAT", confHat: "PHYSICAL RESET MMDVM ON: ",
confOta: "ESEGUIRE GIT PULL SUL NODO ",
btnReqCfg: "REQ_CFG", btnGlobal: "GBL_OVR", btnAdmin: "SYS_ADM", btnPass: "CHG_PWD", btnLogout: "ESCI",
btnSvc: "SERVIZI", btnFile: "CFG", btnBoot: "RIAVVIA", btnAdd: "AGGIUNGI",
waitNet: "> Attesa rete...", waitData: "In attesa dei dati dal nodo...", forceUpdate: "FORZA AGGIORNAMENTO",
adminTitle: "AMMINISTRAZIONE SISTEMA", adminDBSync: "SINCRONIZZAZIONE DB", adminTime: "Orario Aggiornamento:", adminSave: "SALVA CONFIG", roleOp: "Operatore",
modSvcTitle: "DEMONI:", modFileTitle: "FILE CONFIGURAZIONE", modEditTitle: "MODIFICA:",
warnEdit: "[ATTENZIONE] MODIFICA DIRETTA ATTIVA",
btnEdit: "MODIFICA", btnStart: "AVVIA", btnRestart: "RIAVVIA", btnStop: "FERMA", btnSave: "SALVA FILE",
btnHat: "RESET HAT", confHat: "Reset hardware modem MMDVM su: ",
confOta: "Eseguire git pull sul nodo ",
confOp: "Confermi l'operazione su ", confTgOn: "Vuoi ATTIVARE le notifiche Telegram per il nodo ", confTgOff: "Vuoi SILENZIARE le notifiche Telegram per il nodo ", confOvr: "Sei sicuro di voler sovrascrivere il file su ",
warnDaemon: "[WARN] DAEMON OFFLINE",
promptOvr: "GBL_OVR", promptOvrConfirm: "Confermi l'invio a TUTTA la rete?",
modUpdateTitle: "GBL_UPDATE", confUpdate: "Vuoi richiedere i dati e i file di configurazione aggiornati a tutti i nodi della flotta?", alertUpdateOk: "ACK",
btnConfReset: "CONFIRM", btnCancel: "ABORT", promptPass: "NEW PWD:",
titleError: "ERR", titleSuccess: "OK", titleAction: "CONFIRM", titleDelete: "DEL_USR", titleSave: "SAVE", titleGlobal: "GBL_OVR",
btnYes: "EXECUTE", msgDelUser: "DELETE USER?", msgPassOk: "PWD_UPDATED", msgPassErr: "PWD_ERR", msgLoginFail: "AUTH_FAIL",
msgConfigSaved: "CFG_SAVED", msgConfigErr: "CFG_ERR", msgNetErr: "NET_ERR", msgOvrSel: "SELECT_PROF:",
msgOvrOk: "CMD_BROADCASTED", msgMissUser: "MISSING_USR", msgMissPass: "MISSING_PWD", btnSvcKo: "DAEMON_ERR",
phNewPass: "NEW_PWD (EMPTY=KEEP)", phPass: "PWD",
titleSwitch: "SW_PROF", confSwitch: "SWITCH TO ", titleBoot: "SYS_REBOOT", confBoot: "REBOOT NODE ",
ttReqCfg: "REQ_DATA", ttGlobal: "GBL_OVR", ttAdmin: "ADMIN", ttPass: "CHG_PWD", ttLogout: "LOGOUT",
warnDaemon: "[ATTENZIONE] DEMONE OFFLINE",
promptOvr: "OVERRIDE GLOBALE", promptOvrConfirm: "Confermi l'invio a TUTTA la rete?",
modUpdateTitle: "AGGIORNAMENTO FLOTTA", confUpdate: "Vuoi richiedere i dati e i file di configurazione aggiornati a tutti i nodi della flotta?", alertUpdateOk: "CONFERMATO",
btnConfReset: "CONFERMA", btnCancel: "ANNULLA", promptPass: "NUOVA PASSWORD:",
titleError: "ERRORE", titleSuccess: "OK", titleAction: "CONFERMA", titleDelete: "ELIMINA UTENTE", titleSave: "SALVA", titleGlobal: "OVERRIDE GLOBALE",
btnYes: "ESEGUI", msgDelUser: "Eliminare definitivamente l'utente?", msgPassOk: "PASSWORD AGGIORNATA", msgPassErr: "ERRORE AGGIORNAMENTO PASSWORD", msgLoginFail: "CREDENZIALI NON VALIDE",
msgConfigSaved: "CONFIGURAZIONE SALVATA", msgConfigErr: "ERRORE SALVATAGGIO CONFIG", msgNetErr: "ERRORE DI RETE", msgOvrSel: "SELEZIONA PROFILO:",
msgOvrOk: "COMANDO INVIATO ALLA RETE", msgMissUser: "SPECIFICARE NOME UTENTE", msgMissPass: "SPECIFICARE PASSWORD", btnSvcKo: "ERRORE DEMONE",
phNewPass: "NUOVA PWD (VUOTA = INVARIATA)", phPass: "PASSWORD",
titleSwitch: "CAMBIO PROFILO", confSwitch: "Passa al profilo ", titleBoot: "RIAVVIO NODO", confBoot: "Riavviare il nodo ",
ttReqCfg: "Richiedi dati nodi", ttGlobal: "Override globale profili", ttAdmin: "Pannello amministrazione", ttPass: "Cambia password", ttLogout: "Disconnetti",
ttProfA: "Passa al Profilo A", ttProfB: "Passa al Profilo B", ttTgOn: "Abilita notifiche Telegram", ttTgOff: "Disabilita notifiche Telegram", ttSvc: "Gestisci demoni di sistema", ttFile: "Modifica file .ini da remoto", ttHat: "Reset fisico scheda modem", ttBoot: "Riavvia sistema operativo",
ttSwitchTo: "SW_TO: ", ttSvcStart: "START", ttSvcRestart: "RST", ttSvcEdit: "EDIT", ttSvcStop: "STOP", ttLang: "LANG",
statTopTG: "TOP_TG", statTopCall: "TOP_CALL", statLoading: "LOADING...", statAvgDur: "AVG_DUR", statTodayTx: "TX_TODAY", statNoData: "NO_DATA",
statTitle: "DAILY_STATS", statAllNodes: "ALL_NODES", modVersions: "SW_VERSIONS",
filtAll: "ALL_NODES", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "ALERTS"
ttSwitchTo: "Passa a: ", ttSvcStart: "Avvia demone", ttSvcRestart: "Riavvia demone", ttSvcEdit: "Modifica configurazione", ttSvcStop: "Arresta demone", ttLang: "Lingua",
statTopTG: "TOP TALKGROUP", statTopCall: "TOP NOMINATIVI", statLoading: "CARICAMENTO...", statAvgDur: "DURATA MEDIA", statTodayTx: "PASSAGGI OGGI", statNoData: "NESSUN DATO",
statTitle: "STATISTICHE GIORNALIERE", statAllNodes: "TUTTI I NODI", modVersions: "VERSIONI SOFTWARE",
filtAll: "TUTTI I NODI", filtOnline: "ONLINE", filtOffline: "OFFLINE", filtAlerts: "AVVISI",
fleetStatus: "[ STATO FLOTTA ]", aprsTraffic: "[ TRAFFICO APRS ]", btnClear: "[ PULISCI ]", btnReturn: "[ < TORNA ALLA DASHBOARD ]",
hwTelemetry: "[ TELEMETRIA HARDWARE ]", rfConfig: "[ CONFIGURAZIONE RF ]", opModes: "[ MODI OPERATIVI ]", actGateways: "[ GATEWAY ATTIVI ]",
tsModes: "[ TIMESLOT E MODI ]", liveTerminal: "[ TERMINALE LIVE ]", nodeLastheard: "[ ULTIMI ASCOLTI NODO ]", adminControls: "[ CONTROLLI AMMINISTRATORE ]",
cpuLoad: "CARICO CPU:", sysTemp: "TEMP. SIS:", ramUsage: "UTILIZZO RAM:", diskSpace: "SPAZIO DISCO:", sysUptime: "ATTIVITÀ:",
txFreq: "FREQ. TX:", rxFreq: "FREQ. RX:", nodeLoc: "POSIZIONE:",
statusOffline: "OFFLINE", statusAlert: "(!) AVVISO", awaitingStream: "> IN ATTESA DI FLUSSO DATI...", focusNode: "DETTAGLI NODO", noActiveGw: "NESSUN GATEWAY ATTIVO",
lblSysUptime: "Tempo di attività sistema", lblSwVersions: "Versioni Software", lblOtaUpdate: "Aggiornamento OTA", waitConfig: "IN ATTESA DELLA CONFIGURAZIONE...",
noDaemonData: "NESSUN DATO DAL DEMONE. RETENTATIVO...", cfgEmpty: "[!] MEMORIA CFG VUOTA", netError: "ERRORE DI RETE", noModesFound: "NESSUN MODO TROVATO NELLA CONFIGURAZIONE",
accessDenied: "[ ACCESSO NEGATO ]", savingRestart: "⏳ SALVATAGGIO & RIAVVIO IN CORSO...", stateUpdated: "✅ STATO AGGIORNATO CON SUCCESSO!",
phSearch: "CERCA ID/CALL...", btnGrid: "[ GRIGLIA ]", btnList: "[ LISTA ]",
liveLogTitle: "[ LIVE_LOG: ", filterAll: "TUTTI I DEMONI", btnScrollOn: "SCROLL: ON", btnScrollOff: "SCROLL: OFF", btnClear: "PULISCI",
logConnWait: "Connessione in corso... In attesa dei log per ", logNoData: "Nessun log recente in memoria per ", logApplyFilter: "Applicazione filtro...", btnDownloadZip: "[ SCARICA_TUTTI_CFG_ZIP ]", lblHistory: "STORICO:", optCurrentUnsaved: "Attuale (Non salvata)", btnPreviewDiff: "[ ANTEPRIMA_DIFF ]", btnCancelDiff: "ANNULLA", titleAuditLogs: "[ LOG_SICUREZZA_AUDIT ]", btnRefresh: "AGGIORNA", btnRefreshBracket: "[ AGGIORNA ]", waitLoading: "In attesa di caricamento...", titleAnalytics: "[ ANALITICHE_NODO ]", msgNoAudit: "Nessun log di sicurezza presente.", msgNoModifications: "[ NESSUNA MODIFICA RILEVATA RISPETTO ALLA CONFIGURAZIONE ATTIVA ]", warnUnverifiedDiff: "Non hai verificato il Diff visivo. Sicuro di voler sovrascrivere?", chartTemp: "Temp °C", chartCpu: "CPU %", chartTransits: "Transiti", chartBer: "BER Medio %"
}
};
@@ -82,8 +126,13 @@ function applyTranslations() {
if (i18n[currentLang][key]) el.title = i18n[currentLang][key];
});
const newPassInput = document.getElementById('new-pass');
if (newPassInput && editingUserId) newPassInput.placeholder = t('phNewPass');
if (newPassInput && typeof editingUserId !== 'undefined' && editingUserId) newPassInput.placeholder = t('phNewPass');
else if (newPassInput) newPassInput.placeholder = t('phPass');
const searchInput = document.getElementById('node-search');
if (searchInput) searchInput.placeholder = t('phSearch') || 'SEARCH ID/CALL...';
if (typeof applyViewMode === 'function') applyViewMode();
}
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
@@ -152,7 +201,44 @@ async function executeUpdateRequest() {
}
// --- MODALE ADMIN & UTENTI ---
async function openAdmin() { document.getElementById('admin-modal').style.display = 'flex'; loadUsers(); loadSettings(); cancelEdit(); }
async function openAdmin() {
document.getElementById('admin-modal').style.display = 'flex';
// Inietto i bottoni operativi dentro l'header del pannello admin
let adminBtnsHtml = '';
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAllNodes = allowedList.includes('all');
const canOverride = hasAllNodes;
if (role === 'admin') {
adminBtnsHtml += `<button id="server-update-btn-modal" onclick="confirmServerUpdate(); closeAdmin();" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; display:none; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ UPD_SERVER ]</button>`;
adminBtnsHtml += `<button onclick="sendGlobalUpdate(); closeAdmin();" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ REQ_CFG ]</button>`;
}
if (role === 'admin' || role === 'node_admin') {
adminBtnsHtml += `<button onclick="openScheduleModal(); closeAdmin();" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ SCHED ]</button>`;
}
if (canOverride) {
adminBtnsHtml += `<button onclick="triggerGlobalEmergency(); closeAdmin();" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width:auto; padding: 4px 10px; font-size: 0.75rem;">[ GBL_OVR ]</button>`;
}
const adminActionDiv = document.getElementById('admin-action-btns');
if (adminActionDiv) {
adminActionDiv.innerHTML = adminBtnsHtml;
// Se siamo admin eseguiamo anche un check per l'update del server per mostrare/nascondere il tasto
if (role === 'admin' && typeof GLOBAL_SERVER_UPDATE_AVAILABLE !== 'undefined' && GLOBAL_SERVER_UPDATE_AVAILABLE) {
const upBtn = document.getElementById('server-update-btn-modal');
if(upBtn) upBtn.style.display = 'inline-block';
}
}
if (me.role === 'admin') {
loadUsers();
loadSettings();
cancelEdit();
}
loadAuditLogs();
}
function closeAdmin() { document.getElementById('admin-modal').style.display = 'none'; cancelEdit(); }
async function loadUsers() {
@@ -205,8 +291,13 @@ async function saveSettings() {
// --- GLOBAL OVERRIDE ---
function triggerGlobalEmergency() {
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAll = allowedList.includes('all');
let uniqueProfiles = {};
for (const id in globalHealthData) {
if (!hasAll && !allowedList.includes(id.toLowerCase())) continue;
if (globalHealthData[id] && globalHealthData[id].profiles) {
for (const [k, v] of Object.entries(globalHealthData[id].profiles)) { uniqueProfiles[k] = v; }
}
@@ -218,14 +309,36 @@ function triggerGlobalEmergency() {
idx++;
}
if (Object.keys(uniqueProfiles).length === 0) { html = `<p style="color:var(--danger); font-weight:400; font-family:'JetBrains Mono',monospace;">NO_PROFS_FOUND</p>`; }
container.innerHTML = html; document.getElementById('override-desc').innerText = t('msgOvrSel'); document.getElementById('override-modal').style.display = 'flex';
container.innerHTML = html;
const descText = hasAll ? t('msgOvrSel') : (currentLang === 'it' ? `SELEZIONA PROFILO (NODI ASSEGNATI: ${allowedList.length}):` : `SELECT PROFILE (NODES: ${allowedList.length}):`);
document.getElementById('override-desc').innerText = descText;
document.getElementById('override-modal').style.display = 'flex';
}
function sendGlobalAction(action) {
document.getElementById('override-modal').style.display = 'none';
customConfirm(t('titleGlobal'), t('promptOvrConfirm'), "var(--danger)", async () => {
try { const res = await fetch('/api/global_command', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({type: action}) }); const d = await res.json();
if(d.success) customAlert(t('titleSuccess'), t('msgOvrOk')); else customAlert(t('titleError'), esc(d.error), true); refreshStates();
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAll = allowedList.includes('all');
const confirmMsg = hasAll
? t('promptOvrConfirm')
: (currentLang === 'it'
? `Confermi l'invio ai tuoi nodi autorizzati (${allowedList.map(n => n.toUpperCase()).join(', ')})?`
: `Confirm sending to your authorized nodes (${allowedList.map(n => n.toUpperCase()).join(', ')})?`);
customConfirm(t('titleGlobal'), confirmMsg, "var(--danger)", async () => {
try {
const res = await fetch('/api/global_command', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({type: action})
});
const d = await res.json();
if(d.success) customAlert(t('titleSuccess'), t('msgOvrOk'));
else customAlert(t('titleError'), esc(d.error), true);
refreshStates();
} catch(e) { console.error(e); }
});
}
@@ -302,16 +415,29 @@ function controlService(clientId, service, action) {
});
}
// --- MODALE EDITOR INI ---
let currentEditClient = ""; let currentEditService = "";
// --- MODALE EDITOR INI E BACKUP HISTORY ---
let currentEditClient = ""; let currentEditService = ""; let currentOriginalConfig = ""; let isDiffMode = false;
let historyConfigs = {}; // Cache per i backup
async function openEditorModal(clientId, service) {
currentEditClient = clientId; currentEditService = service; document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`;
document.getElementById('config-textarea').value = "AWAITING_STREAM..."; document.getElementById('editor-status').innerText = ""; document.getElementById('editor-modal').style.display = 'flex';
currentEditClient = clientId; currentEditService = service; isDiffMode = false;
document.getElementById('editor-title').innerText = `${service.toUpperCase()} @ ${clientId.toUpperCase()}`;
document.getElementById('config-textarea').value = "AWAITING_STREAM...";
document.getElementById('config-textarea').style.display = 'block';
document.getElementById('diff-view').style.display = 'none';
document.getElementById('btn-cancel-diff').style.display = 'none';
document.getElementById('editor-status').innerText = "";
document.getElementById('editor-modal').style.display = 'flex';
document.getElementById('config-history-select').innerHTML = `<option value="">${t('optCurrentUnsaved')}</option>`;
historyConfigs = {};
try {
const res = await fetch(`/api/config_file/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`);
const data = await res.json();
if (data.success) {
document.getElementById('config-textarea').value = data.data.raw_text || "EMPTY";
currentOriginalConfig = data.data.raw_text || "";
document.getElementById('config-textarea').value = currentOriginalConfig;
fetchConfigHistory(clientId, service);
} else {
document.getElementById('config-textarea').value = "ERR:\n" + data.error;
}
@@ -319,18 +445,118 @@ async function openEditorModal(clientId, service) {
document.getElementById('config-textarea').value = "NET_ERR";
}
}
async function fetchConfigHistory(clientId, service) {
try {
const res = await fetch(`/api/config_backups/${encodeURIComponent(clientId)}/${encodeURIComponent(service)}`);
const data = await res.json();
if (data.success && data.backups.length > 0) {
const select = document.getElementById('config-history-select');
data.backups.forEach(b => {
const opt = document.createElement('option');
opt.value = b.id;
opt.text = `${b.timestamp} (${b.username})`;
select.appendChild(opt);
});
}
} catch(e) { console.error("History fetch error:", e); }
}
async function loadHistoryConfig() {
const val = document.getElementById('config-history-select').value;
if (!val) {
// Ripristina testualmente la versione corrente se scelgono "Attuale"
document.getElementById('config-textarea').value = currentOriginalConfig;
return;
}
if (historyConfigs[val]) {
document.getElementById('config-textarea').value = historyConfigs[val];
return;
}
try {
const res = await fetch(`/api/config_backups/${val}`);
const data = await res.json();
if (data.success) {
historyConfigs[val] = data.text;
document.getElementById('config-textarea').value = data.text;
}
} catch (e) { console.error(e); }
}
function previewConfigDiff() {
const newText = document.getElementById('config-textarea').value;
const diffView = document.getElementById('diff-view');
const textarea = document.getElementById('config-textarea');
if (isDiffMode) {
// Torna all'editor
textarea.style.display = 'block';
diffView.style.display = 'none';
document.getElementById('btn-cancel-diff').style.display = 'none';
isDiffMode = false;
return;
}
// Calcola il diff visivo
const dmp = new diff_match_patch();
const diffs = dmp.diff_main(currentOriginalConfig, newText);
dmp.diff_cleanupSemantic(diffs);
let html = "";
diffs.forEach(part => {
const type = part[0]; // -1 rimossa, 1 aggiunta, 0 uguale
const text = esc(part[1]);
if (type === 1) html += `<span style="background-color: rgba(46, 204, 113, 0.2); color: #2ecc71;">${text}</span>`;
else if (type === -1) html += `<span style="background-color: rgba(231, 76, 60, 0.2); color: #e74c3c; text-decoration: line-through;">${text}</span>`;
else html += `<span style="color: var(--text-muted); opacity: 0.8;">${text}</span>`;
});
if (diffs.length === 1 && diffs[0][0] === 0) {
html = `<span style="color: var(--success); font-weight: bold;">${t('msgNoModifications')}</span>\n\n` + html;
}
diffView.innerHTML = html;
textarea.style.display = 'none';
diffView.style.display = 'block';
document.getElementById('btn-cancel-diff').style.display = 'block';
isDiffMode = true;
}
function cancelDiff() {
document.getElementById('config-textarea').style.display = 'block';
document.getElementById('diff-view').style.display = 'none';
document.getElementById('btn-cancel-diff').style.display = 'none';
isDiffMode = false;
}
function closeEditorModal() { document.getElementById('editor-modal').style.display = 'none'; }
function saveConfig() {
const textValue = document.getElementById('config-textarea').value; const statusSpan = document.getElementById('editor-status');
customConfirm(t('titleSave'), `${t('confOvr')}<b>${currentEditClient.toUpperCase()}</b>?`, "var(--danger)", async () => {
const textValue = document.getElementById('config-textarea').value;
const statusSpan = document.getElementById('editor-status');
if (!isDiffMode && textValue !== currentOriginalConfig) {
customConfirm(t('titleSave'), t('warnUnverifiedDiff'), "var(--accent)", () => executeSave(textValue, statusSpan));
} else {
customConfirm(t('titleSave'), `${t('confOvr')}<b>${currentEditClient.toUpperCase()}</b>?`, "var(--danger)", () => executeSave(textValue, statusSpan));
}
}
async function executeSave(textValue, statusSpan) {
statusSpan.innerText = "WRITING..."; statusSpan.style.color = "var(--success)";
try {
const res = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: currentEditClient, service: currentEditService, config_data: { "raw_text": textValue } }) });
const data = await res.json();
if (data.success) { customAlert(t('titleSuccess'), "FILE_WRITTEN"); closeEditorModal(); } else { customAlert(t('titleError'), "ERR: " + esc(data.error), true); statusSpan.innerText = "ERR"; }
if (data.success) {
customAlert(t('titleSuccess'), "FILE_WRITTEN");
currentOriginalConfig = textValue; // Aggiorna l'originale corrente
closeEditorModal();
} else {
customAlert(t('titleError'), "ERR: " + esc(data.error), true); statusSpan.innerText = "ERR";
}
} catch(e) { customAlert(t('titleError'), t('msgNetErr'), true); statusSpan.innerText = "NET_ERR"; }
});
}
// --- MODALE VERSIONI SOFTWARE ---
@@ -341,3 +567,403 @@ function openVersionsModal(clientId) {
document.getElementById('versions-modal').style.display = 'flex';
}
function closeVersionsModal() { document.getElementById('versions-modal').style.display = 'none'; }
// -------------------- LIVE LOG MODAL --------------------
let currentLogClientId = null;
function openLogModal(clientId) {
currentLogClientId = clientId.toLowerCase();
document.getElementById('log-modal-title').innerText = clientId.toUpperCase();
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logConnWait')} ${clientId.toUpperCase()}...</span>\n`;
document.getElementById('log-modal').style.display = 'flex';
document.getElementById('log-service-filter').value = 'ALL';
// 1. Fetch initial logs
fetch(`/api/logs/${clientId}`)
.then(res => res.json())
.then(data => {
if (data.success && data.logs.length > 0) {
document.getElementById('log-console').innerHTML = '';
data.logs.forEach(log => appendLog(log));
} else {
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logNoData')} ${clientId.toUpperCase()}.</span>\n`;
}
})
.catch(err => console.error("Errore fetch logs:", err));
// 2. Subscribe WebSocket
window.socket.on('live_log_' + currentLogClientId, function(logEntry) {
appendLog(logEntry);
});
}
function closeLogModal() {
document.getElementById('log-modal').style.display = 'none';
if (currentLogClientId) {
window.socket.off('live_log_' + currentLogClientId);
}
currentLogClientId = null;
}
let autoScroll = true;
function toggleAutoScroll() {
autoScroll = !autoScroll;
const btn = document.getElementById('btn-autoscroll');
if (autoScroll) {
btn.innerText = t('btnScrollOn') || 'SCROLL: ON';
btn.style.borderColor = 'var(--accent)';
btn.style.setProperty('color', 'var(--accent)', 'important');
scrollToBottom();
} else {
btn.innerText = t('btnScrollOff') || 'SCROLL: OFF';
btn.style.borderColor = 'var(--text-muted)';
btn.style.setProperty('color', 'var(--text-muted)', 'important');
}
}
function clearLogs() {
document.getElementById('log-console').innerHTML = '';
}
function scrollToBottom() {
const box = document.getElementById('log-console');
box.scrollTop = box.scrollHeight;
}
function appendLog(log) {
const filter = document.getElementById('log-service-filter').value.toLowerCase();
const logSvc = log.service.toLowerCase();
if (filter !== 'all' && !logSvc.includes(filter)) {
return;
}
const box = document.getElementById('log-console');
let color = '#c9d1d9';
let prefix = log.service.toLowerCase();
if (prefix.includes('mmdvm')) color = '#58a6ff';
else if (prefix.includes('dmr')) color = '#3fb950';
else if (prefix.includes('ysf')) color = '#8b5cf6'; // Violetto per YSF
else if (prefix.includes('dstar') || prefix.includes('d-star')) color = '#f97316'; // Arancio per D-Star
else if (prefix.includes('nxdn')) color = '#10b981'; // Verde NXDN
else if (prefix.includes('p25')) color = '#ffcc00'; // Giallo P25
const span = document.createElement('div');
span.style.marginBottom = '2px';
const timeSpan = `<span style="color: #8b949e;">[${log.time}]</span>`;
const svcSpan = `<span style="color: ${color}; font-weight: bold;">[${log.service}]</span>`;
span.innerHTML = `${timeSpan} ${svcSpan} ${escapeHtml(log.text)}`;
// Remove default "Connessione in corso..." if present
if (box.innerHTML.includes(t('logConnWait'))) {
box.innerHTML = '';
}
box.appendChild(span);
// Keep max 1000 lines in DOM to prevent lag
if (box.childElementCount > 1000) {
box.removeChild(box.firstChild);
}
if (autoScroll) scrollToBottom();
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function renderLogs() {
// When filter changes, we just clear and wait for new logs, or we could refetch.
// For simplicity, we clear the console and fetch again from server.
if (currentLogClientId) {
document.getElementById('log-console').innerHTML = `<span style="color: #8b949e;">${t('logApplyFilter')}</span>\n`;
fetch(`/api/logs/${currentLogClientId}`)
.then(res => res.json())
.then(data => {
document.getElementById('log-console').innerHTML = '';
if (data.success) {
data.logs.forEach(log => appendLog(log));
}
});
}
}
// --- SECURITY AUDIT LOGS ---
async function loadAuditLogs() {
try {
const res = await fetch('/api/audit_logs');
const data = await res.json();
const container = document.getElementById('audit-logs-container');
if (data.success && data.logs) {
if (data.logs.length === 0) {
container.innerHTML = `<span style="color: var(--text-muted);">${t('msgNoAudit')}</span>`;
return;
}
let html = '';
data.logs.forEach(log => {
html += `<div style="border-bottom: 1px dashed var(--border-light); padding: 4px 0; display: flex; gap: 15px;">
<span style="color: var(--text-muted); flex: 0 0 140px;">[${log.time}]</span>
<span style="color: var(--primary); flex: 0 0 100px;">${esc(log.user.toUpperCase())}</span>
<span style="color: var(--success); flex: 0 0 80px;">${esc(log.node.toUpperCase())}</span>
<span style="color: var(--text-main); flex: 1;">${esc(log.cmd)}</span>
</div>`;
});
container.innerHTML = html;
}
} catch(e) { console.error("Error loading audit logs:", e); }
}
// --- MODALE CALENDARIO SCHEDULAZIONE PROFILI ---
async function openScheduleModal() {
document.getElementById('schedule-modal').style.display = 'flex';
populateScheduleNodeOptions();
loadSchedules();
// Inizializza le date con orari coerenti (Inizio: adesso + 5 min, Fine: adesso + 2 ore)
const now = new Date();
const in5m = new Date(now.getTime() + 5 * 60000);
const in2h = new Date(now.getTime() + 125 * 60000);
const toLocalISO = (d) => {
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
document.getElementById('sched-start').value = toLocalISO(in5m);
document.getElementById('sched-end').value = toLocalISO(in2h);
}
function closeScheduleModal() {
document.getElementById('schedule-modal').style.display = 'none';
}
function updateScheduleProfileOptions() {
const selNodes = document.getElementById('sched-nodes-select');
const selTarget = document.getElementById('sched-target-prof');
const selRestore = document.getElementById('sched-restore-prof');
if (!selNodes || !selTarget || !selRestore) return;
// Proviamo a estrarre i nomi dei profili dal primo nodo selezionato
const selectedCid = selNodes.value;
let profiles = { "A": "Profilo A", "B": "Profilo B" }; // Default
if (selectedCid !== 'all' && globalHealthData[selectedCid] && globalHealthData[selectedCid].profiles) {
profiles = globalHealthData[selectedCid].profiles;
} else {
// Se è 'all', cerchiamo il primo nodo disponibile che abbia i profili valorizzati
for (let cid in globalHealthData) {
if (globalHealthData[cid] && globalHealthData[cid].profiles && Object.keys(globalHealthData[cid].profiles).length > 0) {
profiles = globalHealthData[cid].profiles;
break;
}
}
}
// Aggiorniamo le select
let htmlTarget = "";
let htmlRestore = "";
for (const [pKey, pLabel] of Object.entries(profiles)) {
htmlTarget += `<option value="${pKey}">${pKey} (${esc(pLabel)})</option>`;
htmlRestore += `<option value="${pKey}">${pKey} (${esc(pLabel)})</option>`;
}
htmlRestore += `<option value="NONE" data-i18n="optNone">NONE (Leave active)</option>`;
// Salviamo i valori attuali se possibile per non resettarli
const currTarget = selTarget.value;
const currRestore = selRestore.value;
selTarget.innerHTML = htmlTarget;
selRestore.innerHTML = htmlRestore;
if(currTarget && [...selTarget.options].some(o => o.value === currTarget)) selTarget.value = currTarget;
if(currRestore && [...selRestore.options].some(o => o.value === currRestore)) selRestore.value = currRestore;
// Riapplichiamo le traduzioni per l'opzione NONE se in italiano
if (currentLang === 'it') {
const noneOpt = selRestore.querySelector('option[value="NONE"]');
if(noneOpt) noneOpt.innerText = "NESSUNO (Mantieni attivo)";
}
}
function populateScheduleNodeOptions() {
const sel = document.getElementById('sched-nodes-select');
if (!sel) return;
const role = me.role || '';
const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
const hasAll = allowedList.includes('all');
let html = '';
if (hasAll || role === 'admin') {
html += `<option value="all">${t('optAllNodes')}</option>`;
}
clients.forEach(c => {
if (hasAll || allowedList.includes(c.id.toLowerCase())) {
html += `<option value="${c.id}">${esc(c.name)} (${c.id.toUpperCase()})</option>`;
}
});
sel.innerHTML = html;
sel.addEventListener('change', updateScheduleProfileOptions);
updateScheduleProfileOptions();
}
async function loadSchedules() {
const tbody = document.getElementById('schedules-table-body');
if (!tbody) return;
try {
const res = await fetch('/api/schedules');
const data = await res.json();
if (!data.success || !data.schedules || data.schedules.length === 0) {
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:15px;">NO_SCHEDULES_FOUND</td></tr>`;
return;
}
tbody.innerHTML = data.schedules.map(s => {
let statusColor = "var(--text-muted)";
let statusClass = "";
let statusText = s.status;
if (s.status === 'SCHEDULED') {
statusColor = "#f59e0b";
statusText = t('statusScheduled');
} else if (s.status === 'ACTIVE') {
statusColor = "var(--success)";
statusClass = "blink";
statusText = t('statusActive');
} else if (s.status === 'COMPLETED') {
statusColor = "var(--text-muted)";
statusText = t('statusCompleted');
} else if (s.status === 'CANCELLED') {
statusColor = "var(--danger)";
statusText = t('statusCancelled');
} else if (s.status === 'EXPIRED') {
statusColor = "var(--text-muted)";
statusText = t('statusExpired');
}
const isFinished = ['COMPLETED', 'CANCELLED', 'EXPIRED'].includes(s.status);
// Tentativo di dedurre il profilo di partenza dal primo nodo o dai nodi target
let startProf = "?";
let cids = s.target_nodes.toLowerCase() === 'all' ? Object.keys(globalHealthData) : s.target_nodes.toLowerCase().split(',');
for (let i = 0; i < cids.length; i++) {
let cid = cids[i].trim();
let card = document.getElementById(`card-${cid}`);
if (card && card.dataset.lastMode) {
startProf = card.dataset.lastMode;
// Se leggiamo DMR o D-STAR non è un nome di profilo. Dobbiamo guardare se nel telemetry c'è una hint
let tel = latestStatesData && latestStatesData.telemetry && latestStatesData.telemetry[cid] ? latestStatesData.telemetry[cid] : {};
if(tel.alt && tel.alt.includes('SCHED:')) {
startProf = tel.alt.split(':')[1].trim();
}
break;
}
}
if (startProf === "?" || startProf.length > 5) startProf = "CURR"; // Current
let profDisplay = `<span style="color:var(--text-muted);">${esc(startProf)}</span> ➔ <b style="color:var(--accent);">${esc(s.target_profile)}</b>`;
if (s.restore_profile !== 'NONE') {
profDisplay += ` ➔ <span style="color:var(--success);">${esc(s.restore_profile)}</span>`;
}
return `<tr>
<td style="font-weight:bold; color:var(--text-main);">${esc(s.title)}</td>
<td><span style="color:var(--primary); font-family:'JetBrains Mono',monospace;">${esc(s.target_nodes.toUpperCase())}</span></td>
<td style="font-family:'JetBrains Mono',monospace;">${profDisplay}</td>
<td style="font-size:0.8rem; color:var(--text-muted);">${esc(s.start_time.substring(5, 16))}</td>
<td style="font-size:0.8rem; color:var(--text-muted);">${esc(s.end_time.substring(5, 16))}</td>
<td><span class="${statusClass}" style="color:${statusColor}; font-weight:bold; font-size:0.8rem;">[ ${statusText} ]</span></td>
<td style="text-align:right;">
${!isFinished ? `<button onclick="cancelSchedule(${s.id})" class="btn-cmd" style="border-color:var(--danger); color:var(--danger)!important; padding:4px 8px; font-size:0.75rem; width:auto; flex:none;">DEL</button>` : '—'}
</td>
</tr>`;
}).join('');
} catch(e) {
console.error("Error loading schedules:", e);
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; color:var(--danger); padding:15px;">NET_ERR</td></tr>`;
}
}
async function submitSchedule() {
const title = document.getElementById('sched-title').value.trim();
const targetNodes = document.getElementById('sched-nodes-select').value;
const targetProf = document.getElementById('sched-target-prof').value.trim().toUpperCase();
const restoreProf = document.getElementById('sched-restore-prof').value.trim().toUpperCase();
const startTime = document.getElementById('sched-start').value;
const endTime = document.getElementById('sched-end').value;
if (!title || !targetNodes || !targetProf || !startTime || !endTime) {
return customAlert(t('titleError'), t('errMissingSchedData'), true);
}
if (startTime >= endTime) {
return customAlert(t('titleError'), t('errSchedDates'), true);
}
const payload = {
title: title,
target_nodes: targetNodes,
target_profile: targetProf,
restore_profile: restoreProf,
start_time: startTime,
end_time: endTime
};
try {
const res = await fetch('/api/schedules', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
});
const data = await res.json();
if (data.success) {
customAlert(t('titleSuccess'), t('msgSchedCreated'));
document.getElementById('sched-title').value = '';
loadSchedules();
} else {
customAlert(t('titleError'), esc(data.error), true);
}
} catch(e) {
console.error(e);
customAlert(t('titleError'), t('msgNetErr'), true);
}
}
function cancelSchedule(sid) {
customConfirm(t('titleAction'), t('confCancelSched'), "var(--danger)", async () => {
try {
const res = await fetch(`/api/schedules/${sid}`, { method: 'DELETE' });
const data = await res.json();
if (data.success) {
customAlert(t('titleSuccess'), t('msgSchedCancelled'));
loadSchedules();
} else {
customAlert(t('titleError'), esc(data.error), true);
}
} catch(e) {
console.error(e);
customAlert(t('titleError'), t('msgNetErr'), true);
}
});
}
+241 -54
View File
@@ -20,30 +20,53 @@
<!-- Foglio di Stile Esterno Modularizzato (Cache Buster) -->
<link rel="stylesheet" href="/static/css/style.css?v=blueprint-header-fix">
<!-- Foglio Stili Layout Alternativi -->
<link rel="stylesheet" href="/static/css/layouts.css?v=6">
</head>
<body>
<div id="top-bar-container">
<div id="top-bar">
<div class="title-brand">SCHEMATIC // FLEET C2</div>
<div id="top-bar-container" style="border-bottom: 2px solid var(--border-main); background: var(--bg-main, #04102e); padding: 0; margin-bottom: 25px;">
<div id="top-bar" style="display: flex; justify-content: space-between; align-items: stretch; padding: 0; min-height: 90px; width: 100%; max-width: 100%; box-sizing: border-box;">
<div class="nav-tabs">
<button class="nav-tab active" onclick="switchView('home')" id="tab-home">HOME</button>
<button class="nav-tab" onclick="switchView('nodes')" id="tab-nodes">NODES</button>
<button class="nav-tab" onclick="switchView('map')" id="tab-map">MAP</button>
<button class="nav-tab" onclick="switchView('aprs')" id="tab-aprs">APRS</button>
<!-- HEADER SX: BANNER ANCORATO SENZA CROP -->
<div id="master-banner-container" style="display: none; flex: 0 0 42%; max-width: 42%; border-right: 2px solid var(--border-main); background: #020b1e; align-items: center; justify-content: center; padding: 0; box-sizing: border-box; overflow: hidden;">
<img src="/static/banners/banner.png" style="width: 100%; height: 100%; object-fit: contain; object-position: center; display: block;"
onload="this.parentElement.style.display='flex';"
onerror="this.parentElement.style.display='none';">
</div>
<div class="top-bar-right">
<span id="mqtt-badge" class="mqtt-badge mqtt-offline">MQTT: CHK</span>
<button class="theme-switch" id="lang-btn" onclick="toggleLang()" data-i18n-title="ttLang">ITA</button>
<button class="theme-switch" id="push-btn" onclick="subscribeToPush()">PUSH</button>
<div id="auth-container" style="display:flex; align-items:center; gap:8px; flex-wrap:wrap; justify-content:flex-end;"></div>
</div>
</div>
</div>
<!-- HEADER DX: STRUTTURA FLUIDA A 3 RIGHE -->
<div id="header-right-controls" style="flex: 1; display: flex; flex-direction: column; gap: 8px; justify-content: center; padding: 10px 18px; box-sizing: border-box; background: rgba(0, 15, 45, 0.25); min-width: 350px;">
<!-- VISTA FLEET MAP -->
<!-- RIGA 1: BRAND E OROLOGIO -->
<div style="display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 10px; border-bottom: 1px dashed var(--border-light, rgba(255,255,255,0.15)); padding-bottom: 4px;">
<span class="title-brand" style="font-size: 1.15rem; font-weight: 700; letter-spacing: 2px; color: var(--text-main);">SCHEMATIC // FLEET C2</span>
<span id="live-clock" style="font-family: 'JetBrains Mono', monospace; font-size: 0.8rem; color: var(--primary); letter-spacing: 1px;">SYS_TIME: --:--:--</span>
</div>
<!-- RIGA 2: TASTI DI NAVIGAZIONE (SX) + BADGES (DX) -->
<div style="display: flex; justify-content: space-between; align-items: center; gap: 10px; width: 100%;">
<div class="nav-tabs" style="display: flex; gap: 6px; border: none; margin: 0; padding: 0;">
<button class="nav-tab active" onclick="switchView('home')" id="tab-home" style="padding: 6px 14px; font-size: 0.85rem; font-weight: bold; letter-spacing: 1px; border-radius: 4px;">HOME</button>
<button class="nav-tab" onclick="switchView('nodes')" id="tab-nodes" style="padding: 6px 14px; font-size: 0.85rem; font-weight: bold; letter-spacing: 1px; border-radius: 4px;">NODES</button>
<button class="nav-tab" onclick="switchView('map')" id="tab-map" style="padding: 6px 14px; font-size: 0.85rem; font-weight: bold; letter-spacing: 1px; border-radius: 4px;">MAP</button>
<button class="nav-tab" onclick="switchView('aprs')" id="tab-aprs" style="padding: 6px 14px; font-size: 0.85rem; font-weight: bold; letter-spacing: 1px; border-radius: 4px;">APRS</button>
</div>
<div class="top-bar-right" style="display: flex; align-items: center; gap: 6px; margin: 0; padding: 0; justify-content: flex-end;">
<span id="mqtt-badge" class="mqtt-badge mqtt-offline" style="padding: 4px 8px; font-size: 0.75rem; font-weight: bold; letter-spacing: 1px;">MQTT: CHK</span>
<span id="users-badge" class="mqtt-badge" style="padding: 4px 8px; font-size: 0.75rem; font-weight: bold; letter-spacing: 1px; border-color: var(--primary); color: var(--primary); cursor: pointer;" title="Operatori attivi (clicca per info)" onclick="showActiveUsers()">👥 <span id="active-users-count">1</span></span>
<button class="theme-switch" id="layout-btn" onclick="cycleLayout()" title="Cambia Layout" style="padding: 4px 8px; font-size: 0.75rem;">[ L: BLU ]</button>
<button class="theme-switch" id="lang-btn" onclick="toggleLang()" data-i18n-title="ttLang" style="padding: 4px 8px; font-size: 0.75rem;">ITA</button>
<button class="theme-switch" id="push-btn" onclick="subscribeToPush()" style="padding: 4px 8px; font-size: 0.75rem;">PUSH</button>
</div>
</div>
<!-- RIGA 3: UTENTE E CONTROLLI AMMINISTRATIVI (DX) -->
<div id="auth-container" style="display: flex; justify-content: flex-end; align-items: center; width: 100%; margin: 0; padding: 0;"></div>
</div>
</div>
</div><!-- VISTA FLEET MAP -->
<div id="view-map" style="display: none; padding: 0 20px;">
<div id="map-container"></div>
</div>
@@ -52,8 +75,8 @@
<div id="view-aprs" style="display: none;">
<div style="max-width: 1400px; margin: 0 auto 30px auto; padding: 0 20px;">
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed var(--border-main); padding-bottom: 5px; margin-bottom: 15px;">
<h3 style="margin: 0; font-weight: 300; letter-spacing: 2px; color: var(--text-main);">[ APRS_TRAFFIC ]</h3>
<button class="btn-cmd" onclick="document.getElementById('aprs-body').innerHTML='';" style="width: auto; padding: 4px 12px; flex: none;">[ CLEAR ]</button>
<h3 style="margin: 0; font-weight: 300; letter-spacing: 2px; color: var(--text-main);"><span data-i18n="aprsTraffic">[ APRS_TRAFFIC ]</span></h3>
<button class="btn-cmd" onclick="document.getElementById('aprs-body').innerHTML='';" style="width: auto; padding: 4px 12px; flex: none;"><span data-i18n="btnClear">[ CLEAR ]</span></button>
</div>
<div class="table-container" style="max-height: calc(100vh - 200px);">
<table>
@@ -77,7 +100,7 @@
<div style="max-width: 1400px; margin: 0 auto; padding: 0 20px;">
<!-- Header Ritorno e Titolo -->
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 2px dashed var(--border-main); padding-bottom: 15px; margin-bottom: 25px; flex-wrap: wrap; gap: 15px;">
<button class="btn-cmd" style="width: auto; padding: 12px 25px; font-size: 1.1rem; border-color: var(--accent); color: var(--accent) !important;" onclick="closeNodeFocus()">[ < RETURN TO OVERVIEW ]</button>
<button class="btn-cmd" style="width: auto; padding: 12px 25px; font-size: 1.1rem; border-color: var(--accent); color: var(--accent) !important;" onclick="closeNodeFocus()"><span data-i18n="btnReturn">[ < RETURN TO OVERVIEW ]</span></button>
<div style="text-align: right; flex-grow: 1;">
<h2 id="focus-name" style="margin: 0; color: var(--text-main); font-weight: 300; font-size: 2.5rem; letter-spacing: 2px; display: flex; align-items: center; justify-content: flex-end; gap: 15px;">--</h2>
<div id="focus-id" style="color: var(--primary); font-family: 'JetBrains Mono', monospace; font-size: 1.2rem; margin-top: 5px;">--</div>
@@ -85,31 +108,32 @@
</div>
</div>
<!-- BANNER PERSONALIZZATO -->
<div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));">
<!-- COLONNA SX: HARDWARE E RF -->
<div style="display: flex; flex-direction: column; gap: 20px;">
<div class="card" style="border-width: 1px !important;">
<h3 style="margin: 0 0 20px 0; color: var(--accent); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">[ HARDWARE_TELEMETRY ]</h3>
<h3 style="margin: 0 0 20px 0; color: var(--accent); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;"><span data-i18n="hwTelemetry">[ HARDWARE_TELEMETRY ]</span></h3>
<div style="font-size: 1.2rem; font-family: 'JetBrains Mono', monospace; display: flex; flex-direction: column; gap: 15px;">
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>CPU_LOAD:</span> <span id="focus-cpu">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>SYS_TEMP:</span> <span id="focus-temp">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>RAM_USAGE:</span> <span id="focus-ram">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>DISK_SPACE:</span> <span id="focus-disk">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>UPTIME:</span> <span id="focus-up">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="cpuLoad">CPU_LOAD:</span></span> <span id="focus-cpu">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="sysTemp">SYS_TEMP:</span></span> <span id="focus-temp">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="ramUsage">RAM_USAGE:</span></span> <span id="focus-ram">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="diskSpace">DISK_SPACE:</span></span> <span id="focus-disk">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="sysUptime">UPTIME:</span></span> <span id="focus-up">--</span></div>
</div>
</div>
<div class="card" style="border-width: 1px !important;">
<h3 style="margin: 0 0 20px 0; color: var(--primary); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">[ RF_CONFIGURATION ]</h3>
<h3 style="margin: 0 0 20px 0; color: var(--primary); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;"><span data-i18n="rfConfig">[ RF_CONFIGURATION ]</span></h3>
<div style="font-size: 1.2rem; font-family: 'JetBrains Mono', monospace; display: flex; flex-direction: column; gap: 15px;">
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>TX_FREQ:</span> <span id="focus-tx" style="color: var(--danger);">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>RX_FREQ:</span> <span id="focus-rx" style="color: var(--success);">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span>LOCATION:</span> <span id="focus-loc" style="color: var(--text-main);">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="txFreq">TX_FREQ:</span></span> <span id="focus-tx" style="color: var(--danger);">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="rxFreq">RX_FREQ:</span></span> <span id="focus-rx" style="color: var(--success);">--</span></div>
<div style="display: flex; justify-content: space-between; border-bottom: 1px dashed var(--border-light); padding-bottom: 8px;"><span><span data-i18n="nodeLoc">LOCATION:</span></span> <span id="focus-loc" style="color: var(--text-main);">--</span></div>
</div>
</div>
<div class="card" id="focus-modes-card" style="border-width: 1px !important; display: none;">
<h3 style="margin: 0 0 15px 0; color: #fff; font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">[ OPERATING_MODES ]</h3>
<h3 style="margin: 0 0 15px 0; color: #fff; font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;"><span data-i18n="opModes">[ OPERATING_MODES ]</span></h3>
<div id="focus-modes-toggles" style="display: flex; flex-wrap: wrap; gap: 10px; font-family: 'JetBrains Mono', monospace;">
<span style="color:var(--text-muted); font-size: 0.9rem;">WAITING FOR CONFIG...</span>
</div>
@@ -119,13 +143,13 @@
<!-- COLONNA DX: SOFTWARE E LOG -->
<div style="display: flex; flex-direction: column; gap: 20px;">
<div class="card" style="border-width: 1px !important; flex: 1;">
<h3 style="margin: 0 0 20px 0; color: var(--success); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">[ ACTIVE_GATEWAYS ]</h3>
<h3 style="margin: 0 0 20px 0; color: var(--success); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;"><span data-i18n="actGateways">[ ACTIVE_GATEWAYS ]</span></h3>
<div id="focus-gw" style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; min-height: 40px; font-size: 0.9rem;"></div>
<h3 style="margin: 0 0 20px 0; color: var(--primary); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">[ TIMESLOTS_MODES ]</h3>
<h3 style="margin: 0 0 20px 0; color: var(--primary); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;"><span data-i18n="tsModes">[ TIMESLOTS_MODES ]</span></h3>
<div id="focus-ts" style="display: flex; flex-direction: column; gap: 15px; margin-bottom: 25px; font-family: 'JetBrains Mono', monospace; font-size: 1.2rem;"></div>
<h3 style="margin: 0 0 15px 0; color: var(--border-main); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">[ LIVE_TERMINAL ]</h3>
<h3 style="margin: 0 0 15px 0; color: var(--border-main); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;"><span data-i18n="liveTerminal">[ LIVE_TERMINAL ]</span></h3>
<div id="focus-log" class="terminal-log" style="height: 320px; max-height: 320px; font-size: 0.95rem; border-color: var(--border-main);">> AWAITING_STREAM...</div>
</div>
</div>
@@ -133,7 +157,7 @@
<!-- FOCUS LASTHEARD -->
<div style="margin-top: 30px; border-top: 1px dashed var(--border-light); padding-top: 20px;">
<h3 style="margin: 0 0 15px 0; color: var(--text-main); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">[ NODE_LASTHEARD ]</h3>
<h3 style="margin: 0 0 15px 0; color: var(--text-main); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;"><span data-i18n="nodeLastheard">[ NODE_LASTHEARD ]</span></h3>
<div class="table-container" style="margin: 0; max-height: 400px;">
<table>
<thead>
@@ -156,9 +180,37 @@
</div>
</div>
<!-- FOCUS ANALYTICS -->
<div style="margin-top: 30px; border-top: 1px dashed var(--border-light); padding-top: 20px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; flex-wrap: wrap; gap: 10px;">
<h3 style="margin: 0; color: var(--text-main); font-weight: 300; font-size: 1.3rem; letter-spacing: 2px;">
<span data-i18n="titleAnalytics">[ NODE_ANALYTICS ]</span> <span id="analytics-time-label" style="color: var(--primary);">24H</span>
</h3>
<div style="display: flex; gap: 8px; flex-wrap: wrap; align-items: center;">
<button class="filter-pill" onclick="setAnalyticsTimeframe(12)" id="btn-ana-12">12H</button>
<button class="filter-pill active" onclick="setAnalyticsTimeframe(24)" id="btn-ana-24">24H</button>
<button class="filter-pill" onclick="setAnalyticsTimeframe(48)" id="btn-ana-48">48H</button>
<button class="filter-pill" onclick="setAnalyticsTimeframe(168)" id="btn-ana-168">7D</button>
<div style="width: 1px; background: var(--border-light); margin: 0 5px; height: 20px;"></div>
<button class="btn-cmd" onclick="loadNodeAnalytics()" style="width: auto; padding: 4px 12px; flex: none;" data-i18n="btnRefreshBracket">[ REFRESH ]</button>
</div>
</div>
<div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px;">
<!-- Telemetria HW (CPU / Temp) -->
<div class="card" style="border-width: 1px !important; padding: 15px; height: 250px;">
<canvas id="chart-hw"></canvas>
</div>
<!-- Stat RF (Transiti / BER) -->
<div class="card" style="border-width: 1px !important; padding: 15px; height: 250px;">
<canvas id="chart-rf"></canvas>
</div>
</div>
</div>
<!-- CONTROLLI ADMIN DEL NODO -->
<div id="focus-controls" style="display: none; margin-top: 30px; border: 1px dashed var(--danger); padding: 30px; background: rgba(6, 36, 111, 0.6); backdrop-filter: blur(2px);">
<h3 style="margin: 0 0 20px 0; color: var(--danger); font-weight: 300; font-size: 1.5rem; text-align: center; letter-spacing: 2px;">[ ADMIN_CONTROLS ]</h3>
<h3 style="margin: 0 0 20px 0; color: var(--danger); font-weight: 300; font-size: 1.5rem; text-align: center; letter-spacing: 2px;"><span data-i18n="adminControls">[ ADMIN_CONTROLS ]</span></h3>
<div id="focus-admin-btns" style="display: flex; gap: 15px; flex-wrap: wrap; justify-content: center;">
</div>
</div>
@@ -193,8 +245,10 @@
<!-- VISTA HOME -->
<div id="view-home">
<div style="max-width: 1400px; margin: 0 auto 20px auto; padding: 0 20px;">
<h3 style="margin: 0 0 15px 0; font-weight: 300; letter-spacing: 2px; color: var(--text-main); border-bottom: 1px dashed var(--border-main); padding-bottom: 5px;">
[ FLEET_STATUS ]
<span data-i18n="fleetStatus">[ FLEET_STATUS ]</span>
</h3>
<div id="home-mini-nodes" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 15px;"></div>
</div>
@@ -240,27 +294,27 @@
</div>
<div style="max-width: 1400px; margin: 0 auto 30px auto; padding: 0 20px;">
<h3 style="margin: 0 0 15px 0; font-weight: 300; letter-spacing: 2px; color: var(--text-main); border-bottom: 1px dashed var(--border-main); padding-bottom: 5px;" data-i18n="statTitle">[ DAILY_STATISTICS ]</h3>
<h3 style="margin: 0 0 15px 0; font-weight: 300; letter-spacing: 2px; color: var(--text-main); border-bottom: 1px dashed var(--border-main); padding-bottom: 5px;" data-i18n="statTitle">[ <span data-i18n="statTitle">DAILY_STATISTICS</span> ]</h3>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
<div class="card" style="border-left: 1px solid var(--accent) !important; padding: 15px;">
<h4 style="margin: 0 0 10px 0; color: var(--accent); font-weight: 300; letter-spacing: 1px;" data-i18n="statTopTG">TOP_TALKGROUPS</h4>
<div id="stat-tgs" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">LOADING...</div>
<h4 style="margin: 0 0 10px 0; color: var(--accent); font-weight: 300; letter-spacing: 1px;" data-i18n="statTopTG"><span data-i18n="statTopTG">TOP_TALKGROUPS</span></h4>
<div id="stat-tgs" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading"><span data-i18n="statLoading">LOADING...</span></div>
</div>
<div class="card" style="border-left: 1px solid var(--success) !important; padding: 15px;">
<h4 style="margin: 0 0 10px 0; color: var(--success); font-weight: 300; letter-spacing: 1px;" data-i18n="statTopCall">TOP_CALLSIGNS</h4>
<div id="stat-calls" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">LOADING...</div>
<h4 style="margin: 0 0 10px 0; color: var(--success); font-weight: 300; letter-spacing: 1px;" data-i18n="statTopCall"><span data-i18n="statTopCall">TOP_CALLSIGNS</span></h4>
<div id="stat-calls" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading"><span data-i18n="statLoading">LOADING...</span></div>
</div>
<div class="card" style="border-left: 1px solid var(--primary) !important; padding: 15px; display: flex; justify-content: space-around; align-items: center; text-align: center; flex-direction: row;">
<div>
<div style="font-size: 1.8rem; font-weight: 300; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-avg">--</span>s</div>
<div style="font-size: 0.75rem; color: var(--border-main); text-transform: uppercase; font-weight: 300; letter-spacing: 1px;" data-i18n="statAvgDur">AVG_DURATION</div>
<div style="font-size: 0.75rem; color: var(--border-main); text-transform: uppercase; font-weight: 300; letter-spacing: 1px;" data-i18n="statAvgDur"><span data-i18n="statAvgDur">AVG_DURATION</span></div>
</div>
<div style="width: 1px; height: 50px; border-left: 1px dashed var(--border-light);"></div>
<div>
<div style="font-size: 1.8rem; font-weight: 300; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-today">--</span></div>
<div style="font-size: 0.75rem; color: var(--border-main); text-transform: uppercase; font-weight: 300; letter-spacing: 1px;" data-i18n="statTodayTx">TRANSITS_TODAY</div>
<div style="font-size: 0.75rem; color: var(--border-main); text-transform: uppercase; font-weight: 300; letter-spacing: 1px;" data-i18n="statTodayTx"><span data-i18n="statTodayTx">TRANSITS_TODAY</span></div>
</div>
</div>
</div>
@@ -268,7 +322,7 @@
</div>
<footer>
<div style="text-align: center; padding: 25px; color: var(--border-light); font-size: 0.85rem; font-weight: 300; display: flex; justify-content: center; align-items: center; gap: 15px; flex-wrap: wrap;">
<div style="text-align: center; padding: 25px; color: var(--text-muted); font-size: 0.85rem; font-weight: 300; display: flex; justify-content: center; align-items: center; gap: 15px; flex-wrap: wrap;">
<span>SYS_OP: IV3JDV @ ARIFVG</span>
<span>|</span>
<a href="https://git.arifvg.it/iv3jdv/fleet-control-server" target="_blank" style="color: inherit; text-decoration: none;">GITEA_REPO</a>
@@ -295,21 +349,30 @@
</div>
<div id="admin-modal" class="modal-overlay">
<div class="modal-content" style="max-width:900px;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px dashed var(--border-main); padding-bottom:10px; margin-bottom:20px;">
<div class="modal-content" style="max-width:1200px; width:95%;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px dashed var(--border-main); padding-bottom:10px; margin-bottom:20px; flex-wrap: wrap; gap: 10px;">
<div style="display:flex; align-items:center; gap: 15px;">
<h2 style="margin:0; color:var(--text-main); font-weight:300;" data-i18n="adminTitle">[ SYS_ADMIN ]</h2>
<div id="admin-action-btns" style="display:flex; gap: 10px;"></div>
</div>
<button onclick="closeAdmin()" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width: 24px; height: 24px; flex: 0 0 24px; padding: 0; display: flex; align-items: center; justify-content: center; font-size: 0.8rem;">X</button>
</div>
<div style="display:flex; flex-wrap:wrap; gap:10px; margin-bottom:20px; background:rgba(0,0,0,0.2); padding:15px; align-items:center; border: 1px solid var(--border-light);">
<input type="text" id="new-user" placeholder="USR" style="flex:1; min-width:120px;">
<input type="password" id="new-pass" placeholder="PWD" style="flex:1; min-width:120px;">
<select id="new-role" style="flex:none; width: 80px;"><option value="operator" data-i18n="roleOp">OP</option><option value="admin">ADM</option></select>
<select id="new-role" style="flex:none; width: auto;"><option value="operator" data-i18n="roleOp">OP</option><option value="node_admin">N_ADM</option><option value="admin">ADM</option></select>
<input type="text" id="new-nodes" placeholder="NODES (IR3UIC,IR3Q)" style="flex:2; min-width:150px;">
<button id="btn-user-submit" onclick="submitUser()" class="btn-cmd" style="border-color:var(--success); color:var(--success) !important; flex:none; width: 80px;" data-i18n="btnAdd">ADD</button>
<button id="btn-user-cancel" onclick="cancelEdit()" class="btn-cmd" style="display:none; width: 24px; height: 24px; flex: 0 0 24px; padding: 0; align-items: center; justify-content: center; font-size: 0.8rem;">X</button>
</div>
<div style="margin-bottom:20px; background:rgba(0,0,0,0.2); padding:20px; border: 1px solid var(--border-light);">
<h4 style="margin:0 0 15px 0; color:var(--primary); font-weight:300;" data-i18n="adminDBSync">[ DB_SYNC_CFG ]</h4>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(450px, 1fr)); gap: 20px; align-items: start;">
<!-- COLONNA SINISTRA: Impostazioni & Utenti -->
<div style="display: flex; flex-direction: column; gap: 20px;">
<div style="background:rgba(0,0,0,0.2); padding:20px; border: 1px solid var(--border-light);">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom: 1px dashed var(--border-main); padding-bottom: 15px; margin-bottom: 20px;">
<h4 style="margin:0; color:var(--primary); font-weight:300;" data-i18n="adminDBSync">[ DB_SYNC_CFG ]</h4>
<a href="/api/fleet_backup" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; text-decoration:none; display:flex; font-size: 0.75rem; padding: 6px 12px; width: auto; flex: none;" data-i18n="btnDownloadZip">[ DOWNLOAD_ALL_CFG_ZIP ]</a>
</div>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap:15px; margin-bottom:15px;">
<div><label style="font-size:0.8rem; font-weight:300; display:block; margin-bottom:5px; color:var(--text-muted);">URL_DMR (.dat):</label><input type="text" id="url-dmr-input" style="width:100%;"></div>
<div><label style="font-size:0.8rem; font-weight:300; display:block; margin-bottom:5px; color:var(--text-muted);">URL_NXDN (.csv):</label><input type="text" id="url-nxdn-input" style="width:100%;"></div>
@@ -326,6 +389,20 @@
</table>
</div>
</div>
<!-- COLONNA DESTRA: Security Audit Logs -->
<div style="background:rgba(0,0,0,0.2); padding:20px; border: 1px solid var(--border-light); height: 100%; box-sizing: border-box; display: flex; flex-direction: column;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom: 1px dashed var(--border-main); padding-bottom: 15px; margin-bottom: 15px;">
<h4 style="margin:0; color:var(--accent); font-weight:300;" data-i18n="titleAuditLogs">[ SECURITY_AUDIT_LOGS ]</h4>
<button onclick="loadAuditLogs()" class="btn-cmd" style="padding: 4px 10px; font-size: 0.75rem; width: auto; flex: none;" data-i18n="btnRefresh">REFRESH</button>
</div>
<div id="audit-logs-container" style="flex: 1; min-height: 250px; max-height: 500px; overflow-y: auto; font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; line-height: 1.6; padding-right: 5px;">
<span style="color: var(--text-muted);" data-i18n="waitLoading">In attesa di caricamento...</span>
</div>
</div>
</div>
</div>
</div>
<div id="services-modal" class="modal-overlay">
@@ -354,10 +431,23 @@
<h3 style="margin:0; color:var(--accent); font-weight:300;">[ <span data-i18n="modEditTitle">EDIT:</span> <span id="editor-title" style="color:var(--text-main);"></span> ]</h3>
<button onclick="closeEditorModal()" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width: 24px; height: 24px; flex: 0 0 24px; padding: 0; display: flex; align-items: center; justify-content: center; font-size: 0.8rem;">X</button>
</div>
<textarea id="config-textarea" spellcheck="false" style="width:100%; height:55vh; background:rgba(0,0,0,0.3); color:var(--text-main); font-family:'JetBrains Mono', monospace; font-size:0.85rem; padding:15px; border:1px solid var(--border-light); resize:none; outline:none; margin-top: 15px;"></textarea>
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 10px;">
<div style="display:flex; gap: 10px; align-items: center;">
<span style="font-size: 0.85rem; color: var(--text-muted);" data-i18n="lblHistory">STORICO:</span>
<select id="config-history-select" onchange="loadHistoryConfig()" style="font-size: 0.8rem; padding: 4px 10px;">
<option value="" data-i18n="optCurrentUnsaved">Attuale (Non salvata)</option>
</select>
</div>
<button onclick="previewConfigDiff()" class="btn-cmd" style="border-color:var(--accent); color:var(--accent) !important; width: auto; padding: 4px 15px; flex: none;" data-i18n="btnPreviewDiff">[ PREVIEW_DIFF ]</button>
</div>
<div id="diff-view" style="display:none; width:100%; height:55vh; overflow-y:auto; background:rgba(0,0,0,0.4); font-family:'JetBrains Mono', monospace; font-size:0.85rem; border:1px solid var(--border-main); padding: 15px; white-space: pre-wrap; line-height: 1.4;"></div>
<textarea id="config-textarea" spellcheck="false" style="width:100%; height:55vh; background:rgba(0,0,0,0.3); color:var(--text-main); font-family:'JetBrains Mono', monospace; font-size:0.85rem; padding:15px; border:1px solid var(--border-light); resize:none; outline:none;"></textarea>
<div style="display:flex; justify-content:space-between; margin-top:20px; align-items:center;">
<span id="editor-status" style="font-size:0.9rem; font-weight:300; font-family:'JetBrains Mono',monospace;"></span>
<button onclick="saveConfig()" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; max-width: 250px; flex: none;" data-i18n="btnSave">WRITE_FILE</button>
<div style="display:flex; gap:10px;">
<button id="btn-cancel-diff" onclick="cancelDiff()" class="btn-cmd" style="display:none; border-color:var(--text-muted); color:var(--text-muted) !important;" data-i18n="btnCancelDiff">ANNULLA</button>
<button id="btn-save-cfg" onclick="saveConfig()" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; max-width: 250px; flex: none;" data-i18n="btnSave">WRITE_FILE</button>
</div>
</div>
</div>
</div>
@@ -413,7 +503,33 @@
</div>
</div>
<div id="update-modal" class="modal-overlay">
<!-- Live Log Modal -->
<div id="log-modal" class="modal-overlay">
<div class="modal-content" style="max-width:900px; padding: 20px;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px dashed var(--border-main); padding-bottom:10px; margin-bottom:15px; flex-wrap: wrap; gap: 10px;">
<h2 style="margin:0; color:var(--success); font-weight:300;"><span data-i18n="liveLogTitle">[ LIVE_LOG: </span> <span id="log-modal-title" style="color:var(--text-main);"></span> ]</h2>
<div style="display: flex; gap: 10px; align-items: center;">
<select id="log-service-filter" style="width: auto; padding: 4px 10px; font-size: 0.85rem;" onchange="renderLogs()">
<option value="ALL" data-i18n="filterAll">ALL DAEMONS</option>
<option value="mmdvm">MMDVMHost</option>
<option value="dmrgateway">DMRGateway</option>
<option value="ysfgateway">YSFGateway</option>
<option value="dstargateway">DStarGateway</option>
<option value="nxdngateway">NXDNGateway</option>
<option value="p25gateway">P25Gateway</option>
</select>
<button class="btn-cmd" onclick="toggleAutoScroll()" id="btn-autoscroll" style="border-color:var(--accent); color:var(--accent) !important; padding: 4px 10px;" data-i18n="btnScrollOn">SCROLL: ON</button>
<button class="btn-cmd" onclick="clearLogs()" style="border-color:var(--danger); color:var(--danger) !important; padding: 4px 10px;" data-i18n="btnClear">CLEAR</button>
<button onclick="closeLogModal()" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width: 24px; height: 24px; flex: 0 0 24px; padding: 0; display: flex; align-items: center; justify-content: center; font-size: 0.8rem;">X</button>
</div>
</div>
<div id="log-console" class="terminal-log" style="height: 500px; max-height: 500px; font-size: 0.85rem; border: 1px solid var(--border-light); padding: 15px; background: rgba(0,0,0,0.4);">
</div>
</div>
</div>
<div id="update-modal" class="modal-overlay">
<div class="modal-content" style="max-width:400px; text-align:center;">
<h2 style="margin-top:0; color:var(--primary); border-bottom: 1px dashed var(--border-main); padding-bottom: 10px; font-weight:300;" data-i18n="modUpdateTitle">[ GBL_UPDATE ]</h2>
<p style="margin-bottom:25px; font-weight: 300;" data-i18n="confUpdate">REQ DATA?</p>
@@ -434,13 +550,84 @@
</div>
</div>
<div id="schedule-modal" class="modal-overlay">
<div class="modal-content" style="max-width:1050px; width:95%;">
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px dashed var(--border-main); padding-bottom:10px; margin-bottom:20px;">
<h2 style="margin:0; color:var(--text-main); font-weight:300;" data-i18n="schedTitle">[ CALENDAR_PROFILE_SCHEDULER ]</h2>
<button onclick="closeScheduleModal()" class="btn-cmd" style="border-color:var(--danger); color:var(--danger) !important; width: 24px; height: 24px; flex: 0 0 24px; padding: 0; display: flex; align-items: center; justify-content: center; font-size: 0.8rem;">X</button>
</div>
<!-- FORM CREAZIONE EVENTO -->
<div style="background:rgba(0,0,0,0.2); padding:15px; border:1px solid var(--border-light); margin-bottom:20px;">
<h4 style="margin:0 0 15px 0; color:var(--primary); font-weight:300;" data-i18n="schedNew">[ NEW_SCHEDULED_EVENT ]</h4>
<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap:12px; margin-bottom:15px;">
<div>
<label style="font-size:0.75rem; color:var(--text-muted); display:block; margin-bottom:4px;" data-i18n="lblSchedTitle">EVENT_TITLE:</label>
<input type="text" id="sched-title" placeholder="Es. Net Regionale / Esercitazione" style="width:100%;">
</div>
<div>
<label style="font-size:0.75rem; color:var(--text-muted); display:block; margin-bottom:4px;" data-i18n="lblSchedNodes">TARGET_NODES:</label>
<select id="sched-nodes-select" style="width:100%;"></select>
</div>
<div>
<label style="font-size:0.75rem; color:var(--text-muted); display:block; margin-bottom:4px;" data-i18n="lblSchedTargetProf">TARGET_PROFILE:</label>
<select id="sched-target-prof" style="width:100%;">
<option value="B">B (Profilo B)</option>
<option value="A">A (Profilo A)</option>
</select>
</div>
<div>
<label style="font-size:0.75rem; color:var(--text-muted); display:block; margin-bottom:4px;" data-i18n="lblSchedRestoreProf">RESTORE_PROFILE:</label>
<select id="sched-restore-prof" style="width:100%;">
<option value="A">A (Profilo A)</option>
<option value="B">B (Profilo B)</option>
<option value="NONE" data-i18n="optNone">NONE (Leave active)</option>
</select>
</div>
<div>
<label style="font-size:0.75rem; color:var(--text-muted); display:block; margin-bottom:4px;" data-i18n="lblSchedStart">START_TIME:</label>
<input type="datetime-local" id="sched-start" style="width:100%;">
</div>
<div>
<label style="font-size:0.75rem; color:var(--text-muted); display:block; margin-bottom:4px;" data-i18n="lblSchedEnd">END_TIME:</label>
<input type="datetime-local" id="sched-end" style="width:100%;">
</div>
</div>
<div style="text-align:right;">
<button onclick="submitSchedule()" class="btn-cmd" style="border-color:var(--success); color:var(--success) !important; width:auto; padding:6px 20px; font-size:0.85rem; display:inline-block; flex:none;" data-i18n="btnAddSched">CREATE_SCHEDULE</button>
</div>
</div>
<!-- TABELLA SCHEDULAZIONI -->
<div style="overflow-x:auto; max-height:300px;">
<table style="width:100%; border-collapse:collapse; text-align:left;">
<thead style="background: transparent;">
<tr>
<th data-i18n="thSchedTitle">TITLE</th>
<th data-i18n="thSchedNodes">NODES</th>
<th data-i18n="thSchedProf">PROFILE</th>
<th data-i18n="thSchedStart">START</th>
<th data-i18n="thSchedEnd">END</th>
<th data-i18n="thSchedStatus">STATUS</th>
<th style="text-align:right;" data-i18n="thSchedActs">CMD</th>
</tr>
</thead>
<tbody id="schedules-table-body"></tbody>
</table>
</div>
</div>
</div>
<!-- LIBRERIE ESTERNE -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff_match_patch/20121119/diff_match_patch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<!-- MOTORE MODULARIZZATO JS (Cache Buster aggiunto per forzare il refresh) -->
<script src="/static/js/modals.js?v=blueprint4"></script>
<script src="/static/js/app.js?v=blueprint-modes-admin-only-final"></script>
<script src="/static/js/app.js?v=1793656210"></script>
<!-- SERVICE WORKER -->
<script>