async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Setup the sensor platform."""
    _LOGGER.debug("Initialising renaultze platform")

    g_url = None
    g_key = None
    k_url = None
    k_key = None
    k_account_id = config.get(CONF_K_ACCOUNTID, '')

    cred = CredentialStore()
    cred.clear()

    url = 'https://renault-wrd-prod-1-euw1-myrapp-one.s3-eu-west-1.amazonaws.com/configuration/android/config_%s.json' % config.get(
        CONF_ANDROID_LNG)
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            responsetext = await response.text()
            if responsetext == '':
                responsetext = '{}'
            jsonresponse = json.loads(responsetext)

            g_url = jsonresponse['servers']['gigyaProd']['target']
            g_key = jsonresponse['servers']['gigyaProd']['apikey']
            k_url = jsonresponse['servers']['wiredProd']['target']
            k_key = jsonresponse['servers']['wiredProd']['apikey']

    g = Gigya(api_key=g_key, root_url=g_url)
    if not g.login(config.get(CONF_USERNAME), config.get(CONF_PASSWORD)):
        raise RenaultZEError("Login failed")
    g.account_info()

    k = Kamereon(api_key=k_key, root_url=k_url, gigya=g)
    if k_account_id != '':
        k.set_account_id(k_account_id)

    v = Vehicle(config.get(CONF_VIN), k)

    devices = [RenaultZESensor(v, config.get(CONF_NAME, config.get(CONF_VIN)))]
    async_add_entities(devices)
Beispiel #2
0
def run(args):
    k = Kamereon()
    k.set_account_id(args.account_id)
Beispiel #3
0
class PyzeProxy:
    """Handle account communication with Renault servers via PyZE."""

    def __init__(self, hass):
        """Initialise proxy."""
        LOGGER.debug("Creating PyzeProxy")
        self._hass = hass
        self._gigya = None
        self._kamereon = None
        self._vehicle_links = None
        self._vehicle_proxies = {}
        self._vehicles_lock = asyncio.Lock()
        self.entities = []

    def set_api_keys(self, config_data):
        """Set up gigya."""
        credential_store = BasicCredentialStore()
        credential_store.store(
            "gigya-api-key", config_data.get(CONF_GIGYA_APIKEY), None
        )
        credential_store.store(
            "kamereon-api-key", config_data.get(CONF_KAMEREON_APIKEY), None
        )

        self._gigya = Gigya(
            credentials=credential_store,
        )
        self._kamereon = Kamereon(
            gigya=self._gigya,
            credentials=credential_store,
            country=config_data.get(CONF_LOCALE)[-2:],
        )

    async def attempt_login(self, config_data) -> bool:
        """Attempt login to Renault servers."""
        if self._gigya is None:
            raise RuntimeError("Please ensure Gigya is initialised.")
        try:
            if await self._hass.async_add_executor_job(
                self._gigya.login,
                config_data[CONF_USERNAME],
                config_data[CONF_PASSWORD],
            ):
                return True
        except RuntimeError as ex:
            LOGGER.error("Login to Gigya failed: %s", ex)
        return False

    async def initialise(self, config_data):
        """Set up proxy."""
        if self._kamereon is None:
            raise RuntimeError("Please ensure Kamereon is initialised.")
        self._kamereon.set_account_id(config_data[CONF_KAMEREON_ACCOUNT_ID])
        vehicles = await self._hass.async_add_executor_job(self._kamereon.get_vehicles)
        self._vehicle_links = vehicles["vehicleLinks"]

    async def get_account_ids(self) -> list:
        """Get Kamereon account ids."""
        await self._hass.async_add_executor_job(self._gigya.account_info)

        accounts = []
        for account_details in await self._hass.async_add_executor_job(
            self._kamereon.get_accounts
        ):
            accounts.append(account_details["accountId"])
        return accounts

    def get_vehicle_links(self):
        """Get list of vehicles."""
        return self._vehicle_links

    def get_vehicle_from_vin(self, vin: str):
        """Get vehicle from VIN."""
        return self._vehicle_proxies[vin.upper()]

    async def get_vehicle_proxy(self, vehicle_link: dict):
        """Get a pyze proxy for the vehicle.

        Using lock to ensure vehicle proxies are only created once across all platforms.
        """
        vin: str = vehicle_link["vin"]
        vin = vin.upper()
        async with self._vehicles_lock:
            pyze_vehicle_proxy = self._vehicle_proxies.get(vin)
            if pyze_vehicle_proxy is None:
                pyze_vehicle_proxy = PyzeVehicleProxy(
                    self._hass,
                    vehicle_link,
                    Vehicle(vehicle_link["vin"], self._kamereon),
                )
                self._vehicle_proxies[vin] = pyze_vehicle_proxy
                await pyze_vehicle_proxy.async_initialise
        return self._vehicle_proxies[vin]
Beispiel #4
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Setup the sensor platform."""
    _LOGGER.debug("Initialising renaultze platform")

    g_url = None
    g_key = None
    k_url = None
    k_key = None
    k_account_id = config.get(CONF_K_ACCOUNTID, '')

    cred = CredentialStore()
    cred.clear()

    url = 'https://renault-wrd-prod-1-euw1-myrapp-one.s3-eu-west-1.amazonaws.com/configuration/android/config_{0}.json'.format(
        config.get(CONF_ANDROID_LNG))
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            responsetext = await response.text()
            if responsetext == '':
                responsetext = '{}'
            jsonresponse = json.loads(responsetext)

            g_url = jsonresponse['servers']['gigyaProd']['target']
            g_key = jsonresponse['servers']['gigyaProd']['apikey']
            k_url = jsonresponse['servers']['wiredProd']['target']
            k_key = jsonresponse['servers']['wiredProd']['apikey']

    g = Gigya(api_key=g_key, root_url=g_url)
    if not g.login(config.get(CONF_USERNAME), config.get(CONF_PASSWORD)):
        raise RenaultZEError("Login failed")
    g.account_info()

    k = Kamereon(api_key=k_key, root_url=k_url, gigya=g)
    if k_account_id != '':
        k.set_account_id(k_account_id)

    v = Vehicle(config.get(CONF_VIN), k)

    devices = [RenaultZESensor(v, config.get(CONF_NAME, config.get(CONF_VIN)))]
    async_add_entities(devices)

    platform = entity_platform.current_platform.get()

    platform.async_register_entity_service(
        SERVICE_AC_START,
        {
            vol.Optional(ATTR_WHEN): cv.datetime,
            vol.Optional(ATTR_TEMPERATURE): cv.positive_int,
        },
        "ac_start",
    )
    platform.async_register_entity_service(
        SERVICE_AC_CANCEL,
        {},
        "ac_cancel",
    )
    platform.async_register_entity_service(
        SERVICE_CHARGE_START,
        {},
        "charge_start",
    )
    platform.async_register_entity_service(
        SERVICE_CHARGE_SET_MODE,
        {
            vol.Required(ATTR_CHARGE_MODE): cv.enum(ChargeMode),
        },
        "charge_set_mode",
    )
    platform.async_register_entity_service(
        SERVICE_CHARGE_SET_SCHEDULES,
        {
            vol.Required(ATTR_SCHEDULES): dict,
        },
        "charge_set_schedules",
    )