improved cache logic

This commit is contained in:
Nick
2025-10-27 20:19:10 +01:00
parent 0ed2435536
commit 9b5fecd400
3 changed files with 79 additions and 42 deletions

View File

@@ -63,7 +63,7 @@ class TF5MixerController:
except socket.error as e:
print(f'Errore di connessione dopo {max_retries} tentativi: {e}')
self._disconnect() # Forza riconnessione al prossimo tentativo
self._disconnect()
if attempt < max_retries - 1:
time.sleep(0.1)
@@ -98,13 +98,30 @@ class TF5MixerController:
return {"channels": {}, "mixes": {}, "timestamp": 0}
def _save_cache(self):
"""Salva la cache nel file."""
"""Salva la cache nel file, convertendo -inf in null."""
try:
# Crea una copia della cache per la serializzazione
cache_to_save = self._prepare_cache_for_json(self._cache)
with open(CACHE_FILE, 'w', encoding='utf-8') as f:
json.dump(self._cache, f, indent=2, ensure_ascii=False)
json.dump(cache_to_save, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"⚠️ Errore nel salvataggio della cache: {e}")
def _prepare_cache_for_json(self, obj):
"""Converte ricorsivamente -inf in null per la serializzazione JSON."""
if isinstance(obj, dict):
return {k: self._prepare_cache_for_json(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [self._prepare_cache_for_json(item) for item in obj]
elif isinstance(obj, float):
# Converti -inf in null per JSON
if obj == float('-inf'):
return None
return obj
else:
return obj
def _is_cache_valid(self) -> bool:
"""Verifica se la cache è ancora valida."""
if not self._cache.get("channels"):
@@ -112,6 +129,12 @@ class TF5MixerController:
cache_age = time.time() - self._cache.get("timestamp", 0)
return cache_age < CACHE_DURATION
def _normalize_level_from_cache(self, level_value):
"""Normalizza il valore del livello dalla cache (gestisce None come -inf)."""
if level_value is None:
return float('-inf')
return level_value
def _update_channel_cache(self, channel: int):
"""Aggiorna la cache per un singolo canale leggendo dal mixer.
@@ -555,10 +578,16 @@ class TF5MixerController:
if not force_refresh and self._is_cache_valid():
cached_data = self._cache.get("channels", {}).get(str(channel))
if cached_data:
# Normalizza level_db (None -> -inf)
level_db = self._normalize_level_from_cache(cached_data.get("level_db"))
return {
"status": "success",
"source": "cache",
**cached_data
"channel": cached_data["channel"],
"name": cached_data["name"],
"on": cached_data["on"],
"level_db": level_db,
"pan": cached_data.get("pan")
}
# Altrimenti leggi dal mixer
@@ -613,10 +642,15 @@ class TF5MixerController:
if not force_refresh and self._is_cache_valid():
cached_data = self._cache.get("mixes", {}).get(str(mix_number))
if cached_data:
# Normalizza level_db (None -> -inf)
level_db = self._normalize_level_from_cache(cached_data.get("level_db"))
return {
"status": "success",
"source": "cache",
**cached_data
"mix": cached_data["mix"],
"name": cached_data["name"],
"on": cached_data["on"],
"level_db": level_db
}
# Altrimenti leggi dal mixer
@@ -664,11 +698,13 @@ class TF5MixerController:
for ch_str, info in self._cache.get("channels", {}).items():
if search_lower in info.get("name", "").lower():
# Normalizza level_db quando restituisci i risultati
level_db = self._normalize_level_from_cache(info.get("level_db"))
found_channels.append({
"channel": info["channel"],
"name": info["name"],
"on": info["on"],
"level_db": info["level_db"]
"level_db": level_db
})
# Ordina per numero canale
@@ -701,11 +737,13 @@ class TF5MixerController:
for mix_str, info in self._cache.get("mixes", {}).items():
if search_lower in info.get("name", "").lower():
# Normalizza level_db quando restituisci i risultati
level_db = self._normalize_level_from_cache(info.get("level_db"))
found_mixes.append({
"mix": info["mix"],
"name": info["name"],
"on": info["on"],
"level_db": info["level_db"]
"level_db": level_db
})
# Ordina per numero mix
@@ -781,5 +819,4 @@ class TF5MixerController:
"mixes": mixes,
"cache_age_seconds": int(cache_age),
"message": f"Riepilogo di {len(mixes)} mix (cache: {int(cache_age)}s fa)"
}
}