GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — IG_ZCS_PIX/first_pixoo.py at main · ivan-grasso/IG_ZCS_PIX Expand file tree/ Copy pathfirst_pixoo.pyMore file actions 450 lines (411 loc) · 16.6 KB / Copy pathfirst_pixoo.pyFile metadata and controls450 lines (411 loc) · 16.6 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 from __future__ import annotations import argparse import logging import os from logging.handlers import RotatingFileHandler import time from getpass import getpass from pathlib import Path from datetime import datetime from config import FIREBASE_API_KEY, GRAPHQL_URL, PIXOO_IP, REFRESH_SECONDS, ZCS_EMAIL, ZCS_SERIAL from settings import ( SHOW_WEATHER, WEATHER_CITY, WEATHER_COUNTRY_CODE, WEATHER_REFRESH_MINUTES, WEATHER_TIMEOUT_SECONDS, WEATHER_MODE, FORECAST_SWITCH_HOUR, SHOW_FORECAST_PAGE, FORECAST_DAYS, FORECAST_PAGE_SECONDS, FORECAST_TRANSITION_SECONDS, EMAIL_ALERTS, EMAIL_FROM, EMAIL_TO, SMTP_HOST, SMTP_PORT, SMTP_USE_TLS, SMTP_USE_SSL, SMTP_TIMEOUT_SECONDS, SMTP_TLS_COMPATIBILITY_MODE, SMTP_USERNAME, SMTP_PASSWORD_ENV, EMAIL_ON_EV_OPPORTUNITY, EV_EMAIL_PRODUCTION_W, EV_EMAIL_EXPORT_W, EV_EMAIL_BATTERY_PERCENT, EV_EMAIL_RESET_PRODUCTION_W, EV_EMAIL_RESET_EXPORT_W, EV_BUZZER_ENABLED, EV_BUZZER_ACTIVE_MS, EV_BUZZER_OFF_MS, EV_BUZZER_TOTAL_MS, EMAIL_ON_PIXOO_ERROR, EMAIL_ON_AUTH_ERROR, EMAIL_ON_ZCS_ERROR, TECHNICAL_EMAIL_COOLDOWN_MINUTES, SHOW_STARTUP_STATUS, STARTUP_LOGO_SECONDS, STARTUP_STATUS_SECONDS, PROJECT_NAME, PROJECT_VERSION, HOME_CITY, ) from ig_zcs_pix.auth.manager import FirebaseTokenManager from ig_zcs_pix.api.graphql import GraphQLClient from ig_zcs_pix.providers.zcs import ZCSProvider from ig_zcs_pix.pixoo.client import PixooClient from ig_zcs_pix.pixoo.renderer import FirstLightRenderer from ig_zcs_pix.pixoo.forecast_page import ForecastPageRenderer from ig_zcs_pix.pixoo.startup_status import StartupStatusRenderer from ig_zcs_pix.weather.open_meteo import OpenMeteoClient from ig_zcs_pix.notifications.email_notifier import EmailConfig, EmailNotifier from ig_zcs_pix.notifications.energy_email import EnergyEmailAssistant, EnergyEmailRules from ig_zcs_pix.runtime_platform import add_runtime_marker, detect_runtime_platform from ig_zcs_pix.models.telemetry import SolarTelemetry LOG_DIR = Path("logs") LOG_FILE = LOG_DIR / "ig_zcs_pix.log" def setup_logging() -> logging.Logger: LOG_DIR.mkdir(exist_ok=True) logger = logging.getLogger("ig_zcs_pix") logger.setLevel(logging.INFO) if not logger.handlers: handler = RotatingFileHandler(LOG_FILE, maxBytes=1_000_000, backupCount=3, encoding="utf-8") handler.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")) logger.addHandler(handler) return logger def test_ev_animation(seconds: int = 18) -> None: """Mostra sul Pixoo l'animazione EV usando dati sintetici, senza login ZCS.""" runtime_code, runtime_name = detect_runtime_platform() print(f"IG_ZCS_PIX — test animazione EV | {runtime_name}") pixoo = PixooClient(PIXOO_IP) pixoo.test_connection() pixoo.reset_picture_id() renderer = FirstLightRenderer() renderer.set_weather("33°") telemetry = SolarTelemetry( pv_power_w=4700, load_power_w=1110, battery_percent=100, battery_power_w=0, grid_export_w=3570, grid_import_w=0, self_power_w=1130, raw={}, read_at=datetime.now(), ) total_frames = max(8, int(seconds)) for frame in range(total_frames): renderer.set_frame(frame) renderer.set_refresh_fill(min(64, frame * 4)) image = renderer.render(telemetry) add_runtime_marker(image, runtime_code) pixoo.push_image(image, speed_ms=1000) if frame == 0 and EV_BUZZER_ENABLED: try: pixoo.play_buzzer( active_ms=EV_BUZZER_ACTIVE_MS, off_ms=EV_BUZZER_OFF_MS, total_ms=EV_BUZZER_TOTAL_MS, ) except Exception as exc: print(f"Buzzer non disponibile: {exc}") print(f"\rFrame EV {frame + 1}/{total_frames}", end="", flush=True) time.sleep(1) print("\nTest completato.") def main() -> None: parser = argparse.ArgumentParser(description="IG_ZCS_PIX") parser.add_argument( "--test-ev-animation", nargs="?", const=18, type=int, metavar="SECONDI", help="prova auto, ruote e ricarica sul Pixoo senza collegarsi a ZCS", ) args = parser.parse_args() if args.test_ev_animation is not None: test_ev_animation(args.test_ev_animation) return logger = setup_logging() email_config = EmailConfig.from_values( enabled=EMAIL_ALERTS, host=SMTP_HOST, port=SMTP_PORT, use_tls=SMTP_USE_TLS, use_ssl=SMTP_USE_SSL, username=SMTP_USERNAME, sender=EMAIL_FROM, recipients=EMAIL_TO, password_env=SMTP_PASSWORD_ENV, timeout_seconds=SMTP_TIMEOUT_SECONDS, tls_compatibility_mode=SMTP_TLS_COMPATIBILITY_MODE, ) email_notifier = EmailNotifier(email_config, logger=logger) energy_email = EnergyEmailAssistant( notifier=email_notifier, rules=EnergyEmailRules( production_threshold_w=EV_EMAIL_PRODUCTION_W, export_threshold_w=EV_EMAIL_EXPORT_W, battery_threshold_percent=EV_EMAIL_BATTERY_PERCENT, reset_production_w=EV_EMAIL_RESET_PRODUCTION_W, reset_export_w=EV_EMAIL_RESET_EXPORT_W, ), enabled=EMAIL_ON_EV_OPPORTUNITY, logger=logger, ) runtime_code, runtime_name = detect_runtime_platform() logger.info("Piattaforma rilevata: %s (%s)", runtime_name, runtime_code) if EMAIL_ALERTS: try: email_config.validate() logger.info( "SMTP configurato | server %s:%s | SSL=%s | STARTTLS=%s | destinatari=%s", SMTP_HOST, SMTP_PORT, SMTP_USE_SSL, SMTP_USE_TLS, ", ".join(email_config.recipients), ) except Exception as exc: logger.error("SMTP non disponibile: %s", exc) else: logger.info("Notifiche email disattivate") print(f"\nIG_ZCS_PIX — v1.0.0 | {runtime_name}\n") password = os.environ.get("IG_ZCS_PIX_ZCS_PASSWORD", "").strip() if not password: if os.isatty(0): password = getpass("Password ZCS: ") else: raise RuntimeError( "Password ZCS assente: impostare IG_ZCS_PIX_ZCS_PASSWORD " "nel file nas/secrets.env" ) print("\n[1/5] Login ZCS...") token_manager = FirebaseTokenManager( api_key=FIREBASE_API_KEY, email=ZCS_EMAIL, password=password, refresh_margin_seconds=300, ) token_manager.login() logger.info("Login Firebase OK") print(" OK") print("[2/5] Connessione GraphQL...") provider = ZCSProvider(GraphQLClient(GRAPHQL_URL, token_manager), ZCS_SERIAL) print(" OK") print(f"[3/5] Connessione Pixoo {PIXOO_IP}...") pixoo = PixooClient(PIXOO_IP) pixoo.test_connection() pixoo.reset_picture_id() logger.info("Pixoo connesso: %s", PIXOO_IP) print(" OK") weather = None snapshot = None weather_ok = False if SHOW_WEATHER: print(f"[4/5] Meteo Open-Meteo: {WEATHER_CITY}...") weather = OpenMeteoClient( city=WEATHER_CITY, country_code=WEATHER_COUNTRY_CODE, refresh_minutes=WEATHER_REFRESH_MINUTES, timeout=WEATHER_TIMEOUT_SECONDS, mode=WEATHER_MODE, switch_hour=FORECAST_SWITCH_HOUR, ) snapshot = weather.get_current(force=True) logger.info("Meteo iniziale OK: %.1f°C", snapshot.temperature_c) weather_ok = True print(f" OK — {snapshot.temperature_c:.1f}°C") else: print("[4/5] Meteo disattivato") renderer = FirstLightRenderer() forecast_renderer = ForecastPageRenderer() startup_renderer = StartupStatusRenderer() if SHOW_STARTUP_STATUS: try: # Fade progressivo nei 7 secondi iniziali. stage_delays = (1.5, 1.5, 1.5, max(0.5, STARTUP_LOGO_SECONDS - 4.5)) for stage, delay in enumerate(stage_delays, start=1): brand_image = startup_renderer.render_brand( project_name=PROJECT_NAME, version=PROJECT_VERSION, stage=stage, ) add_runtime_marker(brand_image, runtime_code) pixoo.push_image(brand_image, speed_ms=1000) time.sleep(delay) logger.info("Boot logo/versione/autore inviato | durata=%ss", STARTUP_LOGO_SECONDS) status_image = startup_renderer.render_status( zcs_ok=True, weather_ok=weather_ok or not SHOW_WEATHER, email_ok=EMAIL_ALERTS, city=HOME_CITY, ) add_runtime_marker(status_image, runtime_code) pixoo.push_image(status_image, speed_ms=1000) logger.info("Boot test/città inviato | durata=%ss", STARTUP_STATUS_SECONDS) time.sleep(STARTUP_STATUS_SECONDS) except Exception as exc: logger.warning("Schermata iniziale non inviata: %s", exc) print("[5/5] Dashboard live. Premi CTRL+C per terminare.\n") telemetry = None last_fetch = 0.0 last_heartbeat = time.monotonic() started_at = time.monotonic() frame = 0 showing_forecast = False ev_buzzer_latched = False forecast_started = 0.0 forecast_rows = [] synced_forecast = [] last_dashboard_log = 0.0 last_forecast_log = 0.0 while True: try: now_mono = time.monotonic() elapsed = now_mono - last_fetch if telemetry is None or elapsed >= REFRESH_SECONDS: telemetry = provider.get_live_data() last_fetch = time.monotonic() frame = 0 logger.info( "Telemetry OK | FV %.0fW | Casa %.0fW | Batt %.0f%% %.0fW | Rete %.0fW %s", telemetry.pv_power_w, telemetry.load_power_w, telemetry.battery_percent, telemetry.battery_power_w, telemetry.grid_power_w, telemetry.grid_mode, ) energy_email.evaluate( production_w=telemetry.pv_power_w, battery_percent=telemetry.battery_percent, export_w=telemetry.grid_export_w, house_load_w=telemetry.load_power_w, ) if weather is not None: # Footer e pagina previsioni devono riferirsi allo stesso giorno. # La prima riga della pagina è domani: il footer usa esattamente # la stessa data, lo stesso codice meteo e la stessa massima. synced_forecast = weather.get_forecast(FORECAST_DAYS) if synced_forecast: footer_day = synced_forecast[0] renderer.set_weather(f"{round(footer_day.temp_max_c):.0f}°") renderer.set_weather_state( footer_day.weather_code, True, footer_day.forecast_date, ) # A fine ciclo mostra per alcuni secondi la pagina meteo 4 giorni. if ( SHOW_FORECAST_PAGE and weather is not None and not showing_forecast and elapsed >= REFRESH_SECONDS - FORECAST_PAGE_SECONDS ): forecast_rows = synced_forecast showing_forecast = True forecast_started = time.monotonic() if showing_forecast: forecast_elapsed = time.monotonic() - forecast_started transition_progress = min( 1.0, forecast_elapsed / max(0.1, FORECAST_TRANSITION_SECONDS), ) forecast_image = forecast_renderer.render( forecast_rows, transition_progress=transition_progress, frame=frame, ) add_runtime_marker(forecast_image, runtime_code) pixoo.push_image(forecast_image, speed_ms=1000) if time.monotonic() - last_forecast_log >= FORECAST_PAGE_SECONDS: logger.info( "Pagina Meteo 4 gg inviata al Pixoo | righe=%d | frame=%d", len(forecast_rows), frame, ) last_forecast_log = time.monotonic() if forecast_elapsed >= FORECAST_PAGE_SECONDS: showing_forecast = False frame += 1 time.sleep(1) continue renderer.set_refresh_fill(min(64, int((elapsed / REFRESH_SECONDS) * 64))) renderer.set_frame(frame) dashboard_image = renderer.render(telemetry) add_runtime_marker(dashboard_image, runtime_code) try: pixoo.push_image(dashboard_image, speed_ms=1000) if now_mono - last_dashboard_log >= REFRESH_SECONDS: logger.info( "Dashboard inviata al Pixoo | frame=%d | FV %.0fW | Casa %.0fW | Batt %.0f%% | Rete %.0fW %s", frame, telemetry.pv_power_w, telemetry.load_power_w, telemetry.battery_percent, telemetry.grid_power_w, telemetry.grid_mode, ) last_dashboard_log = now_mono except Exception as exc: logger.warning("Invio Pixoo fallito: %s", exc) if EMAIL_ON_PIXOO_ERROR: try: email_notifier.send( subject="IG_ZCS_PIX — Pixoo non raggiungibile", body=f"Errore durante l'invio al Pixoo {PIXOO_IP}:\n\n{exc}", key="pixoo_error", cooldown_minutes=TECHNICAL_EMAIL_COOLDOWN_MINUTES, ) except Exception as email_exc: logger.warning("Email errore Pixoo non inviata: %s", email_exc) time.sleep(2) pixoo = PixooClient(PIXOO_IP) pixoo.test_connection() pixoo.reset_picture_id() logger.info("Pixoo riconnesso") pixoo.push_image(dashboard_image, speed_ms=1000) # Il buzzer segue esattamente la comparsa dell’auto: un solo # segnale sul fronte di salita, poi si riarma quando l’auto sparisce. if not renderer.ev_visible: ev_buzzer_latched = False elif EV_BUZZER_ENABLED and not ev_buzzer_latched: try: pixoo.play_buzzer( active_ms=EV_BUZZER_ACTIVE_MS, off_ms=EV_BUZZER_OFF_MS, total_ms=EV_BUZZER_TOTAL_MS, ) ev_buzzer_latched = True logger.info("Buzzer EV emesso: alta produzione") except Exception as buzzer_exc: logger.warning("Buzzer EV non emesso: %s", buzzer_exc) print( f"\rFV {telemetry.pv_power_w:.0f}W | Casa {telemetry.load_power_w:.0f}W | " f"Batt {telemetry.battery_percent:.0f}% {telemetry.battery_power_w:+.0f}W | " f"Rete {telemetry.grid_power_w:.0f}W {telemetry.grid_mode} ", end="", flush=True, ) if now_mono - last_heartbeat >= 300: uptime = int(now_mono - started_at) h, rem = divmod(uptime, 3600) m, s = divmod(rem, 60) logger.info("Running | uptime %02d:%02d:%02d", h, m, s) last_heartbeat = now_mono frame += 1 time.sleep(1) except KeyboardInterrupt: logger.info("Arresto manuale") print("\nTerminato.") break except Exception as exc: logger.exception("Errore ciclo principale: %s", exc) print(f"\nERRORE: {exc}") if EMAIL_ON_ZCS_ERROR: try: email_notifier.send( subject="IG_ZCS_PIX — Errore API o ciclo principale", body=f"Si è verificato un errore nel ciclo principale:\n\n{exc}", key="main_loop_error", cooldown_minutes=TECHNICAL_EMAIL_COOLDOWN_MINUTES, ) except Exception as email_exc: logger.warning("Email errore ciclo non inviata: %s", email_exc) time.sleep(5) if __name__ == "__main__": main() |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |