From 2aebe9663b33f0c62d9a18a0ced93e660b15d566 Mon Sep 17 00:00:00 2001 From: linsvensson Date: Sun, 12 May 2024 22:51:45 +0200 Subject: [PATCH] Handling no primary facility set --- custom_components/greenely/api.py | 13 ++++++++----- custom_components/greenely/manifest.json | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/custom_components/greenely/api.py b/custom_components/greenely/api.py index 900e7e2..5bace4e 100644 --- a/custom_components/greenely/api.py +++ b/custom_components/greenely/api.py @@ -1,7 +1,6 @@ """Greenely API""" import logging from datetime import datetime, timedelta -import calendar import requests import json @@ -24,9 +23,9 @@ def __init__(self, email, password, facility_id): def get_price_data(self): today = datetime.today() + nextMonth = (today.replace(day=1) + timedelta(days=32)).replace(day=1) start = "?from=" + str(today.year) + "-" + today.strftime("%m") + "-01" - endOfMonth = calendar.monthrange(today.year, today.month)[1] - end = "&to=" + str(today.year) + "-" + today.strftime("%m") + "-" + str(endOfMonth); + end = "&to=" + str(nextMonth.year) + "-" + nextMonth.strftime("%m") + "-01" url = self._url_facilities_base + self._facility_id + '/consumption' + start + end + "&resolution=daily&unit=currency&operation=sum" response = requests.get(url, headers = self._headers) data = {} @@ -68,13 +67,17 @@ def get_usage(self, startDate, endDate, showHourly): return data def get_facility_id(self): - result = requests.get(self._url_facilities_base + 'primary?includes=retail_state&includes=consumption_limits&includes=parameters', headers = self._headers) + result = requests.get(self._url_facilities_base, headers = self._headers) if result.status_code == requests.codes.ok: data = result.json() + facility = next((f for f in data if f['is_primary'] == True), None) + if facility == None: + _LOGGER.debug('Found no primary facility, using the first one in the list!') + facility = data[0] self._facility_id = str(data['data']['parameters']['facility_id']) _LOGGER.debug('Fetched facility id %s', self._facility_id) else: - _LOGGER.error('Failed to fetch facility id %s', result.text) + _LOGGER.error('Failed to fetch facility id %s', result.reason) def check_auth(self): """Check to see if our jwt is valid.""" diff --git a/custom_components/greenely/manifest.json b/custom_components/greenely/manifest.json index 85d054d..18aa9ac 100644 --- a/custom_components/greenely/manifest.json +++ b/custom_components/greenely/manifest.json @@ -1,7 +1,7 @@ { "domain": "greenely", "name": "Greenely Sensors", - "version": "1.0.6", + "version": "1.0.7", "documentation": "https://github.com/linsvensson/sensor.greenely", "issue_tracker": "https://github.com/linsvensson/sensor.greenely/issues", "codeowners": ["@linsvensson"],