Skip to content

Commit

Permalink
Merge pull request #495 from MyElectricalData/fix/494-489
Browse files Browse the repository at this point in the history
Fix/494 489
  • Loading branch information
m4dm4rtig4n authored Feb 12, 2024
2 parents 9a8ed45 + a36f18b commit ca35bff
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 66 deletions.
46 changes: 33 additions & 13 deletions src/models/export_home_assistant_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
import logging
import ssl
from datetime import datetime, timedelta
from pprint import pprint

import pytz
import websocket

from init import CONFIG, DB
from models.stat import Stat
from dependencies import str2bool

TZ_PARIS = pytz.timezone("Europe/Paris")

Expand All @@ -21,6 +24,7 @@ def __init__(self, usage_point_id):
self.ssl = None
self.token = None
self.id = 1
self.purge = False
self.current_stats = []
if self.load_config():
if self.connect():
Expand Down Expand Up @@ -50,6 +54,8 @@ def load_config(self):
else:
logging.critical("Le token du WebSocket Home Assistant est obligatoire")
return False
if "purge" in self.config:
self.purge = str2bool(self.config["purge"])
return True

def connect(self):
Expand Down Expand Up @@ -111,14 +117,15 @@ def list_data(self):
self.current_stats.append(stats["statistic_id"])
return current_stats

def clear_data(self):
def clear_data(self, statistic_ids):
logging.info("Effacement des données importées dans Energy.")
for key in statistic_ids:
logging.info(f" - {key}")
clear_statistics = {
"id": self.id,
"type": "recorder/clear_statistics",
"statistic_ids": self.current_stats,
"statistic_ids": statistic_ids,
}
logging.info("Clean :")
for data in self.current_stats:
logging.info(f" - {data}")
clear_stat = self.send(clear_statistics)
Expand All @@ -142,7 +149,7 @@ def import_data(self):
plan = self.usage_point_id_config.plan.upper()
if self.usage_point_id_config.consumption_detail:
logging.info("Consommation")
measure_type = "consumption"
measurement_direction = "consumption"
if "max_date" in self.config:
logging.warn(f"WARNING : Max date détecter {self.config['max_date']}")
begin = datetime.strptime(self.config["max_date"], "%Y-%m-%d")
Expand All @@ -162,6 +169,8 @@ def import_data(self):
for tempo_data in DB.get_tempo():
tempo_color_ref[tempo_data.date] = tempo_data.color

stats = Stat(usage_point_id=self.usage_point_id, measurement_direction="consumption")

for data in detail:
year = int(f'{data.date.strftime("%Y")}')
if last_year is None or year != last_year:
Expand All @@ -176,17 +185,18 @@ def import_data(self):
statistic_id = f"myelectricaldata:{self.usage_point_id}"
value = data.value / (60 / data.interval)
if plan == "BASE":
name = f"{name} {plan} {measure_type}"
statistic_id = f"{statistic_id}_{plan.lower()}_{measure_type}"
name = f"{name} {plan} {measurement_direction}"
statistic_id = f"{statistic_id}_{plan.lower()}_{measurement_direction}"
cost = value * self.usage_point_id_config.consumption_price_base / 1000
elif plan == "HC/HP":
if data.measure_type == "HC":
name = f"{name} HC {measure_type}"
statistic_id = f"{statistic_id}_hc_{measure_type}"
measure_type = stats.get_mesure_type(data.date)
if measure_type == "HC":
name = f"{name} HC {measurement_direction}"
statistic_id = f"{statistic_id}_hc_{measurement_direction}"
cost = value * self.usage_point_id_config.consumption_price_hc / 1000
else:
name = f"{name} HP {measure_type}"
statistic_id = f"{statistic_id}_hp_{measure_type}"
name = f"{name} HP {measurement_direction}"
statistic_id = f"{statistic_id}_hp_{measurement_direction}"
cost = value * self.usage_point_id_config.consumption_price_hp / 1000
elif plan == "TEMPO":
if 600 <= hour_minute < 2200:
Expand All @@ -206,8 +216,8 @@ def import_data(self):
tempo_color_price_key = f"{day_color.lower()}_{hour_type.lower()}"
tempo_price = float(db_tempo_price[tempo_color_price_key])
cost = value / 1000 * tempo_price
name = f"{name} {tempo_color} {measure_type}"
statistic_id = f"{statistic_id}_{tempo_color.lower()}_{measure_type}"
name = f"{name} {tempo_color} {measurement_direction}"
statistic_id = f"{statistic_id}_{tempo_color.lower()}_{measurement_direction}"
else:
logging.error(f"Plan {plan} inconnu.")

Expand Down Expand Up @@ -248,7 +258,16 @@ def import_data(self):
stats_euro[statistic_id]["sum"] += cost
stats_euro[statistic_id]["data"][key]["sum"] = stats_euro[statistic_id]["sum"]

# CLEAN OLD DATA
if self.purge:
list_statistic_ids = []
for statistic_id, _ in stats_kwh.items():
list_statistic_ids.append(statistic_id)
self.clear_data(list_statistic_ids)
CONFIG.set("purge", False)

for statistic_id, data in stats_kwh.items():
# self.clear_data(statistic_id)
metadata = {
"has_mean": False,
"has_sum": True,
Expand All @@ -266,6 +285,7 @@ def import_data(self):
self.send(import_statistics)

for statistic_id, data in stats_euro.items():
# self.clear_data(statistic_id)
metadata = {
"has_mean": False,
"has_sum": True,
Expand Down
7 changes: 5 additions & 2 deletions src/models/export_influxdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from init import INFLUXDB, DB

from datetime import datetime
from models.stat import Stat


def forceRound(x, n):
Expand All @@ -24,6 +25,7 @@ def __init__(self, influxdb_config, usage_point_config, measurement_direction="c
self.usage_point_config = usage_point_config
self.usage_point_id = self.usage_point_config.usage_point_id
self.measurement_direction = measurement_direction
self.stat = Stat(self.usage_point_id, measurement_direction=measurement_direction)
self.time_format = "%Y-%m-%dT%H:%M:%SZ"
if "timezone" not in self.influxdb_config or self.influxdb_config["timezone"] == "UTC":
self.tz = pytz.UTC
Expand Down Expand Up @@ -121,7 +123,8 @@ def detail(self, measurement_direction="consumption"):
watth = watt / (60 / detail.interval)
kwatth = watth / 1000
if measurement_direction == "consumption":
if detail.measure_type == "HP":
measure_type = self.stat.get_mesure_type(date)
if measure_type == "HP":
euro = kwatth * self.usage_point_config.consumption_price_hp
else:
euro = kwatth * self.usage_point_config.consumption_price_hc
Expand All @@ -135,7 +138,7 @@ def detail(self, measurement_direction="consumption"):
"year": detail.date.strftime("%Y"),
"month": detail.date.strftime("%m"),
"internal": detail.interval,
"measure_type": detail.measure_type,
"measure_type": measure_type,
},
fields={
"W": float(watt),
Expand Down
103 changes: 52 additions & 51 deletions src/templates/usage_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,57 +228,58 @@ def display(self):
today = datetime.combine(datetime.now(), datetime.min.time())
tomorow = datetime.combine(datetime.now() + timedelta(days=1), datetime.min.time())
tempo = self.db.get_tempo_range(today, tomorow, "asc")
body += f"""
<table style="width:100%" class="table_recap">
<tr>
<td style="width:50%; text-align: center">Aujourd'hui <br> {today.strftime("%d-%m-%Y")}</td>
<td style="width:50%; text-align: center">Demain <br> {tomorow.strftime("%d-%m-%Y")}</td>
</tr>
<tr>"""
tempo_template = {
"?": {
"color": "background-color: #000000",
"text_color": "color: #FFFFFF",
"text": "En attente...",
},
"RED": {
"color": "background-color: #E74C3C",
"text_color": "color: #ECF0F1",
"text": f"""Rouge<br>
06h00 -> 22h00 = {tempo_config['red_hp']}€ / kWh<br>
22h00 -> 06h00 = {tempo_config['red_hc']}€ / kWh<br>
""",
},
"WHITE": {
"color": "background-color: #ECF0F1",
"text_color": "color: #34495E",
"text": f"""Blanc<br>
06h00 -> 22h00 = {tempo_config['white_hp']}€ / kWh<br>
22h00 -> 06h00 = {tempo_config['white_hc']}€ / kWh
""",
},
"BLUE": {
"color": "background-color: #3498DB",
"text_color": "color: #ECF0F1",
"text": f"""Bleu<br>
06h00 -> 22h00 = {tempo_config['blue_hp']}€ / kWh<br>
22h00 -> 06h00 = {tempo_config['blue_hc']}€ / kWh
""",
},
}
if len(tempo) > 0:
color = tempo[0].color
else:
color = "?"
body += f"""<td style="width:50%; text-align: center; {tempo_template[color]["color"]};{tempo_template[color]["text_color"]}">{tempo_template[color]["text"]}</td>"""
if len(tempo) > 1:
color = tempo[1].color
else:
color = "?"
body += f"""<td style="width:50%; text-align: center; {tempo_template[color]["color"]};{tempo_template[color]["text_color"]}">{tempo_template[color]["text"]}</td>"""
body += """</tr>
</table>
"""
if tempo_config:
body += f"""
<table style="width:100%" class="table_recap">
<tr>
<td style="width:50%; text-align: center">Aujourd'hui <br> {today.strftime("%d-%m-%Y")}</td>
<td style="width:50%; text-align: center">Demain <br> {tomorow.strftime("%d-%m-%Y")}</td>
</tr>
<tr>"""
tempo_template = {
"?": {
"color": "background-color: #000000",
"text_color": "color: #FFFFFF",
"text": "En attente...",
},
"RED": {
"color": "background-color: #E74C3C",
"text_color": "color: #ECF0F1",
"text": f"""Rouge<br>
06h00 -> 22h00 = {tempo_config['red_hp']}€ / kWh<br>
22h00 -> 06h00 = {tempo_config['red_hc']}€ / kWh<br>
""",
},
"WHITE": {
"color": "background-color: #ECF0F1",
"text_color": "color: #34495E",
"text": f"""Blanc<br>
06h00 -> 22h00 = {tempo_config['white_hp']}€ / kWh<br>
22h00 -> 06h00 = {tempo_config['white_hc']}€ / kWh
""",
},
"BLUE": {
"color": "background-color: #3498DB",
"text_color": "color: #ECF0F1",
"text": f"""Bleu<br>
06h00 -> 22h00 = {tempo_config['blue_hp']}€ / kWh<br>
22h00 -> 06h00 = {tempo_config['blue_hc']}€ / kWh
""",
},
}
if len(tempo) > 0:
color = tempo[0].color
else:
color = "?"
body += f"""<td style="width:50%; text-align: center; {tempo_template[color]["color"]};{tempo_template[color]["text_color"]}">{tempo_template[color]["text"]}</td>"""
if len(tempo) > 1:
color = tempo[1].color
else:
color = "?"
body += f"""<td style="width:50%; text-align: center; {tempo_template[color]["color"]};{tempo_template[color]["text_color"]}">{tempo_template[color]["text"]}</td>"""
body += """</tr>
</table>
"""

body += "<h1>Récapitulatif</h1>"
# RECAP CONSUMPTION
Expand Down

0 comments on commit ca35bff

Please sign in to comment.