Example #1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Emporia Vue from a config entry."""
    entry_data = entry.data
    email = entry_data[CONF_EMAIL]
    password = entry_data[CONF_PASSWORD]
    _LOGGER.info(entry_data)
    vue = PyEmVue()
    try:
        result = vue.login(username=email, password=password)
        if not result:
            raise Exception("Could not authenticate with Emporia API")
            return False
    except Exception:
        _LOGGER.error("Could not authenticate with Emporia API")
        return False

    # Get device data from Emporia API
    #discovered_devices = vue.get_devices()

    hass.data[DOMAIN][entry.entry_id] = {
        VUE_DATA: vue,
        #VUE_DEVICES_DATA: VueDeviceData(),
        #VUE_DISCOVERED_DEVICES_DATA: discovered_devices,
    }

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Example #2
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Emporia Vue from a config entry."""
    entry_data = entry.data
    email = entry_data[CONF_EMAIL]
    password = entry_data[CONF_PASSWORD]
    #_LOGGER.info(entry_data)
    vue = PyEmVue()
    try:
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(None, vue.login, email, password)
        if not result:
            raise Exception("Could not authenticate with Emporia API")
    except Exception:
        _LOGGER.error("Could not authenticate with Emporia API")
        return False

    hass.data[DOMAIN][entry.entry_id] = {
        VUE_DATA:
        vue,
        ENABLE_1S:
        False if ENABLE_1S not in entry_data else entry_data[ENABLE_1S],
        ENABLE_1M:
        True if ENABLE_1M not in entry_data else entry_data[ENABLE_1M],
        ENABLE_1D:
        True if ENABLE_1D not in entry_data else entry_data[ENABLE_1D],
        ENABLE_1MON:
        True if ENABLE_1MON not in entry_data else entry_data[ENABLE_1MON]
    }

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Example #3
0
def logInAndInit(account):
    if 'vue' not in account:
        account['vue'] = PyEmVue()
        account['vue'].login(username=account['email'], password=account['password'])
        info('Login completed')

        account['INTERVAL_SECS']=config["options"]["initial_interval_secs"]
        populateDevices(account)
class VueHub:
    """Hub for the Emporia Vue Integration."""

    def __init__(self):
        """Initialize."""
        self.vue = PyEmVue()
        pass

    async def authenticate(self, username, password) -> bool:
        """Test if we can authenticate with the host."""
        return self.vue.login(username=username, password=password)
Example #5
0
def get_vue():
    vue = PyEmVue()

    try:
        data = json.load(json_file)
    except:
        return None

    try:
        vue.login(username=data['email'],
                  password=data['password'],
                  token_storage_file=token_file)
    except:
        try:
            vue.login(id_token=data['idToken'],
                      access_token=data['accessToken'],
                      refresh_token=data['refreshToken'],
                      token_storage_file=json_file)
        except:
            return None
    return vue
Example #6
0
pauseEvent = Event()

INTERVAL_SECS = 60
LAG_SECS = 5

if config['influxDb']['reset']:
    info('Resetting database')
    influx.delete_series(measurement='energy_usage')

while running:
    for account in config["accounts"]:
        tmpEndingTime = datetime.datetime.utcnow() - datetime.timedelta(
            seconds=LAG_SECS)

        if 'vue' not in account:
            account['vue'] = PyEmVue()
            account['vue'].login(username=account['email'],
                                 password=account['password'])
            info('Login completed')

            populateDevices(account)

            account['end'] = tmpEndingTime

            start = account['end'] - datetime.timedelta(seconds=INTERVAL_SECS)

            result = influx.query(
                'select last(usage), time from energy_usage where account_name = \'{}\''
                .format(account['name']))
            if len(result) > 0:
                timeStr = next(result.get_points())['time'][:26]
Example #7
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Emporia Vue from a config entry."""
    global device_gids
    global device_information
    device_gids = []
    device_information = {}

    entry_data = entry.data
    email = entry_data[CONF_EMAIL]
    password = entry_data[CONF_PASSWORD]
    # _LOGGER.info(entry_data)
    vue = PyEmVue()
    loop = asyncio.get_event_loop()
    try:
        result = await loop.run_in_executor(None, vue.login, email, password)
        if not result:
            raise Exception("Could not authenticate with Emporia API")
    except Exception:
        _LOGGER.error("Could not authenticate with Emporia API")
        return False

    scales_1hr = []
    try:
        devices = await loop.run_in_executor(None, vue.get_devices)
        total_channels = 0
        for d in devices:
            total_channels += len(d.channels)
        _LOGGER.info(
            "Found {0} Emporia devices with {1} total channels".format(
                len(devices), total_channels
            )
        )
        for device in devices:
            if not device.device_gid in device_gids:
                device_gids.append(device.device_gid)
                await loop.run_in_executor(None, vue.populate_device_properties, device)
                device_information[device.device_gid] = device
            else:
                device_information[device.device_gid].channels += device.channels

        async def async_update_data_1min():
            """Fetch data from API endpoint at a 1 minute interval

            This is the place to pre-process the data to lookup tables
            so entities can quickly look up their data.
            """
            return await update_sensors(vue, [Scale.MINUTE.value])

        async def async_update_data_1hr():
            """Fetch data from API endpoint at a 1 hour interval

            This is the place to pre-process the data to lookup tables
            so entities can quickly look up their data.
            """
            return await update_sensors(vue, scales_1hr)

        if ENABLE_1D not in entry_data or entry_data[ENABLE_1D]:
            scales_1hr.append(Scale.DAY.value)
        if ENABLE_1MON not in entry_data or entry_data[ENABLE_1MON]:
            scales_1hr.append(Scale.MONTH.value)

        coordinator_1min = None
        if ENABLE_1M not in entry_data or entry_data[ENABLE_1M]:
            coordinator_1min = DataUpdateCoordinator(
                hass,
                _LOGGER,
                # Name of the data. For logging purposes.
                name="sensor",
                update_method=async_update_data_1min,
                # Polling interval. Will only be polled if there are subscribers.
                update_interval=timedelta(minutes=1),
            )
            await coordinator_1min.async_config_entry_first_refresh()
            _LOGGER.info(f"1min Update data: {coordinator_1min.data}")
        coordinator_1hr = None
        if scales_1hr:
            coordinator_1hr = DataUpdateCoordinator(
                hass,
                _LOGGER,
                # Name of the data. For logging purposes.
                name="sensor",
                update_method=async_update_data_1hr,
                # Polling interval. Will only be polled if there are subscribers.
                update_interval=timedelta(hours=1),
            )
            await coordinator_1hr.async_config_entry_first_refresh()
            _LOGGER.info(f"1hr Update data: {coordinator_1hr.data}")

    except Exception as err:
        _LOGGER.warn(f"Exception while setting up Emporia Vue. Will retry. {err}")
        raise ConfigEntryNotReady(
            f"Exception while setting up Emporia Vue. Will retry. {err}"
        )

    hass.data[DOMAIN][entry.entry_id] = {
        VUE_DATA: vue,
        "coordinator_1min": coordinator_1min,
        "coordinator_1hr": coordinator_1hr
    }

    try:
        for component in PLATFORMS:
            hass.async_create_task(
                hass.config_entries.async_forward_entry_setup(entry, component)
            )
    except Exception as err:
        _LOGGER.warn(f"Error setting up platforms: {err}")
        raise ConfigEntryNotReady(f"Error setting up platforms: {err}")

    return True
 def __init__(self):
     """Initialize."""
     self.vue = PyEmVue()
     pass