diff --git a/README.md b/README.md index dbcc0e4..a7becce 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ > [!WARNING] > This is an unofficial Generac MobileLink integration. Generac systems may change at anytime, which would break the functionality of this integration, and it should not be used for anything mission critical. If you would like an alternative for whole-home generators that allows you to drop the need to maintain a MobileLink subscription, please see the ongoing discussions [here](https://github.com/binarydev/ha-generac/issues/227) for local hardware solutions using GenMon and Raspberry Pi's. Shoutout to [Jeff Terrace](https://github.com/jterrace) for his [blog post](https://blog.jeffterrace.com/2025/10/free-from-generac-with-genmon.html) documenting how to set this up, so others can benefit from his experience! > -> As of July 26, 2026, this integration currently support logging in with your MyGenerac/MobileLink username and password to expose your devices to Home Assistant for monitoring and automation. +> As of July 26, 2026, this integration currently supports logging in with your MyGenerac/MobileLink username and password to expose your devices to Home Assistant for monitoring and automation. # Generac MobileLink/MyGenerac Home Assistant Integration @@ -9,16 +9,22 @@ **Custom Generac integration component with support for generators and propane tank monitors. It will set up the following platforms.** -| Platform | Entities created for each generator | -| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | -| `button` | `reset_service_timer`, `boost_polling` | -| `sensor` | `status`, `run_time`, `protection_time`, `activation_date`, `last_seen`, `connection_time`, `battery_voltage`, `device_type`, `dealer_email`, `dealer_name`, `dealer_phone`, `address`, `status_text`, `status_label`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, optional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | +| Platform | Entities created for each generator (by `entity_key`) | +| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | +| `button` | `reset_service_timer`, `boost_polling` | +| `sensor` | `status`, `run_time`, `protection_time`, `activation_date`, `last_seen`, `connection_time`, `battery_voltage`, `device_type`, `dealer_email`, `dealer_name`, `dealer_phone`, `address`, `status_text`, `status_label`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, plus conditional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | +| `weather` | conditional `weather` | +| `image` | conditional `hero_image` | -| Platform | Entities created for each propane tank monitor | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning`, plus conditional `subscription_dunning` | -| `sensor` | `status`, `capacity`, `fuel_level`, `remaining_fuel`, `estimated_runtime`, `fuel_type`, `orientation`, `last_reading_date`, `battery_level`, `address`, `device_type`, optional `signal_strength`, `device_battery_level`, `outdoor_temperature` | +| Platform | Entities created for each propane tank monitor (by `entity_key`) | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, plus conditional `subscription_dunning` | +| `sensor` | `status`, `capacity`, `fuel_level`, `remaining_fuel`, `estimated_runtime`, `fuel_type`, `orientation`, `last_reading`, `battery_level`, `address`, `device_type`, plus conditional `signal_strength`, `device_battery_level`, `outdoor_temperature` | +| `weather` | conditional `weather` | +| `image` | conditional `hero_image` | + +> _Note:_ The tables above list each entity's stable `entity_key` (unique ID suffix). On fresh installs, Home Assistant generates entity IDs from friendly display names (for example, `Outage Boost Poll` for `boost_polling` and `Reset Maintenance Timer` for `reset_service_timer`), while existing installs preserve their entity IDs across upgrades. ![example][exampleimg] @@ -83,7 +89,7 @@ Fast polling activates automatically whenever any generator is **Running**, **Ex You can also trigger fast polling manually (for example, from an automation triggered by a utility power-loss sensor) using either: -- **Outage Boost Poll button (`button._outage_boost_poll`)**: Created for each generator; pressing it immediately refreshes data and enables boost polling for `30` minutes. +- **Outage Boost Poll button (`boost_polling`, default entity ID `button._outage_boost_poll`)**: Created for each generator; pressing it immediately refreshes data and enables boost polling for `30` minutes. - **`generac.boost_polling` action (service)**: Switches loaded entries into boost polling and triggers an immediate refresh. Accepts optional `duration_minutes` (`1`–`120`, default `30`) and optional `entry_id` (targets all loaded Generac entries if omitted). ### Telemetry, Long-Term Statistics & Diagnostics @@ -97,11 +103,11 @@ You can also trigger fast polling manually (for example, from an automation trig Each generator automatically tracks exercise activity and maintenance runtime baselines using Home Assistant storage (persisting cleanly across restarts without reloading the integration): - **Maintenance Service Timer**: - - `sensor._hours_until_service` shows estimated runtime hours remaining until the configured service interval (default `100` hours, configurable via **Options** -> `service_interval_hours`; set to `0` to disable). + - `Hours Until Service` (`hours_until_service`, default entity ID `sensor._hours_until_service`) shows estimated runtime hours remaining until the configured service interval (default `100` hours, configurable via **Options** -> `service_interval_hours`; set to `0` to disable). - On first setup, the baseline initializes to the generator's current `run_time` to avoid false day-1 alarms. - - After completing maintenance (oil change, filter, etc.), press **Reset Maintenance Timer** (`button._reset_maintenance_timer`) on the device page to reset the baseline to the current run hours and clear any timer-based Repairs issue immediately. + - After completing maintenance (oil change, filter, etc.), press **Reset Maintenance Timer** (`reset_service_timer`, default entity ID `button._reset_maintenance_timer`) on the device page to reset the baseline to the current run hours and clear any timer-based Repairs issue immediately. - **Exercise Readiness Tracking**: - - `binary_sensor._missed_exercise` turns `on` if no `Running`/`Exercising` status or run-hour increase is observed within `exercise_interval_days` (default `16` days to cover weekly and biweekly schedules; set to `0` to disable). + - `Missed Exercise` (`missed_exercise`, default entity ID `binary_sensor._missed_exercise`) turns `on` if no `Running`/`Exercising` status or run-hour increase is observed within `exercise_interval_days` (default `16` days to cover weekly and biweekly schedules; set to `0` to disable). - **Proactive Home Assistant Repairs Alerts**: - `low_battery_voltage`: raised when generator starting battery voltage drops below `low_battery_threshold` (default `12.2` V). - `missed_exercise`: raised when the generator exceeds `exercise_interval_days` without observed activity. @@ -131,7 +137,7 @@ Generac's sign-in sessions expire 90 days after you log in, no matter how often > > ## Fair Warning > -> Status Quo in summer 2026: This is an unofficial Generac integration, which requires using undocumented APIs in order to access the data of your Generac devices using your username and password. This is because Generac has changed (once again) the authentication workflow to actively block third-party access. They also originally stated that Home Assistant users were overloading their API. We have since adjusted accordingly to adapt to the new authenatication method and reduced our default polling interval from every 30 seconds to every 120 seconds, to be a "good" user of the API and cut the volume of traffic to their servers by 75%. This polling interval can also be tuned to your needs in the options panel of the HA integration once you have set it up, as seen [here](./setup_instructions/options.png). +> Status Quo in summer 2026: This is an unofficial Generac integration, which requires using undocumented APIs in order to access the data of your Generac devices using your username and password. This is because Generac has changed (once again) the authentication workflow to actively block third-party access. They also originally stated that Home Assistant users were overloading their API. We have since adapted to the new authentication method and switched to adaptive polling—defaulting to every 900 seconds (15 minutes) while idle and 120 seconds (2 minutes) while a generator is active—to be a "good" user of the API and minimize traffic to their servers. Both polling intervals can be tuned to your needs in the options panel of the HA integration once you have set it up, as seen [here](./setup_instructions/options.png). > > This approach implies that when Generac is going to change something in their non-public/undocumented API, it's quite likely that the integration will break instantly. > diff --git a/_test_local_access.py b/_test_local_access.py index c9f9466..d13e6b5 100644 --- a/_test_local_access.py +++ b/_test_local_access.py @@ -1,48 +1,73 @@ -# This script is a standalone test for the Generac API client. -# It logs in to the Generac API using credentials from environment variables -# and prints the device data in JSON format using a custom JSON encoder. -# Make sure to set the environment variables GENERAC_USER and GENERAC_PASS before running this script -# to avoid hardcoding sensitive information in the script. -# This script is intended to be run outside of Home Assistant, for testing purposes. -# It uses the aiohttp library for asynchronous HTTP requests and custom JSON encoding for dataclasses. -# Ensure you have aiohttp installed in your environment. -# If you're using Home Assistant, aiohttp is already included. -# You can install it using pip: pip install aiohttp +"""Standalone CLI helper to test GeneracAuth + GeneracApiClient outside HA. + +Set GENERAC_USER and GENERAC_PASS in your environment before running: + + GENERAC_USER="you@example.com" GENERAC_PASS="..." python _test_local_access.py +""" import asyncio import dataclasses import json import logging import os +import sys import aiohttp # type: ignore from custom_components.generac.api import GeneracApiClient +from custom_components.generac.auth import GeneracAuth +from custom_components.generac.auth import InvalidMfaCodeError +from custom_components.generac.auth import MfaRequiredError logging.basicConfig(level=logging.DEBUG) -# Your custom JSON encoder class EnhancedJSONEncoder(json.JSONEncoder): + """JSON encoder that serializes dataclasses.""" + def default(self, o): if dataclasses.is_dataclass(o): return dataclasses.asdict(o) return super().default(o) -# Async main logic -async def main(): - jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False) - async with aiohttp.ClientSession(cookie_jar=jar) as session: - api = GeneracApiClient( - session, - os.environ.get("GENERAC_USER", ""), - os.environ.get("GENERAC_PASS", ""), - os.environ.get("GENERAC_SESSION_COOKIE", ""), +async def _authenticate( + session: aiohttp.ClientSession, email: str, password: str +) -> GeneracAuth: + """Authenticate via Auth0/DPoP, prompting on stdin if code-based MFA is required.""" + try: + return await GeneracAuth.login(session, email, password) + except MfaRequiredError as exc: + flow = exc.flow + try: + while True: + code = input(f"Enter MFA code ({flow.mfa_type}): ").strip() + try: + return await flow.submit_mfa_code(code) + except InvalidMfaCodeError as err: + print(f"Invalid MFA code: {err}", file=sys.stderr) + except MfaRequiredError as next_exc: + flow = next_exc.flow + except BaseException: + await flow.aclose() + raise + + +async def main() -> None: + """Sign in to Mobile Link and print fetched device payloads as JSON.""" + email = os.environ.get("GENERAC_USER", "").strip() + password = os.environ.get("GENERAC_PASS", "") + if not email or not password: + print( + "Please set GENERAC_USER and GENERAC_PASS environment variables.", + file=sys.stderr, ) - await api.login() + sys.exit(1) + + async with aiohttp.ClientSession() as session: + auth = await _authenticate(session, email, password) + api = GeneracApiClient(session, auth) device_data = await api.get_device_data() - print(json.dumps(device_data, cls=EnhancedJSONEncoder)) + print(json.dumps(device_data, cls=EnhancedJSONEncoder, indent=2)) -# Run it using asyncio.run (preferred method in Python 3.7+) if __name__ == "__main__": asyncio.run(main()) diff --git a/custom_components/generac/const.py b/custom_components/generac/const.py index de198c6..13df7f9 100644 --- a/custom_components/generac/const.py +++ b/custom_components/generac/const.py @@ -3,7 +3,7 @@ NAME = "generac" DOMAIN = "generac" DOMAIN_DATA = f"{DOMAIN}_data" -VERSION = "0.0.0" +VERSION = "0.6.1" ATTRIBUTION = ( "Data provided by https://app.mobilelinkgen.com/api. " diff --git a/custom_components/generac/image.py b/custom_components/generac/image.py index a73e515..5fc3f46 100644 --- a/custom_components/generac/image.py +++ b/custom_components/generac/image.py @@ -16,7 +16,7 @@ async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ): - """Setup binary_sensor platform.""" + """Set up image platform.""" coordinator: GeneracDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] data = coordinator.data if isinstance(data, dict): diff --git a/custom_components/generac/manifest.json b/custom_components/generac/manifest.json index 3d6ef49..c185275 100644 --- a/custom_components/generac/manifest.json +++ b/custom_components/generac/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/binarydev/ha-generac/issues", "requirements": ["dacite==1.9.2"], - "version": "0.6" + "version": "0.6.1" } diff --git a/custom_components/generac/sensor.py b/custom_components/generac/sensor.py index b0acb4d..f1ccacd 100644 --- a/custom_components/generac/sensor.py +++ b/custom_components/generac/sensor.py @@ -31,7 +31,7 @@ async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ): - """Setup binary_sensor platform.""" + """Set up sensor platform.""" coordinator: GeneracDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] data = coordinator.data if isinstance(data, dict): @@ -585,7 +585,7 @@ class FuelLevelSensor(GeneracEntity, SensorEntity): entity_key = "fuel_level" _attr_state_class = SensorStateClass.MEASUREMENT - device_class = SensorDeviceClass.BATTERY + _attr_icon = "mdi:propane-tank" native_unit_of_measurement = PERCENTAGE @property diff --git a/custom_components/generac/translations/en.json b/custom_components/generac/translations/en.json index e17e9ca..1c3ea77 100644 --- a/custom_components/generac/translations/en.json +++ b/custom_components/generac/translations/en.json @@ -84,7 +84,6 @@ "scan_interval": "Cloud polling interval (seconds)", "sensor": "Non-binary sensors enabled", "service_interval_hours": "Maintenance service interval (hours, 0 to disable)", - "switch": "Switch enabled", "weather": "Weather sensor enabled" }, "data_description": { diff --git a/custom_components/generac/translations/fr.json b/custom_components/generac/translations/fr.json index aee4e02..c6f85a9 100644 --- a/custom_components/generac/translations/fr.json +++ b/custom_components/generac/translations/fr.json @@ -6,7 +6,11 @@ "description": "Connectez-vous avec votre compte Mobile Link.", "data": { "username": "E-mail", - "password": "Mot de passe" + "password": "Mot de passe", + "remember_password": "Mémoriser le mot de passe" + }, + "data_description": { + "remember_password": "Les sessions Generac expirent environ tous les 90 jours. Si cette option est activée, le mot de passe est enregistré dans Home Assistant afin que l'intégration puisse se reconnecter automatiquement. Non utilisé pour les comptes nécessitant un code de vérification." } }, "reconfigure": { @@ -16,14 +20,24 @@ "username": "E-mail", "password": "Mot de passe", "scan_interval": "Intervalle d'interrogation du cloud (secondes)", - "active_scan_interval": "Intervalle d'interrogation actif (secondes)" + "active_scan_interval": "Intervalle d'interrogation actif (secondes)", + "remember_password": "Mémoriser le mot de passe" + }, + "data_description": { + "scan_interval": "Intervalle d'interrogation du cloud au repos lorsque tous les appareils sont prêts (minimum 10 secondes).", + "active_scan_interval": "Intervalle d'interrogation rapide utilisé lorsqu'un générateur fonctionne, effectue un exercice, affiche un avertissement, se connecte ou est en mode boost (minimum 10 secondes).", + "remember_password": "Les sessions Generac expirent environ tous les 90 jours. Si cette option est activée, le mot de passe est enregistré dans Home Assistant afin que l'intégration puisse se reconnecter automatiquement. Non utilisé pour les comptes nécessitant un code de vérification." } }, "reauth_confirm": { "title": "Réauthentifier Generac MobileLink", "description": "La session pour {username} a expiré. Entrez votre mot de passe pour la rafraîchir.", "data": { - "password": "Mot de passe" + "password": "Mot de passe", + "remember_password": "Mémoriser le mot de passe" + }, + "data_description": { + "remember_password": "Les sessions Generac expirent environ tous les 90 jours. Si cette option est activée, le mot de passe est enregistré dans Home Assistant afin que l'intégration puisse se reconnecter automatiquement. Non utilisé pour les comptes nécessitant un code de vérification." } }, "mfa": { @@ -35,7 +49,7 @@ } }, "error": { - "auth": "E-mail ou mot de passe invalide.", + "auth": "E-mail ou mot de passe invalide. Si vous n'avez pas réinitialisé votre mot de passe depuis la mise à jour de sécurité Generac d'avril 2026, connectez-vous d'abord sur app.mobilelinkgen.com pour le réinitialiser et accepter les conditions mises à jour.", "mfa_invalid": "Ce code est incorrect ou a expiré. Saisissez le code le plus récent, ou annulez et recommencez pour en obtenir un nouveau.", "mfa_unsupported": "Votre compte utilise une méthode à deux facteurs que cette intégration ne peut pas effectuer automatiquement (comme une notification push ou une clé de sécurité). Approuvez la connexion dans l'application MobileLink, ou passez votre compte Generac/ecobee aux codes par SMS, e-mail ou application d'authentification, puis réessayez.", "auth0_unreachable": "Impossible d'atteindre auth.ecobee.com. Vérifiez le réseau sortant/DNS de l'hôte HA.", @@ -65,15 +79,56 @@ "button": "Boutons activés", "exercise_interval_days": "Intervalle d’alerte d’exercice manqué (jours, 0 pour désactiver)", "fuel_burn_rate": "Consommation de carburant estimée (gal/h)", - "image": "Image activé", + "image": "Image activée", "low_battery_threshold": "Seuil d’alerte de tension batterie faible (V)", "scan_interval": "Intervalle d’interrogation en secondes", "sensor": "Capteur activé", "service_interval_hours": "Intervalle d’entretien (heures, 0 pour désactiver)", - "switch": "Interrupteur activé", "weather": "Capteur météo activé" + }, + "data_description": { + "scan_interval": "Intervalle d'interrogation du cloud au repos lorsque tous les appareils sont prêts (minimum 10 secondes).", + "active_scan_interval": "Intervalle d'interrogation rapide utilisé lorsqu'un générateur fonctionne, effectue un exercice, affiche un avertissement, se connecte ou est en mode boost (minimum 10 secondes)." + } + } + } + }, + "services": { + "boost_polling": { + "name": "Accélérer l'interrogation", + "description": "Passe temporairement l'interrogation du cloud Generac à l'intervalle actif et actualise immédiatement.", + "fields": { + "duration_minutes": { + "name": "Durée", + "description": "Durée pendant laquelle maintenir l'interrogation rapide, en minutes (1 à 120)." + }, + "entry_id": { + "name": "Entrée de configuration", + "description": "Entrée de configuration Generac facultative à accélérer. Si omise, toutes les entrées Generac chargées sont accélérées." } } } + }, + "issues": { + "refresh_token_expiring": { + "title": "La connexion Generac pour {username} expire bientôt", + "description": "Les sessions Generac expirent 90 jours après la connexion. La session pour {username} expire autour du {expires}, après quoi vos appareils Generac cesseront de se mettre à jour.\n\nPour la renouveler, allez dans Paramètres → Appareils et services → Generac MobileLink, ouvrez le menu ⋮, choisissez **Reconfigurer** et reconnectez-vous. Cochez **Mémoriser le mot de passe** pour que l'intégration renouvelle désormais la session automatiquement." + }, + "low_battery_voltage": { + "title": "Tension de batterie faible sur {device_name}", + "description": "Le générateur {device_name} a signalé une tension de batterie de {voltage} V, inférieure au seuil configuré de {threshold} V. Inspectez la batterie, le chargeur et les bornes pour garantir un démarrage fiable en cas de panne." + }, + "missed_exercise": { + "title": "Le générateur {device_name} a manqué son exercice programmé", + "description": "Le générateur {device_name} n'a enregistré aucun cycle de fonctionnement ou d'exercice depuis {days_since} jours (intervalle d'alerte : {interval_days} jours). Vérifiez que le générateur est en mode Auto et contrôlez son calendrier d'exercice ainsi que la connexion Mobile Link." + }, + "maintenance_due": { + "title": "Entretien requis pour {device_name}", + "description": "Le générateur {device_name} nécessite un entretien programmé ({reason}). Après l'entretien du générateur, appuyez sur **Reset Maintenance Timer** sur la page de l'appareil pour réinitialiser le compteur." + }, + "subscription_dunning": { + "title": "Problème de facturation de l'abonnement Mobile Link pour {device_name}", + "description": "Generac Mobile Link signale un abonnement en retard de paiement ou en relance pour {device_name}. Mettez à jour votre moyen de paiement sur le portail Mobile Link pour éviter toute interruption de la surveillance à distance." + } } } diff --git a/custom_components/generac/translations/nb.json b/custom_components/generac/translations/nb.json index 11abf51..751e1a7 100644 --- a/custom_components/generac/translations/nb.json +++ b/custom_components/generac/translations/nb.json @@ -6,7 +6,11 @@ "description": "Logg på med din Mobile Link-konto.", "data": { "username": "E-post", - "password": "Passord" + "password": "Passord", + "remember_password": "Husk passord" + }, + "data_description": { + "remember_password": "Generac-økter utløper omtrent hver 90. dag. Hvis dette er aktivert, lagres passordet i Home Assistant slik at integrasjonen kan logge på igjen automatisk. Brukes ikke for kontoer som krever bekreftelseskode." } }, "reconfigure": { @@ -16,14 +20,24 @@ "username": "E-post", "password": "Passord", "scan_interval": "Intervall for skyavstemning (sekunder)", - "active_scan_interval": "Aktivt avstemningsintervall (sekunder)" + "active_scan_interval": "Aktivt avstemningsintervall (sekunder)", + "remember_password": "Husk passord" + }, + "data_description": { + "scan_interval": "Avstemningsintervall i hvilemodus når alle enheter er klare (minimum 10 sekunder).", + "active_scan_interval": "Raskt avstemningsintervall som brukes mens en generator kjører, testkjører, har advarsel, kobler til eller er i boost-modus (minimum 10 sekunder).", + "remember_password": "Generac-økter utløper omtrent hver 90. dag. Hvis dette er aktivert, lagres passordet i Home Assistant slik at integrasjonen kan logge på igjen automatisk. Brukes ikke for kontoer som krever bekreftelseskode." } }, "reauth_confirm": { "title": "Reautentiser Generac MobileLink", "description": "Økten for {username} har utløpt. Skriv inn passordet ditt for å oppdatere den.", "data": { - "password": "Passord" + "password": "Passord", + "remember_password": "Husk passord" + }, + "data_description": { + "remember_password": "Generac-økter utløper omtrent hver 90. dag. Hvis dette er aktivert, lagres passordet i Home Assistant slik at integrasjonen kan logge på igjen automatisk. Brukes ikke for kontoer som krever bekreftelseskode." } }, "mfa": { @@ -35,7 +49,7 @@ } }, "error": { - "auth": "Ugyldig e-post eller passord.", + "auth": "Ugyldig e-post eller passord. Hvis du ikke har tilbakestilt passordet ditt siden Generacs sikkerhetsoppdatering i april 2026, logg på app.mobilelinkgen.com først for å tilbakestille passordet og godta eventuelle oppdaterte vilkår.", "mfa_invalid": "Koden var feil eller har utløpt. Skriv inn den nyeste koden, eller avbryt og start på nytt for å få en ny.", "mfa_unsupported": "Kontoen din bruker en tofaktor-metode som denne integrasjonen ikke kan fullføre automatisk (for eksempel et push-varsel eller en sikkerhetsnøkkel). Godkjenn påloggingen i MobileLink-appen, eller bytt Generac/ecobee-kontoen din til SMS, e-post eller koder fra autentiseringsapp, og prøv igjen.", "auth0_unreachable": "Kunne ikke nå auth.ecobee.com. Sjekk HA-vertens utgående nettverk/DNS.", @@ -70,10 +84,51 @@ "scan_interval": "Avstemningsintervall i sekunder", "sensor": "Sensor aktivert", "service_interval_hours": "Serviceintervall for vedlikehold (timer, 0 for å deaktivere)", - "switch": "Bryter aktivert", "weather": "Værsensor aktivert" + }, + "data_description": { + "scan_interval": "Avstemningsintervall i hvilemodus når alle enheter er klare (minimum 10 sekunder).", + "active_scan_interval": "Raskt avstemningsintervall som brukes mens en generator kjører, testkjører, har advarsel, kobler til eller er i boost-modus (minimum 10 sekunder)." + } + } + } + }, + "services": { + "boost_polling": { + "name": "Boost avstemning", + "description": "Bytter midlertidig Generac-skyavstemning til det aktive intervallet og oppdaterer umiddelbart.", + "fields": { + "duration_minutes": { + "name": "Varighet", + "description": "Hvor lenge rask boost-avstemning skal opprettholdes, i minutter (1 til 120)." + }, + "entry_id": { + "name": "Konfigurasjonsoppføring", + "description": "Valgfri Generac-konfigurasjonsoppføring som skal boostes. Hvis utelatt, boostes alle innlastede Generac-oppføringer." } } } + }, + "issues": { + "refresh_token_expiring": { + "title": "Generac-påloggingen for {username} utløper snart", + "description": "Generac-økter utløper 90 dager etter pålogging. Økten for {username} utløper rundt {expires}, og deretter slutter Generac-enhetene dine å oppdatere.\n\nFor å fornye den, gå til Innstillinger → Enheter og tjenester → Generac MobileLink, åpne ⋮-menyen, velg **Rekonfigurer** og logg på igjen. Kryss av for **Husk passord** for at integrasjonen skal fornye økten automatisk fremover." + }, + "low_battery_voltage": { + "title": "Lav batterispenning på {device_name}", + "description": "Generatoren {device_name} rapporterte en batterispenning på {voltage} V, under den konfigurerte terskelen på {threshold} V. Kontroller batteriet, laderen og polene for å sikre pålitelig start ved strømbrudd." + }, + "missed_exercise": { + "title": "Generator {device_name} gikk glipp av planlagt testkjøring", + "description": "Generatoren {device_name} har ikke registrert noen kjøre- eller testkjøringssyklus på {days_since} dager (varselintervall: {interval_days} dager). Kontroller at generatoren står i Auto-modus og sjekk testkjøringsplanen og Mobile Link-tilkoblingen." + }, + "maintenance_due": { + "title": "Vedlikehold forfaller for {device_name}", + "description": "Generatoren {device_name} krever planlagt vedlikehold ({reason}). Etter utført service på generatoren, trykk på **Reset Maintenance Timer** på enhetssiden for å tilbakestille nedtellingen." + }, + "subscription_dunning": { + "title": "Faktureringsproblem for Mobile Link-abonnementet til {device_name}", + "description": "Generac Mobile Link rapporterer et forfalt abonnement eller purrestatus for {device_name}. Oppdater betalingsmåten din i Mobile Link-portalen for å unngå avbrudd i fjernovervåkingen." + } } } diff --git a/custom_components/generac/translations/pt.json b/custom_components/generac/translations/pt.json index 36f676e..ad163fd 100644 --- a/custom_components/generac/translations/pt.json +++ b/custom_components/generac/translations/pt.json @@ -6,7 +6,11 @@ "description": "Inicie sessão com a sua conta Mobile Link.", "data": { "username": "Email", - "password": "Palavra-passe" + "password": "Palavra-passe", + "remember_password": "Memorizar palavra-passe" + }, + "data_description": { + "remember_password": "As sessões Generac expiram aproximadamente a cada 90 dias. Se estiver ativado, a palavra-passe é guardada no Home Assistant para que a integração possa voltar a iniciar sessão automaticamente. Não é utilizado em contas que requerem um código de verificação." } }, "reconfigure": { @@ -16,14 +20,24 @@ "username": "Email", "password": "Palavra-passe", "scan_interval": "Intervalo de sondagem à cloud (segundos)", - "active_scan_interval": "Intervalo de sondagem ativo (segundos)" + "active_scan_interval": "Intervalo de sondagem ativo (segundos)", + "remember_password": "Memorizar palavra-passe" + }, + "data_description": { + "scan_interval": "Intervalo de sondagem à cloud em repouso quando todos os dispositivos estão prontos (mínimo de 10 segundos).", + "active_scan_interval": "Intervalo de sondagem rápido utilizado enquanto um gerador está em funcionamento, em exercício, com aviso, a ligar ou em modo boost (mínimo de 10 segundos).", + "remember_password": "As sessões Generac expiram aproximadamente a cada 90 dias. Se estiver ativado, a palavra-passe é guardada no Home Assistant para que a integração possa voltar a iniciar sessão automaticamente. Não é utilizado em contas que requerem um código de verificação." } }, "reauth_confirm": { "title": "Reautenticar Generac MobileLink", "description": "A sessão de {username} expirou. Introduza a sua palavra-passe para a atualizar.", "data": { - "password": "Palavra-passe" + "password": "Palavra-passe", + "remember_password": "Memorizar palavra-passe" + }, + "data_description": { + "remember_password": "As sessões Generac expiram aproximadamente a cada 90 dias. Se estiver ativado, a palavra-passe é guardada no Home Assistant para que a integração possa voltar a iniciar sessão automaticamente. Não é utilizado em contas que requerem um código de verificação." } }, "mfa": { @@ -35,7 +49,7 @@ } }, "error": { - "auth": "Email ou palavra-passe incorretos.", + "auth": "Email ou palavra-passe incorretos. Se não redefiniu a sua palavra-passe desde a atualização de segurança da Generac de abril de 2026, inicie sessão primeiro em app.mobilelinkgen.com para redefinir a palavra-passe e aceitar os termos atualizados.", "mfa_invalid": "Esse código estava incorreto ou expirou. Introduza o código mais recente ou cancele e comece de novo para obter um novo.", "mfa_unsupported": "A sua conta utiliza um método de dois fatores que esta integração não consegue concluir automaticamente (como uma notificação push ou chave de segurança). Aprove o início de sessão na aplicação MobileLink ou mude a sua conta Generac/ecobee para SMS, email ou códigos de aplicação de autenticação e tente novamente.", "auth0_unreachable": "Não foi possível contactar auth.ecobee.com. Verifique a rede de saída/DNS do anfitrião HA.", @@ -70,10 +84,51 @@ "scan_interval": "Intervalo de sondagem (segundos)", "sensor": "Sensores não binários ativados", "service_interval_hours": "Intervalo de manutenção (horas, 0 para desativar)", - "switch": "Interruptor ativado", "weather": "Sensor meteorológico ativado" + }, + "data_description": { + "scan_interval": "Intervalo de sondagem à cloud em repouso quando todos os dispositivos estão prontos (mínimo de 10 segundos).", + "active_scan_interval": "Intervalo de sondagem rápido utilizado enquanto um gerador está em funcionamento, em exercício, com aviso, a ligar ou em modo boost (mínimo de 10 segundos)." + } + } + } + }, + "services": { + "boost_polling": { + "name": "Acelerar sondagem", + "description": "Muda temporariamente a sondagem à cloud da Generac para o intervalo ativo e atualiza imediatamente.", + "fields": { + "duration_minutes": { + "name": "Duração", + "description": "Durante quanto tempo manter a sondagem rápida, em minutos (1 a 120)." + }, + "entry_id": { + "name": "Entrada de configuração", + "description": "Entrada de configuração Generac opcional a acelerar. Se omitida, todas as entradas Generac carregadas são aceleradas." } } } + }, + "issues": { + "refresh_token_expiring": { + "title": "O início de sessão Generac para {username} expira em breve", + "description": "As sessões Generac expiram 90 dias após o início de sessão. A sessão de {username} expira por volta de {expires}, após o que os seus dispositivos Generac deixarão de atualizar.\n\nPara a renovar, vá a Definições → Dispositivos e serviços → Generac MobileLink, abra o menu ⋮, escolha **Reconfigurar** e inicie sessão novamente. Marque **Memorizar palavra-passe** para que a integração renove a sessão automaticamente a partir de agora." + }, + "low_battery_voltage": { + "title": "Tensão baixa da bateria em {device_name}", + "description": "O gerador {device_name} comunicou uma tensão da bateria de {voltage} V, abaixo do limite configurado de {threshold} V. Inspecione a bateria, o carregador e os terminais para garantir um arranque fiável durante uma falha de energia." + }, + "missed_exercise": { + "title": "O gerador {device_name} falhou o exercício agendado", + "description": "O gerador {device_name} não registou um ciclo de funcionamento ou exercício há {days_since} dias (intervalo de alerta: {interval_days} dias). Verifique se o gerador está em modo Auto e inspecione o calendário de exercícios e a ligação Mobile Link." + }, + "maintenance_due": { + "title": "Manutenção necessária para {device_name}", + "description": "O gerador {device_name} requer manutenção agendada ({reason}). Após efetuar a manutenção do gerador, prima **Reset Maintenance Timer** na página do dispositivo para repor a contagem decrescente." + }, + "subscription_dunning": { + "title": "Problema de faturação da subscrição Mobile Link para {device_name}", + "description": "A Generac Mobile Link indica uma subscrição em atraso ou em cobrança para {device_name}. Atualize o seu método de pagamento no portal Mobile Link para evitar a interrupção da monitorização remota." + } } } diff --git a/custom_components/generac/weather.py b/custom_components/generac/weather.py index d9772b2..4b3ae30 100644 --- a/custom_components/generac/weather.py +++ b/custom_components/generac/weather.py @@ -16,7 +16,7 @@ async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ): - """Setup binary_sensor platform.""" + """Set up weather platform.""" coordinator: GeneracDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] data = coordinator.data if isinstance(data, dict): diff --git a/info.md b/info.md index a6e7f2c..0922dcc 100644 --- a/info.md +++ b/info.md @@ -1,13 +1,25 @@ -# generac +# Generac MobileLink/MyGenerac [![hacs][hacsbadge]][hacs] -**This component will set up the following platforms.** +**Custom Generac integration component with support for generators and propane tank monitors. It will set up the following platforms.** -| Platform | Entities created for each generator | -| --------------- | ------------------------------------------------------------------------------------------------------------- | -| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning` | -| `sensor` | `status`, `run_time`, `protection_time`, `activation_date`, `last_seen`, `connection_time`, `battery_voltage` | +| Platform | Entities created for each generator (by `entity_key`) | +| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | +| `button` | `reset_service_timer`, `boost_polling` | +| `sensor` | `status`, `run_time`, `protection_time`, `activation_date`, `last_seen`, `connection_time`, `battery_voltage`, `device_type`, `dealer_email`, `dealer_name`, `dealer_phone`, `address`, `status_text`, `status_label`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, plus conditional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | +| `weather` | conditional `weather` | +| `image` | conditional `hero_image` | + +| Platform | Entities created for each propane tank monitor (by `entity_key`) | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, plus conditional `subscription_dunning` | +| `sensor` | `status`, `capacity`, `fuel_level`, `remaining_fuel`, `estimated_runtime`, `fuel_type`, `orientation`, `last_reading`, `battery_level`, `address`, `device_type`, plus conditional `signal_strength`, `device_battery_level`, `outdoor_temperature` | +| `weather` | conditional `weather` | +| `image` | conditional `hero_image` | + +Includes adaptive cloud polling (`900` s idle / `120` s active) with manual outage boost, long-term statistics, propane fuel autonomy estimates, maintenance/exercise readiness tracking with Repairs alerts, and bundled automation blueprints. ![example][exampleimg] @@ -15,15 +27,17 @@ ## Installation -1. Click install. -2. In the HA UI go to "Configuration" -> "Integrations" click "+" and search for "generac". -3. Enter the credentials you use to login for https://app.mobilelinkgen.com/ and submit the form -4. The integration should initialize and begin pulling your device information within seconds +1. Click download/install in HACS and restart Home Assistant. +2. Go to **Settings → Devices & services**, click **Add Integration**, and search for `generac`. +3. Sign in with your **MyGenerac / MobileLink** email and password (code-based SMS, email, and authenticator-app 2FA are supported). +4. The integration will initialize and begin polling your devices within seconds. {% endif %} ## Configuration is done in the UI +Open **Settings → Devices & services → Generac MobileLink → Configure** to adjust enabled platforms, polling intervals, readiness thresholds, and propane fuel burn rate. + ## Contributions are welcome! diff --git a/tests/test_init.py b/tests/test_init.py index 7881767..289c284 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1,4 +1,6 @@ """Test generac setup process.""" +import json +import re from pathlib import Path from unittest.mock import AsyncMock from unittest.mock import patch @@ -11,6 +13,7 @@ from custom_components.generac.auth import DPoPKey from custom_components.generac.auth import GeneracAuth from custom_components.generac.const import CONF_DPOP_PEM +from custom_components.generac.const import CONF_OPTIONS from custom_components.generac.const import CONF_PASSWORD from custom_components.generac.const import CONF_REFRESH_TOKEN from custom_components.generac.const import CONF_TOKEN_ISSUED_AT @@ -18,6 +21,8 @@ from custom_components.generac.const import DEFAULT_BOOST_DURATION_MINUTES from custom_components.generac.const import DOMAIN from custom_components.generac.const import SERVICE_BOOST_POLLING +from custom_components.generac.const import STARTUP_MESSAGE +from custom_components.generac.const import VERSION from custom_components.generac.coordinator import GeneracDataUpdateCoordinator from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed @@ -43,14 +48,16 @@ async def test_setup_unload_and_reload_entry(hass: HomeAssistant, bypass_get_dat ) config_entry.add_to_hass(hass) - await hass.config_entries.async_setup(config_entry.entry_id) - assert await async_setup_entry(hass, config_entry) + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() assert DOMAIN in hass.data and config_entry.entry_id in hass.data[DOMAIN] assert await async_reload_entry(hass, config_entry) is None + await hass.async_block_till_done() assert DOMAIN in hass.data and config_entry.entry_id in hass.data[DOMAIN] - assert await async_unload_entry(hass, config_entry) + assert await hass.config_entries.async_unload(config_entry.entry_id) + await hass.async_block_till_done() assert config_entry.entry_id not in hass.data[DOMAIN] @@ -106,8 +113,8 @@ async def test_setup_entry_existing_domain(hass: HomeAssistant, bypass_get_data) ) config_entry.add_to_hass(hass) - await hass.config_entries.async_setup(config_entry.entry_id) - assert await async_setup_entry(hass, config_entry) + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() assert DOMAIN in hass.data and config_entry.entry_id in hass.data[DOMAIN] assert "existing_entry" in hass.data[DOMAIN] @@ -119,8 +126,8 @@ async def test_unload_entry_failed(hass: HomeAssistant, bypass_get_data): ) config_entry.add_to_hass(hass) - await hass.config_entries.async_setup(config_entry.entry_id) - assert await async_setup_entry(hass, config_entry) + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() with patch( "homeassistant.config_entries.ConfigEntries.async_unload_platforms", @@ -561,3 +568,59 @@ async def test_platform_toggles_setup_reload_and_unload(hass: HomeAssistant): assert hass.data[DOMAIN][all_disabled_entry.entry_id].loaded_platforms == [] assert await hass.config_entries.async_unload(all_disabled_entry.entry_id) assert all_disabled_entry.entry_id not in hass.data[DOMAIN] + + +def test_manifest_and_const_version_match(): + """manifest.json uses 3-part SemVer matching const.VERSION and STARTUP_MESSAGE.""" + manifest_path = ( + Path(__file__).resolve().parents[1] + / "custom_components" + / "generac" + / "manifest.json" + ) + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + version = manifest["version"] + assert re.fullmatch(r"\d+\.\d+\.\d+", version), version + assert VERSION == version + assert f"Version: {version}" in STARTUP_MESSAGE + + +def test_translations_parity_and_options_coverage(): + """All locales match en.json keys/placeholders and mirror CONF_OPTIONS.""" + from custom_components.generac.issues import _DEVICE_ISSUE_KEYS + + def _flatten(data: dict, prefix: str = "") -> dict[str, str]: + flat: dict[str, str] = {} + for key, value in data.items(): + path = f"{prefix}.{key}" if prefix else key + if isinstance(value, dict): + flat.update(_flatten(value, path)) + else: + flat[path] = value + return flat + + def _placeholders(text: str) -> set[str]: + return set(re.findall(r"\{([a-zA-Z0-9_]+)\}", text)) + + translations_dir = ( + Path(__file__).resolve().parents[1] + / "custom_components" + / "generac" + / "translations" + ) + en_data = json.loads((translations_dir / "en.json").read_text(encoding="utf-8")) + en_flat = _flatten(en_data) + expected_issues = {"refresh_token_expiring", *_DEVICE_ISSUE_KEYS} + + for path in sorted(translations_dir.glob("*.json")): + locale_data = json.loads(path.read_text(encoding="utf-8")) + locale_flat = _flatten(locale_data) + assert set(locale_flat) == set(en_flat), path.name + assert set(locale_data["options"]["step"]["user"]["data"]) == set( + CONF_OPTIONS + ), path.name + assert expected_issues.issubset(locale_data["issues"]), path.name + for key, en_text in en_flat.items(): + assert _placeholders(locale_flat[key]) == _placeholders( + en_text + ), f"{path.name}:{key}" diff --git a/tests/test_sensor.py b/tests/test_sensor.py index fb6cc70..bf75115 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -266,6 +266,9 @@ async def test_propane_monitor_sensors(hass): sensor = FuelLevelSensor(coordinator, entry, "12345", item) assert sensor.native_value == 50 + assert sensor.device_class is None + assert sensor.icon == "mdi:propane-tank" + assert sensor.native_unit_of_measurement == "%" sensor = FuelTypeSensor(coordinator, entry, "12345", item) assert sensor.native_value == "Propane"