Skip to content

Commit

Permalink
Merge pull request #17 from Ernst79/bug_fix
Browse files Browse the repository at this point in the history
Fix ValueError
  • Loading branch information
Ernst79 authored Jun 22, 2023
2 parents e07389b + 969531c commit f63e5a6
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 31 deletions.
2 changes: 1 addition & 1 deletion custom_components/degree_days/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ async def _async_update_data(self):
try:
self.gas_sensor_state = self.hass.states.get(self.gas_sensor)
self.gas_consumption = float(self.gas_sensor_state.state)
except AttributeError as err:
except AttributeError:
self.gas_consumption = 0
try:
data = await self.hass.async_add_executor_job(
Expand Down
51 changes: 25 additions & 26 deletions custom_components/degree_days/knmi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""Module to calculate the (weighted) degree days from KNMI data"""
from datetime import datetime
from io import StringIO
import requests
import pandas as pd
from io import StringIO
from datetime import datetime
import logging

from ..const import STATION_MAPPING, WEIGHT_FACTOR


class KNMI(object):
"""KMNI datas"""
def __init__(self, startdate, station, T_indoor, T_heatinglimit, gas_usage, gas_other):
self.startdate = startdate
self.station = station
Expand All @@ -24,10 +25,11 @@ def __init__(self, startdate, station, T_indoor, T_heatinglimit, gas_usage, gas_
self.gas_per_weighted_degree_day = data["gas_per_weighted_degree_day"]
self.gas_prognose = data["gas_prognose"]
else:
self.gas_per_weighted_degree_day = "Unavailable"
self.gas_prognose = "Unavailable"
self.gas_per_weighted_degree_day = None
self.gas_prognose = None

def get_degree_days(self):
"""Calculate degree days."""
enddate = datetime.now().strftime("%Y%m%d")

station_code = STATION_MAPPING[self.station]
Expand All @@ -36,20 +38,20 @@ def get_degree_days(self):
# Get data for the last 20 years
df = self.get_daily_data_df(self.startdate.replace(str(year), str(int(year) - 20), 1), enddate, [station_code],
variables)

df = df.rename(columns={' TG': 'TG'})
df['Date'] = pd.to_datetime(df['YYYYMMDD'], format='%Y%m%d')
df["TG"] = pd.to_numeric(df["TG"], errors='coerce', downcast="float")

# add day, month and year number
df['day'] = df['Date'].dt.dayofyear
df['month'] = df['Date'].dt.month
df['year'] = df['Date'].dt.year

# calculate mean of every yearday in range
df_average = df.groupby('day')['TG'].mean().reset_index(name="TG_average")
df = pd.merge(df, df_average, on=['day'], how='left')

# add weight factor based on month
df['WF'] = df['month'].map(lambda value: WEIGHT_FACTOR[value])

Expand All @@ -70,9 +72,9 @@ def get_degree_days(self):
WDD = df[df.Date >= self.startdate].WDD.sum()
WDD_average_total = df[df["Date"].between(startdate_offset_year, self.startdate)].WDD_average.sum()
WDD_average_cum = df[df.Date >= self.startdate].WDD_average.sum()

data = {}

data["last_update"] = df["YYYYMMDD"].iloc[-1]
data["total_degree_days_this_year"] = DD
data["weighted_degree_days_year"] = WDD
Expand Down Expand Up @@ -101,11 +103,11 @@ def calculate_DD(self, TG, WF):
if self.T_heatinglimit - TG/10 <= 0:
return 0
else:
return(max(self.T_indoor - TG/10 , 0) * WF)
return (max(self.T_indoor - TG / 10, 0) * WF)

def get_daily_data_df(self, startdate, enddate, stations, variables):
"""Request and parse data from knmi api.
Parameters
----------
start : str
Expand All @@ -116,7 +118,7 @@ def get_daily_data_df(self, startdate, enddate, stations, variables):
List of station numbers in int format, by default None
variables : [str], optional
List of variables in str format, if None is given, all are returned by the api
Returns
-------
DataFrame
Expand All @@ -125,11 +127,10 @@ def get_daily_data_df(self, startdate, enddate, stations, variables):
r = self.get_daily_data_raw(startdate, enddate, stations, variables)
df = self.parse_result_to_df(r)
return df



def get_daily_data_raw(self, start, end, stations=None, variables=None):
"""Get raw data from knmi api.
See: https://www.knmi.nl/kennis-en-datacentrum/achtergrond/data-ophalen-vanuit-een-script
Parameters
----------
Expand All @@ -141,7 +142,7 @@ def get_daily_data_raw(self, start, end, stations=None, variables=None):
List of station numbers in int format, by default None
variables : [str], optional
List of variables in str format, if None is given, all are returned by the api
Returns
-------
str
Expand All @@ -154,11 +155,10 @@ def get_daily_data_raw(self, start, end, stations=None, variables=None):
params = self.add_list_items_to_params(params, 'vars', variables)
r = requests.post(url=url, data=params)
return r.text



def add_list_items_to_params(self, params, name, variables):
"""Add every variable in var_list to the parameter string.
Parameters
----------
params : str
Expand All @@ -167,7 +167,7 @@ def add_list_items_to_params(self, params, name, variables):
Name of the variable, specified by knmi api
variables : list
Containing items to be added to params
Returns
-------
str
Expand All @@ -180,16 +180,15 @@ def add_list_items_to_params(self, params, name, variables):
vars_parsed = vars_parsed + ':' + str(var)
params = params + '&' + name + '=' + vars_parsed
return params



def parse_result_to_df(self, response_text):
"""Parse result of function get_daily_data_raw
Parameters
----------
response_text : str
Containing data returned by knmi api
Returns
-------
DataFrame
Expand Down
10 changes: 6 additions & 4 deletions custom_components/degree_days/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
"domain": "degree_days",
"name": "Degree-Days",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/degree_days",
"codeowners": ["@Ernst79", "@nelbs"],
"dependencies": [],
"documentation": "https://www.home-assistant.io/integrations/degree_days",
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/Ernst79/degree-days/issues",
"requirements": [],
"version": "0.9.0",
"iot_class": "cloud_polling"
"version": "0.9.1"
}


0 comments on commit f63e5a6

Please sign in to comment.