-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
465 lines (370 loc) · 12.7 KB
/
config.py
File metadata and controls
465 lines (370 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# ============================================================================
# CONFIG.PY - Configuración y Estadísticas Persistentes
# PSIC-O-TRONIC - Guardado en Flash del ESP32
# ============================================================================
import ujson
import os
# Importar sistema de errores
try:
from error_handler import report_error
ERROR_HANDLER_AVAILABLE = True
except ImportError:
ERROR_HANDLER_AVAILABLE = False
# Archivos de configuración
CONFIG_FILE = "/config.json"
STATS_FILE = "/stats.json"
# Configuración por defecto
DEFAULT_CONFIG = {
"wifi_ssid": "",
"wifi_pass": "",
"wifi_configured": False,
"brightness": 100,
"sound_enabled": True,
"version": "1.0",
"api_key": "",
"api_model": "gemini-2.5-flash-lite",
"data_version": "2.3", # Versión de estructura de datos
}
# Estadísticas por defecto
DEFAULT_STATS = {
"total_games": 0, # Partidas jugadas totales
"total_cases_solved": 0, # Casos resueltos totales
"best_streak": 0, # Mejor racha sin fallar
"best_streak_initials": "---", # Iniciales del récord racha
"survival_record": 0, # Récord modo survival
"survival_initials": "---", # Iniciales del récord survival
"history_progress": 0, # Progreso modo historia (capítulo)
"history_rank": "Interno", # Rango actual en modo historia
}
def file_exists(filename):
"""Comprueba si un archivo existe"""
try:
os.stat(filename)
return True
except OSError:
return False
def load_config():
"""Carga la configuración desde flash"""
if file_exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, "r") as f:
config = ujson.load(f)
# Merge con defaults por si hay campos nuevos
merged = DEFAULT_CONFIG.copy()
merged.update(config)
return merged
except ValueError as e:
print(f"[CONFIG] JSON corrupt: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("storage_corrupt", "config.json", e)
except Exception as e:
print(f"[CONFIG] Error loading: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("storage_read_error", str(e), e)
return DEFAULT_CONFIG.copy()
def save_config(config):
"""Guarda la configuración en flash"""
try:
with open(CONFIG_FILE, "w") as f:
ujson.dump(config, f)
return True
except OSError as e:
print(f"[CONFIG] Write error: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("storage_write_error", "config.json", e)
return False
except Exception as e:
print(f"[CONFIG] Error saving: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("unknown_error", f"save_config: {e}", e)
return False
def load_stats():
"""Carga las estadísticas desde flash"""
if file_exists(STATS_FILE):
try:
with open(STATS_FILE, "r") as f:
stats = ujson.load(f)
# Merge con defaults
merged = DEFAULT_STATS.copy()
merged.update(stats)
return merged
except ValueError as e:
print(f"[STATS] JSON corrupt: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("storage_corrupt", "stats.json", e)
except Exception as e:
print(f"[STATS] Error loading: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("storage_read_error", str(e), e)
return DEFAULT_STATS.copy()
def save_stats(stats):
"""Guarda las estadísticas en flash"""
try:
with open(STATS_FILE, "w") as f:
ujson.dump(stats, f)
return True
except OSError as e:
print(f"[STATS] Write error: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("storage_write_error", "stats.json", e)
return False
except Exception as e:
print(f"[STATS] Error saving: {e}")
if ERROR_HANDLER_AVAILABLE:
report_error("unknown_error", f"save_stats: {e}", e)
return False
def reset_stats():
"""Resetea todas las estadísticas"""
save_stats(DEFAULT_STATS.copy())
def update_stat(key, value):
"""Actualiza una estadística específica"""
stats = load_stats()
stats[key] = value
save_stats(stats)
def increment_stat(key, amount=1):
"""Incrementa una estadística numérica"""
stats = load_stats()
if key in stats and isinstance(stats[key], int):
stats[key] += amount
save_stats(stats)
return stats[key]
return None
# --- Funciones específicas de estadísticas ---
def record_game_start():
"""Registra inicio de partida"""
return increment_stat("total_games")
def record_case_solved():
"""Registra caso resuelto"""
return increment_stat("total_cases_solved")
def check_streak_record(streak, initials="???"):
"""
Comprueba y actualiza récord de racha.
Args:
streak: Racha actual
initials: Iniciales del jugador (3 chars)
Returns:
True si es nuevo récord
"""
stats = load_stats()
if streak > stats["best_streak"]:
stats["best_streak"] = streak
stats["best_streak_initials"] = initials[:3].upper()
save_stats(stats)
return True
return False
def check_survival_record(score, initials="???"):
"""
Comprueba y actualiza récord de survival.
Args:
score: Puntuación survival
initials: Iniciales del jugador (3 chars)
Returns:
True si es nuevo récord
"""
stats = load_stats()
if score > stats["survival_record"]:
stats["survival_record"] = score
stats["survival_initials"] = initials[:3].upper()
save_stats(stats)
return True
return False
def update_history_progress(chapter, rank):
"""Actualiza progreso del modo historia"""
stats = load_stats()
if chapter > stats["history_progress"]:
stats["history_progress"] = chapter
stats["history_rank"] = rank
save_stats(stats)
def get_stats_summary():
"""Retorna resumen de estadísticas para mostrar"""
stats = load_stats()
return {
"games": stats["total_games"],
"cases": stats["total_cases_solved"],
"streak": f"{stats['best_streak']} ({stats['best_streak_initials']})",
"survival": f"{stats['survival_record']} ({stats['survival_initials']})",
}
# --- WiFi Config ---
def get_wifi_config():
"""Obtiene configuración WiFi guardada"""
config = load_config()
if config["wifi_configured"]:
return config["wifi_ssid"], config["wifi_pass"]
return None, None
def save_wifi_config(ssid, password):
"""Guarda configuración WiFi"""
config = load_config()
config["wifi_ssid"] = ssid
config["wifi_pass"] = password
config["wifi_configured"] = True
return save_config(config)
def clear_wifi_config():
"""Borra configuración WiFi guardada"""
config = load_config()
config["wifi_ssid"] = ""
config["wifi_pass"] = ""
config["wifi_configured"] = False
return save_config(config)
def is_wifi_configured():
"""Comprueba si hay WiFi configurada"""
config = load_config()
return config["wifi_configured"]
# --- API Config ---
# Modelo por defecto
DEFAULT_MODEL = "gemini-2.5-flash-lite"
# === SISTEMA DE OFUSCACIÓN DE API KEY ===
# La key se almacena fragmentada y codificada para evitar detección
# por escáneres automáticos de GitHub/Google
# Fragmentos de la key por defecto (codificados con offset +3)
_K_PARTS = [
"DL}dV|DSWv", # Parte 1
"7w|3uZz3fo", # Parte 2
"xmi0Xykx:q", # Parte 3
";PFbv3{lL", # Parte 4
]
def _decode_key_part(encoded, offset=-3):
"""Decodifica un fragmento de key"""
return ''.join(chr(ord(c) + offset) for c in encoded)
def _get_default_key():
"""Reconstruye la API key por defecto"""
return ''.join(_decode_key_part(p) for p in _K_PARTS)
# Para compatibilidad con código existente
DEFAULT_API_KEY = None # Se calcula en runtime
def get_default_api_key():
"""Obtiene la API key por defecto (decodificada)"""
global DEFAULT_API_KEY
if DEFAULT_API_KEY is None:
DEFAULT_API_KEY = _get_default_key()
return DEFAULT_API_KEY
def get_api_config():
"""
Obtiene configuración de API.
Permite usar API key/modelo personalizado del flash,
pero auto-actualiza valores viejos obsoletos.
Returns:
Tupla (api_key, model)
"""
config = load_config()
key = config.get("api_key", "")
model = config.get("api_model", "")
# Keys viejas obsoletas (ofuscadas con +3 para evitar detección)
_OLD_ENCODED = [
"DL}dV|EV[f5O8vxl8loXDTYsz4yVkWX{vIv9Nm3", # Key original
"DL}dV|GfFi\\UfxRPb:ytS6prvv0byluK4gL7{Ej", # Key segunda
]
OLD_KEYS = [_decode_key_part(k) for k in _OLD_ENCODED]
# Lista de modelos viejos obsoletos (con cuota 0 o deprecados)
OLD_MODELS = [
"gemini-2.0-flash", # Cuota 0 en free tier
"gemini-1.5-flash", # Deprecado
]
# Si no hay key guardada O es una key vieja, usar la nueva por defecto
if not key or key in OLD_KEYS:
key = get_default_api_key()
# Si no hay modelo guardado O es un modelo viejo, usar el nuevo por defecto
if not model or model in OLD_MODELS:
model = DEFAULT_MODEL
return key, model
def save_api_config(api_key, model=None):
"""
Guarda configuración de API.
Args:
api_key: API Key de Gemini
model: Modelo a usar (opcional)
"""
config = load_config()
config["api_key"] = api_key
if model:
config["api_model"] = model
return save_config(config)
def clear_api_config():
"""Restaura API a valores por defecto"""
config = load_config()
config["api_key"] = ""
config["api_model"] = DEFAULT_MODEL
return save_config(config)
def parse_version(version_str):
"""
Parsea versión semver a tupla comparable.
Args:
version_str: String "X.Y" o "X.Y.Z"
Returns:
Tupla (major, minor, patch)
"""
try:
parts = str(version_str).split(".")
major = int(parts[0]) if len(parts) > 0 else 0
minor = int(parts[1]) if len(parts) > 1 else 0
patch = int(parts[2]) if len(parts) > 2 else 0
return (major, minor, patch)
except:
return (0, 0, 0)
def check_and_wipe_if_needed():
"""
Verifica si es necesario hacer wipe de datos por actualización.
Si data_version < 2.3, borra todos los datos guardados y crea
config fresh con data_version 2.3.
Returns:
bool: True si se hizo wipe, False si no
"""
config = load_config()
current_data_version = config.get("data_version", "0.0")
# Usar comparación semver correcta (2.10 > 2.3 correctamente)
current_ver = parse_version(current_data_version)
target_ver = parse_version("2.3")
# Si data_version < 2.3, hacer wipe
if current_ver < target_ver:
print(f"[CONFIG] Data version {current_data_version} < 2.3 - Wiping data...")
# Borrar todos los archivos de datos
try:
import os
# Borrar config y stats
try:
os.remove(CONFIG_FILE)
print("[CONFIG] Deleted config.json")
except:
pass
try:
os.remove(STATS_FILE)
print("[CONFIG] Deleted stats.json")
except:
pass
# Borrar carrera
try:
os.remove("/career_save.json")
print("[CONFIG] Deleted career_save.json")
except:
pass
# Crear config fresh con nueva data_version
fresh_config = DEFAULT_CONFIG.copy()
save_config(fresh_config)
print(f"[CONFIG] Created fresh config with data_version 2.3")
return True
except Exception as e:
print(f"[CONFIG] Error during wipe: {e}")
return False
return False
# Test standalone
if __name__ == "__main__":
print("=== Test Config/Stats ===")
# Test config
print("\n[Config]")
config = load_config()
print(f"Config actual: {config}")
# Test stats
print("\n[Stats]")
stats = load_stats()
print(f"Stats actuales: {stats}")
# Test incremento
print("\n[Incremento]")
new_val = increment_stat("total_games")
print(f"Total games ahora: {new_val}")
# Test récord
print("\n[Record]")
is_record = check_streak_record(5, "MGC")
print(f"Es record? {is_record}")
# Resumen
print("\n[Resumen]")
summary = get_stats_summary()
for k, v in summary.items():
print(f" {k}: {v}")