Ejemplo n.º 1
0
class LinkyData:
    """The class for handling the data retrieval."""
    def __init__(self, username, password, timeout):
        """Initialize the data object."""
        self._username = username
        self._password = password
        self._timeout = timeout
        self.client = {}
        self.data = {}
        self.halfhourly = []
        self.daily = []
        self.monthly = []
        self.yearly = []
        self.compare_month = []
        self.success = False

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def _fetch_data(self):
        """Fetch latest data from Linky."""
        from pylinky.client import PyLinkyError
        from pylinky import LinkyClient
        from datetime import date
        from dateutil.relativedelta import relativedelta
        try:
            self.client = LinkyClient(self._username, self._password, None,
                                      self._timeout)
            self.client.login()
            _LOGGER.info("Connected to Enedis server successfully.")
            self.client.fetch_data()
            self.data = self.client.get_data()
            today = date.today()
            # Get partial CONSUMPTION of the same month last year
            self.compare_month = 0
            for value in self.client.get_data_per_period(
                    "daily", (today.replace(day=1) - relativedelta(months=12)),
                (today - relativedelta(months=12)))['data']:
                self.compare_month += value[
                    'valeur'] if value['valeur'] != -1 else 0

            _LOGGER.info("Same month last year (from 1st to same day): %s",
                         str(self.compare_month))
        except PyLinkyError as exp:
            reason = "(maybe due to night maintenance downtime schedule):"
            _LOGGER.warning("Unable to fetch Linky data %s %s", reason, exp)
            return False
        return True

    def update(self):
        """Return the latest collected data from Linky."""
        self._fetch_data()
        if not self.data:
            return
        _LOGGER.debug("Linky data retrieved: %s", str(self.data))
        self.halfhourly = list(reversed(self.data["hourly"]))
        self.daily = list(reversed(self.data["daily"]))
        self.monthly = list(reversed(self.data["monthly"]))
        self.yearly = list(reversed(self.data["yearly"]))
        self.success = True
Ejemplo n.º 2
0
def getLinkyData(startDate):
    tstamp = int(time.time())
    try:
        client = LinkyClient(args.enedisUsername, args.enedisPassword)
        client.login()
        endDate = startDate + TimeDelta(days=1)
        data = client.get_data_per_period(start=startDate, end=endDate)
        print(data)
        client.close_session()
        formatedData = formatData(startDate, data['data'])
        return (True, formatedData)
    except Exception as e:
        return (False, {
            "time": tstamp,
            "message": "Enedis not available : " + str(e)
        })
Ejemplo n.º 3
0
class LinkyData:
    """The class for handling the data retrieval."""
    def __init__(self, username, password, timeout):
        """Initialize the data object."""
        self._username = username
        self._password = password
        self._timeout = timeout
        self.client = {}
        self.data = {}
        self.halfhourly = []
        self.daily = []
        self.monthly = []
        self.yearly = []
        self.compare_month = []
        self.success = False

    @property
    def username(self):
        """Return the username."""
        return self._username

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def _fetch_data(self):
        """Fetch latest data from Linky."""
        from pylinky.exceptions import PyLinkyAccessException, PyLinkyEnedisException, PyLinkyMaintenanceException, PyLinkyWrongLoginException
        from pylinky import LinkyClient
        from datetime import date
        from dateutil.relativedelta import relativedelta

        try:
            self.client = LinkyClient(self._username, self._password, None,
                                      self._timeout)
            self.client.login()
            self.client.fetch_data()
            _LOGGER.info("Connected to Enedis server successfully.")
            self.data = self.client.get_data()
            today = date.today()
            # Get partial CONSUMPTION of the same month last year
            self.compare_month = sum([
                d[CONSUMPTION] for d in self.client.format_data(
                    self.client.get_data_per_period(
                        "monthly",
                        today.replace(day=1) - relativedelta(months=12),
                        today - relativedelta(months=12),
                    ))
            ])
            _LOGGER.info(
                "Same month last year (from 1st to same day): %s",
                str(self.compare_month),
            )
        except PyLinkyAccessException as accessExp:
            reason = "(verify your login password):"
            _LOGGER.warning("Unable to fetch Linky data %s %s", reason,
                            accessExp)
            return False
        except PyLinkyEnedisException as enedisExp:
            reason = "(unknown exception):"
            _LOGGER.warning("Unable to fetch Linky data %s %s", reason,
                            enedisExp)
            return False
        except PyLinkyMaintenanceException as maintenanceExp:
            reason = "(verify your login password):"
            _LOGGER.warning("Unable to fetch Linky data %s %s", reason,
                            maintenanceExp)
            return False
        except PyLinkyWrongLoginException as accessExp:
            reason = "(your login is wrong ...):"
            _LOGGER.warning("Unable to fetch Linky data %s %s", reason,
                            accessExp)
            return False
        return True

    def update(self):
        """Return the latest collected data from Linky."""
        self._fetch_data()
        if not self.data:
            return
        _LOGGER.debug("Linky data retrieved: %s", str(self.data))
        self.halfhourly = list(reversed(self.data["hourly"]))
        self.daily = list(reversed(self.data["daily"]))
        self.monthly = list(reversed(self.data["monthly"]))
        self.yearly = list(reversed(self.data["yearly"]))
        self.success = True