Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1b344f509 | ||
|
|
951396563a | ||
|
|
000ac4f530 | ||
|
|
891c995cc0 | ||
|
|
a3031ce33f | ||
|
|
47b4bed21f | ||
|
|
7a9008de78 | ||
|
|
dad1a656fe | ||
|
|
b33d495474 | ||
|
|
38f7efce6b | ||
|
|
24c81c1abb | ||
|
|
126ad8cdaf | ||
|
|
2f0abdc9bf | ||
|
|
a1449eedfb | ||
|
|
2fa1b476c4 | ||
|
|
8ce2ed243d | ||
|
|
8ee2958b8e | ||
|
|
298478e36d | ||
|
|
502244dff4 | ||
|
|
c5dcacefd1 | ||
|
|
cae5c4ea83 | ||
|
|
445cc5e97d |
@@ -37,6 +37,27 @@ The server acts as the brain of the network:
|
||||
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.
|
||||
**Pro Tip:** You can use Let's Encrypt to get a free SSL certificate for your domain.
|
||||
|
||||
### ⚠️ 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, causing the dashboard's tables to randomly clear or flash.
|
||||
You must enable the WebSocket tunnel in Apache:
|
||||
```bash
|
||||
sudo a2enmod proxy_wstunnel rewrite headers
|
||||
```
|
||||
And insert the **Rewrite** rules *before* the `ProxyPass` directives inside your `<VirtualHost *:443>` block:
|
||||
```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/
|
||||
```
|
||||
|
||||
#### 🛠️ Advanced Remote Control & Maintenance
|
||||
* **Remote .INI Editor:** Edit daemon configuration files (e.g., MMDVMHost.ini) directly from the web interface without SSH access.
|
||||
* **Service Management:** Start, Stop, or Restart remote system daemons with a single click.
|
||||
@@ -82,6 +103,7 @@ pip install -r requirements.txt
|
||||
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:
|
||||
@@ -126,6 +148,27 @@ Il server agisce da cervello della rete:
|
||||
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.
|
||||
**Suggerimento:** Puoi usare Let's Encrypt per ottenere un certificato SSL gratuito per il tuo dominio.
|
||||
|
||||
### ⚠️ 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, causando fastidiosi "azzeramenti" o lampeggiamenti della dashboard.
|
||||
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/
|
||||
```
|
||||
|
||||
#### 🛠️ Controllo Remoto & Manutenzione Avanzata
|
||||
* **Editor .INI Remoto:** Modifica i file di configurazione (es. MMDVMHost.ini) direttamente dal pannello web, senza bisogno di accessi SSH.
|
||||
* **Gestione Demoni:** Avvia, arresta o riavvia i servizi di sistema remoti con un clic.
|
||||
@@ -171,6 +214,7 @@ pip install -r requirements.txt
|
||||
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:
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import gevent.monkey
|
||||
gevent.monkey.patch_all()
|
||||
|
||||
from flask import Flask, render_template, request, session, jsonify, send_from_directory
|
||||
from paho.mqtt import client as mqtt_client
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
@@ -12,6 +15,7 @@ import re
|
||||
import queue
|
||||
import hashlib
|
||||
import secrets
|
||||
import subprocess
|
||||
from contextlib import closing
|
||||
from pywebpush import webpush, WebPushException
|
||||
from logging.handlers import RotatingFileHandler
|
||||
@@ -29,25 +33,15 @@ NXDN_IDS_PATH = os.path.join(BASE_DIR, 'nxdn.csv')
|
||||
CLIENTS_PATH = os.path.join(BASE_DIR, 'clients.json')
|
||||
LOG_FILE = os.path.join(BASE_DIR, 'fleet_console.log')
|
||||
|
||||
# --- LOGGING CONFIGURATION ---
|
||||
logging.basicConfig(
|
||||
handlers=[
|
||||
RotatingFileHandler(LOG_FILE, maxBytes=10000000, backupCount=3),
|
||||
logging.StreamHandler()
|
||||
],
|
||||
level=logging.INFO,
|
||||
format='[%(asctime)s] %(levelname)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
logger = logging.getLogger("FleetHub")
|
||||
logging.getLogger('werkzeug').setLevel(logging.ERROR)
|
||||
|
||||
# --- CONFIG ---
|
||||
# --- CONFIG LOADER (INIZIALE PER IL LOGGING) ---
|
||||
config_lock = threading.Lock()
|
||||
|
||||
def read_config():
|
||||
with open(CONFIG_PATH, 'r') as f:
|
||||
return json.load(f)
|
||||
try:
|
||||
with open(CONFIG_PATH, 'r') as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def write_config(cfg):
|
||||
tmp = CONFIG_PATH + '.tmp'
|
||||
@@ -63,6 +57,23 @@ def write_config(cfg):
|
||||
config = read_config()
|
||||
web_cfg = config.get('web', {})
|
||||
|
||||
# --- LOGGING CONFIGURATION DINAMICA ---
|
||||
log_max_mb = int(config.get('log_max_mb', 50))
|
||||
log_backup_count = int(config.get('log_backup_count', 10))
|
||||
max_bytes_val = log_max_mb * 1024 * 1024 if log_max_mb > 0 else 0
|
||||
|
||||
logging.basicConfig(
|
||||
handlers=[
|
||||
RotatingFileHandler(LOG_FILE, maxBytes=max_bytes_val, backupCount=log_backup_count),
|
||||
logging.StreamHandler()
|
||||
],
|
||||
level=logging.INFO,
|
||||
format='[%(asctime)s] %(levelname)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
logger = logging.getLogger("FleetHub")
|
||||
logging.getLogger('werkzeug').setLevel(logging.ERROR)
|
||||
|
||||
def get_secret_key():
|
||||
key = os.environ.get('FLEET_SECRET_KEY') or config.get('secret_key')
|
||||
if not key or key == 'ari_fvg_secret_ultra_secure':
|
||||
@@ -96,6 +107,14 @@ def init_db():
|
||||
c.execute("ALTER TABLE radio_logs ADD COLUMN rssi REAL DEFAULT 0")
|
||||
except sqlite3.OperationalError: pass
|
||||
|
||||
try:
|
||||
c.execute("ALTER TABLE radio_logs ADD COLUMN source_conn TEXT DEFAULT ''")
|
||||
except sqlite3.OperationalError: pass
|
||||
|
||||
try:
|
||||
c.execute("ALTER TABLE radio_logs ADD COLUMN ysf_mode TEXT DEFAULT ''")
|
||||
except sqlite3.OperationalError: pass
|
||||
|
||||
c.execute('''CREATE TABLE IF NOT EXISTS users
|
||||
(id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password_hash TEXT,
|
||||
role TEXT, allowed_nodes TEXT)''')
|
||||
@@ -190,8 +209,8 @@ def save_to_sqlite(client_id, data, protocol="DMR"):
|
||||
elif 'rssi' in data:
|
||||
rssi_val = data['rssi']
|
||||
|
||||
c.execute("INSERT INTO radio_logs (timestamp, client_id, protocol, source_id, target, slot, duration, ber, source_ext, rssi) VALUES (datetime('now', 'localtime'), ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(client_id, protocol, str(data.get('src_id', '---')), str(data.get('dst_id', '---')), data.get('slot', 0), round(data.get('duration', 0), 1), round(data.get('ber', 0), 2), str(data.get('src_ext', '')), rssi_val))
|
||||
c.execute("INSERT INTO radio_logs (timestamp, client_id, protocol, source_id, target, slot, duration, ber, source_ext, rssi, source_conn, ysf_mode) VALUES (datetime('now', 'localtime'), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(client_id, protocol, str(data.get('src_id', '---')), str(data.get('dst_id', '---')), data.get('slot', 0), round(data.get('duration', 0), 1), round(data.get('ber', 0), 2), str(data.get('src_ext', '')), rssi_val, str(data.get('source', '')), str(data.get('mode', ''))))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
notify_update('log_aggiornato')
|
||||
@@ -235,10 +254,10 @@ client_telemetry = {}
|
||||
last_notified_errors = {}
|
||||
device_health = {}
|
||||
last_seen_reflector = {}
|
||||
network_mapping = {}
|
||||
node_info = {}
|
||||
node_general = {}
|
||||
node_versions = {}
|
||||
gateway_states = {}
|
||||
|
||||
if os.path.exists(CACHE_FILE):
|
||||
try:
|
||||
@@ -295,7 +314,7 @@ def on_connect(client, userdata, flags, reason_code, properties=None):
|
||||
|
||||
topics_list = config.get('mqtt', {}).get('topics', default_topics)
|
||||
subscribe_list = [(topic, 0) for topic in topics_list]
|
||||
subscribe_list.append(("+/+/log", 0)) # Ascolto dinamico dei log
|
||||
subscribe_list.append(("+/+/log", 0))
|
||||
|
||||
client.subscribe(subscribe_list)
|
||||
logger.info(f"Subscribed to {len(subscribe_list)} MQTT topics.")
|
||||
@@ -317,7 +336,7 @@ def handle_connect():
|
||||
def on_message(client, userdata, msg):
|
||||
try:
|
||||
topic = msg.topic
|
||||
payload = msg.payload.decode().strip()
|
||||
payload = msg.payload.decode('utf-8', errors='replace').strip()
|
||||
parts = topic.split('/')
|
||||
if len(parts) < 2: return
|
||||
|
||||
@@ -325,38 +344,31 @@ def on_message(client, userdata, msg):
|
||||
p0 = parts[0].lower().replace('-', '')
|
||||
p2 = parts[2].lower().replace('-', '') if len(parts) > 2 else ""
|
||||
|
||||
# --- LOG MANAGEMENT (ESTRAZIONE VERSIONI E GIT ID) ---
|
||||
if len(parts) >= 3 and parts[2].lower() == 'log':
|
||||
if cid not in node_versions:
|
||||
node_versions[cid] = {}
|
||||
|
||||
# 1. Cattura il Firmware MMDVM (es. "... description: MMDVM 20260424 19.2000 Mhz GitID #57e692a")
|
||||
m_fw = re.search(r'description:\s*(MMDVM[^\n\r]+)', payload, re.IGNORECASE)
|
||||
if m_fw:
|
||||
node_versions[cid]["Firmware MMDVM"] = m_fw.group(1).strip()
|
||||
notify_update()
|
||||
|
||||
# 2. Cattura le versioni dei demoni Formato A (es. "YSFGateway-20260323 is starting")
|
||||
m_sw1 = re.search(r'([A-Za-z0-9_]+)-([a-zA-Z0-9.\-]+)\s+is starting', payload, re.IGNORECASE)
|
||||
if m_sw1:
|
||||
prog = m_sw1.group(1)
|
||||
node_versions[cid][prog] = m_sw1.group(2).strip()
|
||||
node_versions[cid]["_last_prog"] = prog # Per il GitID della riga dopo
|
||||
node_versions[cid]["_last_prog"] = prog
|
||||
notify_update()
|
||||
|
||||
# 3. Cattura le versioni dei demoni Formato B (es. "MMDVMHost version 20250419 git #65ebb55")
|
||||
m_sw2 = re.search(r'([A-Za-z0-9_]+)\s+version\s+([a-zA-Z0-9.\-\s#]+)', payload, re.IGNORECASE)
|
||||
if m_sw2:
|
||||
prog = m_sw2.group(1)
|
||||
# Ignoriamo i falsi positivi dei log (es. "protocol version", "firmware version")
|
||||
if prog.lower() not in ['protocol', 'firmware', 'mmdvm firmware']:
|
||||
# Puliamo un eventuale "is starting" finale, se presente
|
||||
ver = m_sw2.group(2).replace("is starting", "").strip()
|
||||
node_versions[cid][prog] = ver
|
||||
node_versions[cid]["_last_prog"] = prog
|
||||
notify_update()
|
||||
|
||||
# 4. Cattura il GitID della riga successiva per i demoni di Formato A
|
||||
m_git = re.search(r'Built .*?\(GitID #([0-9a-fA-F]+)\)', payload, re.IGNORECASE)
|
||||
if m_git:
|
||||
git_id = m_git.group(1)
|
||||
@@ -417,25 +429,24 @@ def on_message(client, userdata, msg):
|
||||
"files": data.get("files", data.get("config_files", [])),
|
||||
"file_names": data.get("file_names", []),
|
||||
"profiles": data.get("profiles", {"A": "PROFILE A", "B": "PROFILE B"}),
|
||||
"interval": data.get("update_interval")
|
||||
"interval": data.get("update_interval"),
|
||||
"uptime": data.get("uptime_seconds", 0),
|
||||
"agent_version": data.get("agent_version", "1.0"),
|
||||
"agent_update_available": data.get("agent_update_available", False)
|
||||
}
|
||||
# --- AGGIUNTA E PULIZIA: SALVA LE VERSIONI DEI BINARI ---
|
||||
bin_versions = data.get("versions", {})
|
||||
if bin_versions:
|
||||
if cid not in node_versions:
|
||||
node_versions[cid] = {}
|
||||
|
||||
# Rimuove le vecchie versioni binarie che il nodo non trasmette più
|
||||
# (proteggendo però il "Firmware MMDVM" e le chiavi interne che derivano dai log)
|
||||
keys_to_remove = [k for k in node_versions[cid].keys()
|
||||
if k not in bin_versions and k not in ["Firmware MMDVM", "_last_prog"]]
|
||||
for k in keys_to_remove:
|
||||
del node_versions[cid][k]
|
||||
|
||||
# Aggiorna o aggiunge le versioni attuali
|
||||
for prog_name, prog_ver in bin_versions.items():
|
||||
node_versions[cid][prog_name] = prog_ver
|
||||
# ----------------------------------------------
|
||||
|
||||
health_changed = device_health.get(cid) != new_health
|
||||
device_health[cid] = new_health
|
||||
if health_changed:
|
||||
@@ -458,32 +469,6 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing health data: {e}")
|
||||
|
||||
elif len(parts) >= 4 and p0 == 'data' and p2 == 'dmrgateway' and (parts[3].upper().startswith('NETWORK') or parts[3].upper().startswith('DMR NETWORK')):
|
||||
try:
|
||||
cid = parts[1].lower()
|
||||
data = json.loads(payload)
|
||||
|
||||
if cid not in network_mapping:
|
||||
network_mapping[cid] = {"ts1": "", "ts2": ""}
|
||||
|
||||
if str(data.get("Enabled")) == "1":
|
||||
net_name = data.get("Name", "Net").upper()
|
||||
is_ts1 = False
|
||||
is_ts2 = False
|
||||
|
||||
keys_to_check = ["PassAllTG", "PassAllPC", "TGRewrite", "PCRewrite", "TypeRewrite", "SrcRewrite"]
|
||||
for k in keys_to_check:
|
||||
val = str(data.get(k, "")).strip()
|
||||
if val.startswith("1"): is_ts1 = True
|
||||
if val.startswith("2"): is_ts2 = True
|
||||
|
||||
if is_ts1: network_mapping[cid]["ts1"] = net_name
|
||||
if is_ts2: network_mapping[cid]["ts2"] = net_name
|
||||
notify_update()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing DMRGateway for {cid}: {e}")
|
||||
|
||||
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'info':
|
||||
try:
|
||||
cid = parts[1].lower()
|
||||
@@ -538,6 +523,19 @@ def on_message(client, userdata, msg):
|
||||
elif "p25" in p0: proto = "P25"
|
||||
elif "dstar" in p0: proto = "D-STAR"
|
||||
|
||||
if cid not in gateway_states:
|
||||
gateway_states[cid] = {}
|
||||
|
||||
if 'status' in data:
|
||||
gateway_states[cid][proto] = {"action": "status", "dest": data['status'].get('message', 'IDLE')}
|
||||
notify_update()
|
||||
elif 'link' in data:
|
||||
l = data['link']
|
||||
g_dest = str(l.get('reflector') or l.get('talkgroup') or '---').strip()
|
||||
g_action = l.get('action', '')
|
||||
gateway_states[cid][proto] = {"action": g_action, "dest": g_dest}
|
||||
notify_update()
|
||||
|
||||
m = ""
|
||||
if 'status' in data:
|
||||
m = data['status'].get('message', '')
|
||||
@@ -571,18 +569,36 @@ def on_message(client, userdata, msg):
|
||||
if act in ['start', 'late_entry']:
|
||||
src = get_call(d.get('src_id'))
|
||||
dst = str(d.get('dst_id'))
|
||||
active_calls[cid][sk] = {'src': src, 'dst': dst}
|
||||
|
||||
active_calls[cid][sk] = {
|
||||
'src': src,
|
||||
'dst': dst,
|
||||
'slot': d.get('slot', 1),
|
||||
'ext': str(d.get('src_ext', '')),
|
||||
'source': str(d.get('source', '')),
|
||||
'mode': str(d.get('mode', ''))
|
||||
}
|
||||
|
||||
client_telemetry[cid]["alt"] = ""
|
||||
client_telemetry[cid][sk] = f"🎙️ {src} ➔ TG {dst}"
|
||||
notify_update()
|
||||
|
||||
elif act in ['end', 'lost']:
|
||||
info = active_calls[cid].get(sk, {'src': '---', 'dst': '---'})
|
||||
d['src_id'], d['dst_id'] = info['src'], info['dst']
|
||||
info = active_calls[cid].get(sk, {'src': '---', 'dst': '---', 'slot': d.get('slot', 1), 'ext': '', 'source': '', 'mode': ''})
|
||||
|
||||
d.update({
|
||||
'src_id': info['src'],
|
||||
'dst_id': info['dst'],
|
||||
'slot': info['slot'],
|
||||
'src_ext': info['ext'],
|
||||
'source': info['source'],
|
||||
'mode': info['mode']
|
||||
})
|
||||
|
||||
save_to_sqlite(cid, d, protocol="DMR")
|
||||
client_telemetry[cid][sk] = f"{'✅' if act=='end' else '⚠️'} {info['src']}"
|
||||
save_cache(client_telemetry)
|
||||
if sk in active_calls[cid]: del active_calls[cid][sk]
|
||||
|
||||
else:
|
||||
for k, ico, name in [('NXDN','🟢','NXDN'),('YSF','🟣','YSF'),('P25','🟠','P25'),('D-Star','🔵','D-STAR')]:
|
||||
if k in data:
|
||||
@@ -594,21 +610,33 @@ def on_message(client, userdata, msg):
|
||||
elif k == 'P25': src = get_call(p.get('src_id', '---'), 'DMR')
|
||||
else: src = str(p.get('Callsign', p.get('src_callsign', p.get('src_info', p.get('src_id', '---')))))
|
||||
|
||||
t_list = [p.get('reflector'), p.get('dst_callsign'), p.get('dst_id')]
|
||||
current_target = next((str(x).strip() for x in t_list if x and str(x).strip() not in ['', '---', '0', 'CQCQCQ']), None)
|
||||
raw_target = str(p.get('dst_callsign', p.get('dst_id', ''))).strip()
|
||||
|
||||
if not current_target or current_target == cid.upper():
|
||||
target = last_seen_reflector.get(f"{cid}_{name}", "---")
|
||||
if name == 'D-STAR':
|
||||
target = raw_target if raw_target else "---"
|
||||
else:
|
||||
target = current_target
|
||||
target = raw_target if raw_target not in ['', '0', 'ALL'] else "---"
|
||||
if name == 'YSF' and 'dg-id' in p:
|
||||
dg_id = str(p.get('dg-id')).strip()
|
||||
if dg_id:
|
||||
target = f"DG-ID {dg_id}" if target == "---" else f"{target} (DG {dg_id})"
|
||||
|
||||
mem_ref = last_seen_reflector.get(f"{cid}_{name}", "---")
|
||||
pack_ref = str(p.get('reflector', '')).strip()
|
||||
|
||||
ref_slot = mem_ref if mem_ref != "---" else (pack_ref if pack_ref else "---")
|
||||
|
||||
active_calls[cid][k] = {'src': src, 'dst': target, 'ext': str(p.get('src_ext', ''))}
|
||||
client_telemetry[cid].update({"ts1":"","ts2":"","alt": f"{ico} {name}: {src} ➔ {target}"})
|
||||
active_calls[cid][k] = {'src': src, 'dst': target, 'slot': ref_slot, 'ext': str(p.get('src_ext', '')), 'source': str(p.get('source', '')), 'mode': str(p.get('mode', ''))}
|
||||
|
||||
target_str = target if target != "---" else "NET"
|
||||
client_telemetry[cid].update({"ts1":"","ts2":"","alt": f"{ico} {name}: {src} ➔ {target_str} ({ref_slot})"})
|
||||
notify_update()
|
||||
|
||||
elif act in ['end', 'lost']:
|
||||
info = active_calls[cid].get(k, {'src': '---', 'dst': '---', 'ext': ''})
|
||||
p.update({'src_id': info['src'], 'dst_id': info['dst'], 'src_ext': info['ext']})
|
||||
info = active_calls[cid].get(k, {'src': '---', 'dst': '---', 'slot': '---', 'ext': '', 'source': '', 'mode': ''})
|
||||
|
||||
p.update({'src_id': info['src'], 'dst_id': info['dst'], 'slot': info['slot'], 'src_ext': info['ext'], 'source': info['source'], 'mode': info['mode']})
|
||||
|
||||
save_to_sqlite(cid, p, protocol=name)
|
||||
client_telemetry[cid]["alt"] = f"{'✅' if act=='end' else '⚠️'} {name}: {info['src']}"
|
||||
save_cache(client_telemetry)
|
||||
@@ -616,16 +644,16 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"MQTT MSG ERROR: {e}")
|
||||
|
||||
mqtt_id = config['mqtt'].get('client_id', 'flask_backend_generic')
|
||||
mqtt_id = config.get('mqtt', {}).get('client_id', 'flask_backend_generic')
|
||||
mqtt_backend = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, mqtt_id)
|
||||
mqtt_backend.username_pw_set(config['mqtt']['user'], config['mqtt']['password'])
|
||||
mqtt_backend.username_pw_set(config.get('mqtt', {}).get('user', ''), config.get('mqtt', {}).get('password', ''))
|
||||
mqtt_backend.on_connect = on_connect
|
||||
mqtt_backend.on_disconnect = on_disconnect
|
||||
mqtt_backend.on_message = on_message
|
||||
try:
|
||||
mqtt_backend.connect_async(config['mqtt']['broker'], config['mqtt']['port'])
|
||||
mqtt_backend.connect_async(config.get('mqtt', {}).get('broker', 'localhost'), config.get('mqtt', {}).get('port', 1883))
|
||||
mqtt_backend.loop_start()
|
||||
logger.info(f"Avvio connessione MQTT asincrona verso {config['mqtt']['broker']}...")
|
||||
logger.info(f"Avvio connessione MQTT asincrona verso {config.get('mqtt', {}).get('broker')}...")
|
||||
except Exception as e:
|
||||
logger.error(f"Errore critico nell'inizializzazione MQTT: {e}")
|
||||
|
||||
@@ -652,8 +680,17 @@ def add_security_headers(resp):
|
||||
resp.headers['Cache-Control'] = 'no-store'
|
||||
return resp
|
||||
|
||||
def get_git_commit():
|
||||
try:
|
||||
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip()
|
||||
except Exception:
|
||||
return "sconosciuta"
|
||||
|
||||
SERVER_COMMIT = get_git_commit()
|
||||
|
||||
@app.route('/')
|
||||
def index(): return render_template('index.html')
|
||||
def index():
|
||||
return render_template('index.html', git_commit=SERVER_COMMIT)
|
||||
|
||||
@app.route('/api/clients')
|
||||
def get_clients():
|
||||
@@ -665,28 +702,56 @@ def get_clients():
|
||||
def get_logs():
|
||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||
c = conn.cursor()
|
||||
c.execute("SELECT timestamp, client_id, protocol, source_id, target, slot, duration, ber, source_ext, rssi FROM radio_logs ORDER BY id DESC LIMIT 60")
|
||||
c.execute("SELECT timestamp, client_id, protocol, source_id, target, slot, duration, ber, source_ext, rssi, source_conn, ysf_mode FROM radio_logs ORDER BY id DESC LIMIT 60")
|
||||
logs = c.fetchall()
|
||||
conn.close()
|
||||
return jsonify(logs)
|
||||
|
||||
@app.route('/api/states', methods=['GET'])
|
||||
def get_states():
|
||||
# Filtriamo le chiavi di servizio (come '_last_prog') per non mandarle all'interfaccia
|
||||
clean_versions = {}
|
||||
for c, d in node_versions.items():
|
||||
clean_versions[c] = {k: v for k, v in d.items() if not k.startswith('_')}
|
||||
|
||||
# --- INIEZIONE DMR NETWORKS DA CONFIGURAZIONE (Versione 4.0) ---
|
||||
enriched_gateway_states = dict(gateway_states)
|
||||
|
||||
for cid, confs in device_configs.items():
|
||||
if 'dmrgateway' in confs:
|
||||
dmr_conf = confs['dmrgateway']
|
||||
if isinstance(dmr_conf, dict) and 'raw_text' in dmr_conf:
|
||||
raw = dmr_conf['raw_text']
|
||||
active_dmr_nets = []
|
||||
|
||||
# Cerca le sezioni [DMR Network 1] fino a [DMR Network 5]
|
||||
for i in range(1, 6):
|
||||
section_name = f"[DMR Network {i}]"
|
||||
if section_name in raw:
|
||||
# Estrai blocco della sezione
|
||||
block = raw.split(section_name)[1].split('[')[0]
|
||||
# Cerca Enabled=1
|
||||
if re.search(r'^Enabled\s*=\s*1', block, re.MULTILINE | re.IGNORECASE):
|
||||
# Cerca Name= (es. Name=BM_2222)
|
||||
m_name = re.search(r'^Name\s*=\s*(.+)', block, re.MULTILINE | re.IGNORECASE)
|
||||
net_name = m_name.group(1).strip() if m_name else f"Net {i}"
|
||||
active_dmr_nets.append(net_name)
|
||||
|
||||
if active_dmr_nets:
|
||||
if cid not in enriched_gateway_states:
|
||||
enriched_gateway_states[cid] = {}
|
||||
enriched_gateway_states[cid]['DMR_NETS'] = active_dmr_nets
|
||||
# ----------------------------------------------------------------
|
||||
|
||||
return jsonify({
|
||||
"states": client_states,
|
||||
"telemetry": client_telemetry,
|
||||
"health": device_health,
|
||||
"networks": network_mapping,
|
||||
"info": node_info,
|
||||
"general": node_general,
|
||||
"last_seen": seen_ages(),
|
||||
"uptime": int(time.time() - START_TIME),
|
||||
"versions": clean_versions
|
||||
"versions": clean_versions,
|
||||
"gateway_states": enriched_gateway_states
|
||||
})
|
||||
|
||||
@app.route('/api/stats')
|
||||
@@ -1188,7 +1253,9 @@ def get_config_api():
|
||||
return jsonify({
|
||||
"update_schedule": cfg.get("update_schedule", "03:00"),
|
||||
"url_dmr": cfg.get("id_urls", {}).get("dmr", ""),
|
||||
"url_nxdn": cfg.get("id_urls", {}).get("nxdn", "")
|
||||
"url_nxdn": cfg.get("id_urls", {}).get("nxdn", ""),
|
||||
"log_max_mb": cfg.get("log_max_mb", 50),
|
||||
"log_backup_count": cfg.get("log_backup_count", 10)
|
||||
})
|
||||
|
||||
@app.route('/api/config', methods=['POST'])
|
||||
@@ -1201,6 +1268,13 @@ def save_config_api():
|
||||
schedule = str(d.get("update_schedule", "03:00")).strip()
|
||||
url_dmr = str(d.get("url_dmr", "")).strip()
|
||||
url_nxdn = str(d.get("url_nxdn", "")).strip()
|
||||
|
||||
try:
|
||||
log_max_mb = int(d.get("log_max_mb", 50))
|
||||
log_backup_count = int(d.get("log_backup_count", 10))
|
||||
except ValueError:
|
||||
return err("Invalid log rotation settings")
|
||||
|
||||
if not TIME_RE.match(schedule):
|
||||
return err("Invalid time (use HH:MM)")
|
||||
for u in (url_dmr, url_nxdn):
|
||||
@@ -1212,6 +1286,9 @@ def save_config_api():
|
||||
cfg.setdefault("id_urls", {})
|
||||
cfg["id_urls"]["dmr"] = url_dmr
|
||||
cfg["id_urls"]["nxdn"] = url_nxdn
|
||||
cfg["log_max_mb"] = log_max_mb
|
||||
cfg["log_backup_count"] = log_backup_count
|
||||
|
||||
write_config(cfg)
|
||||
audit(auth['username'], '-', 'EDIT_SERVER_CONFIG')
|
||||
return jsonify({"success": True})
|
||||
@@ -1252,6 +1329,43 @@ def save_config_file():
|
||||
audit(auth['username'], cid, f"EDIT_CONFIG_{service.upper()}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
@app.route('/api/server_update/check', methods=['GET'])
|
||||
def check_server_update():
|
||||
auth = get_auth()
|
||||
if not auth or auth['role'] != 'admin':
|
||||
return err("Unauthorized", 403)
|
||||
|
||||
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})
|
||||
except Exception as e:
|
||||
logger.error(f"Errore controllo aggiornamenti server: {e}")
|
||||
return jsonify({"success": False, "error": "Impossibile verificare aggiornamenti"})
|
||||
|
||||
@app.route('/api/server_update/apply', methods=['POST'])
|
||||
def apply_server_update():
|
||||
auth = get_auth()
|
||||
if not auth or auth['role'] != 'admin':
|
||||
return err("Unauthorized", 403)
|
||||
|
||||
try:
|
||||
audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE')
|
||||
subprocess.run(['git', 'pull', '--ff-only'], timeout=30, cwd=BASE_DIR, check=True)
|
||||
def restart_server():
|
||||
time.sleep(2)
|
||||
os._exit(1)
|
||||
threading.Thread(target=restart_server, daemon=True).start()
|
||||
return jsonify({"success": True})
|
||||
except subprocess.CalledProcessError as e:
|
||||
logger.error(f"Errore durante git pull: {e}")
|
||||
return err("Conflitto o errore durante il git pull.")
|
||||
except Exception as e:
|
||||
logger.error(f"Errore aggiornamento server: {e}")
|
||||
return err(str(e))
|
||||
|
||||
@app.route('/manifest.json')
|
||||
def serve_manifest():
|
||||
return send_from_directory(BASE_DIR, 'manifest.json')
|
||||
|
||||
+3
-1
@@ -37,5 +37,7 @@
|
||||
"id_urls": {
|
||||
"dmr": "https://radioid.net/static/dmrid.dat",
|
||||
"nxdn": "https://radioid.net/static/nxdn.csv"
|
||||
}
|
||||
},
|
||||
"log_max_mb": 50,
|
||||
"log_backup_count": 10
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const CACHE_NAME = 'fleet-c2-v3'; // incrementare a ogni modifica degli asset precaricati
|
||||
const CACHE_NAME = 'fleet-c2-v5';
|
||||
const PRECACHE_URLS = [
|
||||
'/',
|
||||
'/manifest.json',
|
||||
@@ -6,8 +6,6 @@ const PRECACHE_URLS = [
|
||||
];
|
||||
|
||||
// --- 1. INSTALL: precache "best effort" -------------------------------------
|
||||
// Se un file manca (es. icona non ancora caricata) l'installazione NON fallisce:
|
||||
// un SW che non si installa significa niente notifiche push.
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME)
|
||||
@@ -26,8 +24,6 @@ self.addEventListener('activate', event => {
|
||||
});
|
||||
|
||||
// --- 3. FETCH: network-first, cache come ripiego offline ---------------------
|
||||
// Gestiamo solo le GET della nostra origine. API e WebSocket (socket.io) passano
|
||||
// sempre direttamente dalla rete: i dati della flotta non vanno mai serviti "vecchi".
|
||||
self.addEventListener('fetch', event => {
|
||||
const req = event.request;
|
||||
if (req.method !== 'GET') return;
|
||||
@@ -80,8 +76,6 @@ self.addEventListener('push', event => {
|
||||
icon: '/icon-512.png',
|
||||
badge: '/icon-512.png',
|
||||
vibrate: [200, 100, 200],
|
||||
// Stesso tag = la nuova notifica dello stesso nodo sostituisce la precedente
|
||||
// (invece di accumulare 10 notifiche) e rifà vibrare/suonare.
|
||||
tag: data.tag || 'fleet-alert',
|
||||
renotify: true,
|
||||
data: {
|
||||
@@ -100,8 +94,6 @@ self.addEventListener('push', event => {
|
||||
});
|
||||
|
||||
// --- 5. CLICK SULLA NOTIFICA -------------------------------------------------
|
||||
// Click sul corpo O su "Apri Dashboard": porta in primo piano la finestra già aperta,
|
||||
// altrimenti ne apre una nuova. "Chiudi" chiude soltanto.
|
||||
self.addEventListener('notificationclick', event => {
|
||||
event.notification.close();
|
||||
if (event.action === 'close') return;
|
||||
|
||||
+526
-392
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user