Skip to content

Commit

Permalink
pre-release
Browse files Browse the repository at this point in the history
  • Loading branch information
m4dm4rtig4n committed Oct 11, 2021
1 parent b7e21d7 commit 3f640a5
Show file tree
Hide file tree
Showing 3 changed files with 120 additions and 52 deletions.
13 changes: 10 additions & 3 deletions app/daily.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def getDaily(cur, con, client, mode="consumption", last_activation_date=datetime
dateEnded = dateEnded.strftime('%Y-%m-%d')

data = dailyBeetwen(cur, con, pdl, mode, dateBegin, dateEnded, last_activation_date)
pprint(data)
if "error_code" in data:
f.publish(client, f"{pdl}/{mode}/current_year/error", str(1))
for key, value in data.items():
Expand Down Expand Up @@ -225,6 +226,12 @@ def dailyBeetwen(cur, con, pdl, mode, dateBegin, dateEnded, last_activation_date
f.log("Data not found :")
f.splitLog(not_found_data)

elif daily['error_code'] == 2:
f.log(f"Fetch data error detected beetween {dateBegin} / {dateEnded}")
f.log(f" => Load data from cache")
for date, data in current_data['date'].items():
mesures[date] = data['value']

list_date = list(reversed(sorted(mesures.keys())))

dateEnded = datetime.strptime(dateEnded, '%Y-%m-%d')
Expand Down Expand Up @@ -301,15 +308,15 @@ def dailyBeetwen(cur, con, pdl, mode, dateBegin, dateEnded, last_activation_date
if current_date >= dateYears:
energyYears = int(energyYears) + int(value)

response['thisWeek'] = {
response['this_week'] = {
"value": energyWeek,
"date": date
}
response['thisMonth'] = {
response['this_month'] = {
"value": energyMonths,
"date": date
}
response['thisYear'] = {
response['this_year'] = {
"value": energyYears,
"date": date
}
Expand Down
157 changes: 109 additions & 48 deletions app/detail.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,7 @@ def getDetail(cur, con, client, mode="consumption", last_activation_date=datetim
query_result = cur.fetchall()

result = {}
# result = {
# "measure_hp": 0,
# "measure_hp_wh": 0,
# "measure_hc": 0,
# "measure_hc_wh": 0,
# "measure_total": 0,
# "measure_total_wh": 0
# }
base_vs_offpeak = 0

for data in query_result:
date = data[1]
Expand Down Expand Up @@ -119,25 +112,87 @@ def getDetail(cur, con, client, mode="consumption", last_activation_date=datetim
result[year][month]["measure_hc_wh"] += int(value_wh)
result[year][month]["measure_total_wh"] += int(value_wh)

result[year][month]["mesure_ration_hp"] = round(100 * result[year][month]["measure_hp"] / result[year][month]["measure_total"], 2)
result[year][month]["mesure_ration_hc"] = round(100 * result[year][month]["measure_hc"] / result[year][month]["measure_total"], 2)

result[year][month]["measure_hp_euro"] = result[year][month]["measure_hp_wh"] / 1000 * price_hp
result[year][month]["measure_hc_euro"] = result[year][month]["measure_hc_wh"] / 1000 * price_hc
result[year][month]["measure_hphc_euro"] = result[year][month]["measure_hp_euro"] + result[year][month]["measure_hc_euro"]
result[year][month]["measure_base_euro"] = result[year][month]["measure_total_wh"] / 1000 * price_base
result[year][month]["measure_ration_hp"] = round(100 * result[year][month]["measure_hp"] / result[year][month]["measure_total"], 2)
result[year][month]["measure_ration_hc"] = round(100 * result[year][month]["measure_hc"] / result[year][month]["measure_total"], 2)

if price_base != 0:
result[year][month]["measure_base_euro"] = result[year][month]["measure_total_wh"] / 1000 * price_base

result[year][month]["base_vs_offpeak"] = 100 - (
if price_hc != 0 and price_hp != 0:
result[year][month]["measure_hp_euro"] = result[year][month]["measure_hp_wh"] / 1000 * price_hp
result[year][month]["measure_hc_euro"] = result[year][month]["measure_hc_wh"] / 1000 * price_hc
result[year][month]["measure_hphc_euro"] = result[year][month]["measure_hp_euro"] + result[year][month]["measure_hc_euro"]


result[year][month]["base_vs_offpeak"] = 100 - (
100 * result[year][month]["measure_base_euro"] / (result[year][month]["measure_hphc_euro"]))
if result[year][month]["base_vs_offpeak"] > 0:
result[year][month]["best_plan"] = f"BASE"
result[year][month]["best_plan_percent"] = f"{round(result[year][month]['base_vs_offpeak'], 2)}"
else:
result[year][month]["best_plan"] = f"HC/HP"
result[year][month]["best_plan_percent"] = f"{round(result[year][month]['base_vs_offpeak'], 2)}"

base_vs_offpeak += result[year][month]["base_vs_offpeak"]

if result[year][month]["base_vs_offpeak"] > 0:
result[year][month]["best_plan"] = f"BASE"
result[year][month]["best_plan_percent"] = f"{abs(round(result[year][month]['base_vs_offpeak'], 2))}"
else:
result[year][month]["best_plan"] = f"HC/HP"
result[year][month]["best_plan_percent"] = f"{abs(round(result[year][month]['base_vs_offpeak'], 2))}"

if base_vs_offpeak > 0:
best_plan = f"BASE"
best_plan_percent = f"{abs(round(result[year][month]['base_vs_offpeak'], 2))}"
else:
best_plan = f"HC/HP"
best_plan_percent = f"{abs(round(result[year][month]['base_vs_offpeak'], 2))}"

f.logLine()

year = dateObject.strftime('%Y')
month = dateObject.strftime('%m')
for plan in ["hc", "hp"]:
ha_discovery[pdl].update({
f"{mode}_detail_this_month_{plan}": {
"value": result[year][month][f"measure_{plan}_wh"],
"unit_of_meas": "kW",
"device_class": "energy",
"state_class": "total_increasing",
"attributes": {}
}
})
ha_discovery[pdl][f"{mode}_detail_this_month_{plan}"]["attributes"]["ratio"] = result[year][month][f"measure_ration_{plan}"]
ha_discovery[pdl][f"{mode}_detail_this_month_{plan}"]["attributes"]["W"] = result[year][month][f"measure_{plan}"]

if price_hc != 0 and price_hp != 0:
ha_discovery[pdl][f"{mode}_detail_this_month_{plan}"]["attributes"][f"measure_{plan}_euro"] = result[year][month][f"measure_{plan}_euro"]

ha_discovery[pdl].update({
f"{mode}_detail_this_month_base": {
"value": result[year][month]["measure_total_wh"],
"unit_of_meas": "kW",
"device_class": "energy",
"state_class": "total_increasing",
"attributes": {}
}
})
ha_discovery[pdl][f"{mode}_detail_this_month_base"]["attributes"]["W"] = result[year][month][f"measure_total"]
if price_base != 0:
ha_discovery[pdl][f"{mode}_detail_this_month_base"]["attributes"][f"measure_base_euro"] = result[year][month][f"measure_base_euro"]

if price_base != 0 and price_hc != 0 and price_hp != 0:
ha_discovery[pdl].update({
f"{mode}_detail_this_month_compare": {
"value": result[year][month][f"best_plan"],
"attributes": {}
}
})
ha_discovery[pdl][f"{mode}_detail_this_month_compare"]["attributes"]["best_plan_percent"] = result[year][month][f"best_plan_percent"]
ha_discovery[pdl].update({
f"{mode}_detail_this_year_compare": {
"value": best_plan,
"attributes": {}
}
})
ha_discovery[pdl][f"{mode}_detail_this_year_compare"]["attributes"]["best_plan_percent"] = best_plan_percent

for year, value in result.items():
for month, subvalue in value.items():
for key, subsubvalue in subvalue.items():
Expand Down Expand Up @@ -183,33 +238,39 @@ def is_between(time, time_range):
f.log(f" => Load data from API")

detail = f.apiRequest(cur, con, type="POST", url=f"{main.url}", headers=main.headers, data=json.dumps(data))
meter_reading = detail['meter_reading']
f.log("Import data :")
new_date = []
for interval_reading in meter_reading["interval_reading"]:
date = interval_reading['date']
interval_length = re.findall(r'\d+', interval_reading['interval_length'])[0]
value = int(interval_reading['value'])
measure_type = "HP"
dateObject = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
dateHourMinute = dateObject.strftime('%H:%M')
for offpeak_hour in offpeak_hours:
offpeak_begin = offpeak_hour.split("-")[0].replace('h', ':').replace('H', ':')
# FORMAT HOUR WITH 2 DIGIT
offpeak_begin = datetime.strptime(offpeak_begin, '%H:%M')
offpeak_begin = datetime.strftime(offpeak_begin, '%H:%M')
offpeak_stop = offpeak_hour.split("-")[1].replace('h', ':').replace('H', ':')
# FORMAT HOUR WITH 2 DIGIT
offpeak_stop = datetime.strptime(offpeak_stop, '%H:%M')
offpeak_stop = datetime.strftime(offpeak_stop, '%H:%M')
result = is_between(dateHourMinute, (offpeak_begin, offpeak_stop))
if result == True:
measure_type = "HC"
new_date.append(date)
query = f"INSERT OR REPLACE INTO {mode}_detail VALUES ('{pdl}','{date}',{value},{interval_length},'{measure_type}', 0)"
cur.execute(query)
con.commit()
f.log(f" => Import {len(new_date)} entry")
if not "error_code" in detail:
meter_reading = detail['meter_reading']
f.log("Import data :")
new_date = []
for interval_reading in meter_reading["interval_reading"]:
date = interval_reading['date']
interval_length = re.findall(r'\d+', interval_reading['interval_length'])[0]
value = int(interval_reading['value'])
measure_type = "HP"
dateObject = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
dateHourMinute = dateObject.strftime('%H:%M')
for offpeak_hour in offpeak_hours:
offpeak_begin = offpeak_hour.split("-")[0].replace('h', ':').replace('H', ':')
# FORMAT HOUR WITH 2 DIGIT
offpeak_begin = datetime.strptime(offpeak_begin, '%H:%M')
offpeak_begin = datetime.strftime(offpeak_begin, '%H:%M')
offpeak_stop = offpeak_hour.split("-")[1].replace('h', ':').replace('H', ':')
# FORMAT HOUR WITH 2 DIGIT
offpeak_stop = datetime.strptime(offpeak_stop, '%H:%M')
offpeak_stop = datetime.strftime(offpeak_stop, '%H:%M')
result = is_between(dateHourMinute, (offpeak_begin, offpeak_stop))
if result == True:
measure_type = "HC"
new_date.append(date)
query = f"INSERT OR REPLACE INTO {mode}_detail VALUES ('{pdl}','{date}',{value},{interval_length},'{measure_type}', 0)"
cur.execute(query)
con.commit()
f.log(f" => Import {len(new_date)} entry")

elif detail['error_code'] == 2:
f.log(f"Fetch data error detected beetween {dateBegin} / {dateEnded}")
f.log(f" => Load data from cache")

con.commit()
except Exception as e:
f.log(f"=====> ERROR : Exception - detailBeetwen <======")
Expand Down
2 changes: 1 addition & 1 deletion app/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def apiRequest(cur, con, type="POST", url=None, headers=None, data=None):
if query_result["day"] == datetime.now().strftime('%Y-%m-%d'):
if query_result["call_number"] > query_result["max_call"]:
return {
"error_code": 1,
"error_code": 2,
"errorMsg": f"API Call number per day is reached ({query_result['max_call']}), please wait until tomorrow to load the rest of data"
}
else:
Expand Down

0 comments on commit 3f640a5

Please sign in to comment.