class LinkyData(object): """Get data from Linky.""" def __init__(self, username, password): """Initialize the data object.""" self._username = username self._password = password self.client = {} self.data = {} @Throttle(MIN_TIME_BETWEEN_UPDATES) def _fetch_data(self): """Fetch latest data from Linky.""" from pylinky.client import PyLinkyError from pylinky import LinkyClient try: self.client = LinkyClient(self._username, self._password) self.client.fetch_data() except PyLinkyError as exp: _LOGGER.error("Error on receive last Linky data: %s", exp) return False return True def update(self): """Return the latest collected data from Linky.""" self._fetch_data() self.data = self.client.get_data()
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
def main(): """Main function""" parser = argparse.ArgumentParser() parser.add_argument('-u', '--username', required=True, help='enedis username') parser.add_argument('-p', '--password', required=True, help='Password') args = parser.parse_args() client = LinkyClient(args.username, args.password) try: client.fetch_data() except BaseException as exp: print(exp) return 1 finally: client.close_session() print(json.dumps(client.get_data(), indent=2))
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
def main(): """Main function""" parser = argparse.ArgumentParser() parser.add_argument('-c', '--client-id', required=True, help='Client ID from Enedis') parser.add_argument('-s', '--client-secret', required=True, help='Client Secret from Enedis') parser.add_argument( '-u', '--redirect-url', required=True, help='Redirect URL as stated in the Enedis admin console') parser.add_argument('-t', '--test-consumer', required=False, help='Test consumer for sandbox 0-9') parser.add_argument('-v', '--verbose', required=False, action='store_true', help='Verbose, debug network calls') args = parser.parse_args() if (args.verbose): '''Switches on logging of the requests module.''' HTTPConnection.debuglevel = 2 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True test_consumer = args.test_consumer auth = AbstractAuth(client_id=args.client_id, client_secret=args.client_secret, redirect_url=args.redirect_url) linky_api = LinkyAPI(auth) try: authorization_url = linky_api.get_authorisation_url( test_customer=test_consumer) print("Please go to \n{}\nand authorize access.".format( authorization_url)) authorization_response = input("Enter the full callback URL :\n") authorization_response_qa = parse_qs( urlparse(authorization_response).query) code = authorization_response_qa["code"][0] state = authorization_response_qa["state"][0] token = linky_api.request_tokens(code) # Not needed, just a test to make sure that refresh_tokens works token = auth.refresh_tokens() usage_point_ids = linky_api.get_usage_point_ids() for usage_point_id in usage_point_ids: print(usage_point_id) response = linky_api.get_customer_identity(usage_point_id) print("get_customer_identity") print(response.content) #input("Press a key") response = linky_api.get_customer_contact_data(usage_point_id) print("get_customer_contact_data") print(response.content) #input("Press a key") response = linky_api.get_customer_usage_points_contracts( usage_point_id) print("get_customer_usage_points_contracts") print(response.content) #input("Press a key") response = linky_api.get_customer_usage_points_addresses( usage_point_id) print("get_customer_usage_points_addresses") print(response.content) #input("Press a key") response = linky_api.get_consumption_load_curve( usage_point_id, "2020-03-01", "2020-03-05") print("get_consumption_load_curve") print(response.content) #input("Press a key") response = linky_api.get_production_load_curve( usage_point_id, "2020-03-01", "2020-03-05") print("get_production_load_curve") print(response.content) #input("Press a key") response = linky_api.get_daily_consumption_max_power( usage_point_id, "2020-03-01", "2020-03-05") print("get_daily_consumption_max_power") print(response.content) #input("Press a key") response = linky_api.get_daily_consumption(usage_point_id, "2020-03-01", "2020-03-05") print("get_daily_consumption") print(response.content) #input("Press a key") response = linky_api.get_daily_production(usage_point_id, "2020-03-01", "2020-03-05") print("get_daily_production") print(response.content) #input("Press a key") linky_client = LinkyClient(auth) linky_client.fetch_data() data = linky_client.get_data() print(data) except BaseException as exp: print(exp) return 1 finally: linky_api.close_session() linky_client.close_session()