-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathntp_time.py
More file actions
329 lines (248 loc) · 8.44 KB
/
ntp_time.py
File metadata and controls
329 lines (248 loc) · 8.44 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
# ============================================================================
# NTP_TIME.PY - Sincronizacion horaria para Espana
# PSIC-O-TRONIC - Modo Mi Consulta
# ============================================================================
import ntptime
import time
import machine
# Offset horario Espana (CET = +1, CEST = +2)
# Simplificado: +1 en invierno (nov-mar), +2 en verano (mar-oct)
TIMEZONE_WINTER = 1 # CET
TIMEZONE_SUMMER = 2 # CEST
# Dias de la semana en espanol (abreviados, 3 chars)
DIAS_SEMANA = ["Lun", "Mar", "Mie", "Jue", "Vie", "Sab", "Dom"]
# Meses en espanol (abreviados, 3 chars)
MESES = ["Ene", "Feb", "Mar", "Abr", "May", "Jun",
"Jul", "Ago", "Sep", "Oct", "Nov", "Dic"]
def is_dst(month, day, weekday):
"""
Determina si estamos en horario de verano (CEST).
Espana: ultimo domingo de marzo a ultimo domingo de octubre.
Args:
month: Mes (1-12)
day: Dia del mes (1-31)
weekday: Dia de la semana (0=lunes, 6=domingo)
Returns:
True si es horario de verano
"""
# Abril a septiembre: siempre verano
if 4 <= month <= 9:
return True
# Noviembre a febrero: siempre invierno
if month <= 2 or month >= 11:
return False
# Marzo: verano desde el ultimo domingo (a las 2:00 -> 3:00)
if month == 3:
# Calcular que dia de la semana fue el dia 31
# weekday actual + (31 - day) dias = weekday del 31
weekday_31 = (weekday + (31 - day)) % 7
# Ultimo domingo: retroceder desde 31 hasta encontrar domingo (6)
last_sunday = 31 - ((weekday_31 - 6) % 7)
return day >= last_sunday
# Octubre: invierno desde el ultimo domingo (a las 3:00 -> 2:00)
if month == 10:
weekday_31 = (weekday + (31 - day)) % 7
last_sunday = 31 - ((weekday_31 - 6) % 7)
return day < last_sunday
return False
def get_timezone_offset():
"""Obtiene offset actual de Espana en segundos"""
t = time.localtime()
if is_dst(t[1], t[2], t[6]):
return TIMEZONE_SUMMER * 3600
return TIMEZONE_WINTER * 3600
def is_time_valid():
"""
Verifica si el reloj tiene una fecha razonable.
Si el año es anterior a 2024, probablemente no se sincronizó.
Returns:
True si la fecha parece válida
"""
t = time.localtime()
return t[0] >= 2024 # Año >= 2024
def _log_current_time(prefix):
"""Log de la hora actual para debug."""
t = time.localtime()
print(f"[NTP] {prefix}: {t[0]}-{t[1]:02d}-{t[2]:02d} {t[3]:02d}:{t[4]:02d}:{t[5]:02d}")
def sync_time(max_retries=3):
"""
Sincroniza con servidor NTP con reintentos.
Args:
max_retries: Número máximo de intentos (default 3)
Returns:
True si exito, False si fallo
"""
_log_current_time("Antes de sync")
# Lista de servidores NTP a probar
ntp_servers = ["pool.ntp.org", "time.google.com", "time.windows.com"]
for server in ntp_servers:
print(f"[NTP] Probando servidor: {server}")
ntptime.host = server
for attempt in range(max_retries):
try:
ntptime.settime()
_log_current_time(f"Después de {server} (intento {attempt + 1})")
if is_time_valid():
# Verificar que la fecha cambió (no sigue en 1 de enero si estamos en otro día)
t = time.localtime()
print(f"[NTP] OK con {server}: {t[0]}-{t[1]:02d}-{t[2]:02d} {t[3]:02d}:{t[4]:02d}")
return True
else:
print(f"[NTP] Fecha inválida, reintentando...")
except Exception as e:
print(f"[NTP] Error {server} intento {attempt + 1}: {e}")
time.sleep(1)
print("[NTP] Fallo con todos los servidores")
return False
def get_local_time(debug=False):
"""
Obtiene hora local de Espana.
Returns:
Tupla (year, month, day, hour, minute, second, weekday, yearday)
"""
utc_secs = time.time()
utc_tuple = time.localtime(utc_secs)
offset = get_timezone_offset()
local = time.localtime(utc_secs + offset)
if debug:
print(f"[TIME] UTC secs: {utc_secs}")
print(f"[TIME] UTC: {utc_tuple[0]}-{utc_tuple[1]:02d}-{utc_tuple[2]:02d} {utc_tuple[3]:02d}:{utc_tuple[4]:02d}")
print(f"[TIME] Offset: {offset} secs ({offset//3600}h)")
print(f"[TIME] Local: {local[0]}-{local[1]:02d}-{local[2]:02d} {local[3]:02d}:{local[4]:02d}")
return local
def get_timestamp():
"""
Obtiene timestamp ISO para guardar en JSON.
Returns:
String "YYYY-MM-DDTHH:MM:SS"
"""
t = get_local_time()
return f"{t[0]:04d}-{t[1]:02d}-{t[2]:02d}T{t[3]:02d}:{t[4]:02d}:{t[5]:02d}"
def get_date_str():
"""
Obtiene fecha formateada para LCD (max 10 chars).
Returns:
String "Mie 27-Nov"
"""
t = get_local_time()
dia = DIAS_SEMANA[t[6]]
mes = MESES[t[1] - 1]
return f"{dia} {t[2]:02d}-{mes}"
def get_time_str():
"""
Obtiene hora formateada para LCD (5 chars).
Returns:
String "14:32"
"""
t = get_local_time()
return f"{t[3]:02d}:{t[4]:02d}"
def get_hour():
"""Obtiene hora actual (0-23)"""
return get_local_time()[3]
def get_minute():
"""Obtiene minuto actual (0-59)"""
return get_local_time()[4]
def get_weekday():
"""Obtiene dia de la semana (0=lunes, 6=domingo)"""
return get_local_time()[6]
def get_today_str():
"""
Obtiene fecha de hoy para comparaciones.
Returns:
String "YYYY-MM-DD"
"""
t = get_local_time()
return f"{t[0]:04d}-{t[1]:02d}-{t[2]:02d}"
def is_weekend():
"""True si es sabado o domingo"""
return get_weekday() >= 5
def is_work_hours():
"""
True si estamos en horario laboral.
L-V: 9:00-14:00 y 17:00-20:00
"""
if is_weekend():
return False
hour = get_hour()
minute = get_minute()
current = hour * 60 + minute
# Manana: 9:00 (540) a 14:00 (840)
# Tarde: 17:00 (1020) a 20:00 (1200)
morning = 540 <= current < 840
afternoon = 1020 <= current < 1200
return morning or afternoon
def is_emergency_hours():
"""
True si pueden llegar emergencias.
Cualquier dia hasta las 22:30
"""
hour = get_hour()
minute = get_minute()
current = hour * 60 + minute
# Hasta las 22:30 (1350 minutos)
return current <= 1350
def is_quiet_hours():
"""
True si estamos en horas de silencio (no notificaciones).
22:30 a 9:00
"""
hour = get_hour()
minute = get_minute()
current = hour * 60 + minute
# 22:30 (1350) a 23:59 (1439) o 00:00 (0) a 09:00 (540)
return current >= 1350 or current < 540
def minutes_until(target_hour, target_minute):
"""
Calcula minutos hasta una hora objetivo.
Args:
target_hour: Hora objetivo (0-23)
target_minute: Minuto objetivo (0-59)
Returns:
Minutos hasta esa hora (puede ser negativo si ya paso)
"""
t = get_local_time()
current = t[3] * 60 + t[4]
target = target_hour * 60 + target_minute
return target - current
def parse_timestamp(ts_str):
"""
Parsea timestamp ISO a tupla.
Args:
ts_str: "YYYY-MM-DDTHH:MM:SS"
Returns:
Tupla (year, month, day, hour, minute, second)
"""
try:
date_part, time_part = ts_str.split("T")
year, month, day = [int(x) for x in date_part.split("-")]
hour, minute, second = [int(x) for x in time_part.split(":")]
return (year, month, day, hour, minute, second)
except:
return None
def timestamp_to_display(ts_str):
"""
Convierte timestamp a formato corto para LCD.
Args:
ts_str: "YYYY-MM-DDTHH:MM:SS"
Returns:
String "14:32" o "27-Nov" si es otro dia
"""
parsed = parse_timestamp(ts_str)
if not parsed:
return "??:??"
today = get_today_str()
msg_date = f"{parsed[0]:04d}-{parsed[1]:02d}-{parsed[2]:02d}"
if msg_date == today:
return f"{parsed[3]:02d}:{parsed[4]:02d}"
else:
mes = MESES[parsed[1] - 1]
return f"{parsed[2]:02d}-{mes}"
# Test standalone
if __name__ == "__main__":
print("=== Test NTP Time ===")
print(f"Fecha: {get_date_str()}")
print(f"Hora: {get_time_str()}")
print(f"Timestamp: {get_timestamp()}")
print(f"Fin de semana: {is_weekend()}")
print(f"Horario laboral: {is_work_hours()}")
print(f"Horas de silencio: {is_quiet_hours()}")