Skip to content

Commit

Permalink
doc
Browse files Browse the repository at this point in the history
  • Loading branch information
m4dm4rtig4n committed Dec 16, 2022
1 parent 6c65a0a commit d4d31a3
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 21 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ La dépendance à MQTT n'est plus obligatoire et je supporte :
* Hassio Addons : https://github.com/alexbelgium/hassio-addons/tree/master/myelectricaldata
* Saniho Card pour Home Assistant : https://github.com/saniho/content-card-linky

# Dashboard Grafana
* https://github.com/geobar78/Myelectricaldata-Graphana-Dashbord

<img src="imgs/grafana_geobar78.png" alt="drawing" style="width:200px;"/>

## Informations

MyElectricalData utilise une [API](https://myelectricaldata.fr/) dédiée afin de récupérer toutes les informations auprès d'Enedis.
Expand Down
15 changes: 13 additions & 2 deletions app/models/export_home_assistant.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from dateutil.relativedelta import relativedelta

from models.stat import Stat
from models.log import Log

utc = pytz.UTC

Expand Down Expand Up @@ -123,8 +124,18 @@ def convert_kw_to_euro(value, price):
idx = 0
while idx <= 6:
_offpeak_hours = []
for offpeak_hours_data in getattr(usage_point, f"offpeak_hours_{idx}").split(";"):
_offpeak_hours.append(offpeak_hours_data.split("-"))
offpeak_hour = getattr(usage_point, f"offpeak_hours_{idx}")
if type(offpeak_hour) != str:
Log().error([
f"offpeak_hours_{idx} n'est pas une chaine de caractère",
" Format si une seul période : 00H00-06H00",
" Format si plusieurs périodes : 00H00-06H00;12H00-14H00"
])
else:
for offpeak_hours_data in getattr(usage_point, f"offpeak_hours_{idx}").split(";"):
if type(offpeak_hours_data) == str:
_offpeak_hours.append(offpeak_hours_data.split("-"))

offpeak_hours.append(_offpeak_hours)
idx = idx + 1

Expand Down
59 changes: 48 additions & 11 deletions app/models/export_mqtt.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import __main__ as app

from datetime import datetime

from dateutil.relativedelta import relativedelta


class ExportMqtt:

def __init__(self, usage_point_id, measurement_direction="consumption"):
Expand All @@ -14,19 +15,55 @@ def status(self):
app.LOG.title(f"[{self.usage_point_id}] Statut du compte.")
usage_point_id_config = app.DB.get_usage_point(self.usage_point_id)
# consentement_expiration_date = usage_point_id_config.consentement_expiration.strftime("%Y-%m-%d %H:%M:%S")
if hasattr(usage_point_id_config,
"consentement_expiration") and usage_point_id_config.consentement_expiration is not None:
consentement_expiration = usage_point_id_config.consentement_expiration.strftime("%Y-%m-%d %H:%M:%S")
else:
consentement_expiration = ""
if hasattr(usage_point_id_config,
"call_number") and usage_point_id_config.call_number is not None:
call_number = usage_point_id_config.call_number
else:
call_number = ""
if hasattr(usage_point_id_config,
"quota_reached") and usage_point_id_config.quota_reached is not None:
quota_reached = usage_point_id_config.quota_reached
else:
quota_reached = ""
if hasattr(usage_point_id_config,
"quota_limit") and usage_point_id_config.quota_limit is not None:
quota_limit = usage_point_id_config.quota_limit
else:
quota_limit = ""
if hasattr(usage_point_id_config,
"quota_reset_at") and usage_point_id_config.quota_reset_at is not None:
quota_reset_at = usage_point_id_config.quota_reset_at.strftime(
"%Y-%m-%d %H:%M:%S"),
else:
quota_reset_at = ""
if hasattr(usage_point_id_config,
"last_call") and usage_point_id_config.last_call is not None:
last_call = usage_point_id_config.last_call.strftime(
"%Y-%m-%d %H:%M:%S"),
else:
last_call = ""
if hasattr(usage_point_id_config,
"ban") and usage_point_id_config.ban is not None:
ban = usage_point_id_config.ban
else:
ban = ""
consentement_expiration = {
f"{self.usage_point_id}/status/consentement_expiration": usage_point_id_config.consentement_expiration.strftime("%Y-%m-%d %H:%M:%S"),
f"{self.usage_point_id}/status/call_number": usage_point_id_config.call_number,
f"{self.usage_point_id}/status/quota_reached": usage_point_id_config.quota_reached,
f"{self.usage_point_id}/status/quota_limit": usage_point_id_config.quota_limit,
f"{self.usage_point_id}/status/quota_reset_at": usage_point_id_config.quota_reset_at.strftime("%Y-%m-%d %H:%M:%S"),
f"{self.usage_point_id}/status/last_call": usage_point_id_config.last_call.strftime("%Y-%m-%d %H:%M:%S"),
f"{self.usage_point_id}/status/ban": usage_point_id_config.ban
f"{self.usage_point_id}/status/consentement_expiration": consentement_expiration,
f"{self.usage_point_id}/status/call_number": call_number,
f"{self.usage_point_id}/status/quota_reached": quota_reached,
f"{self.usage_point_id}/status/quota_limit": quota_limit,
f"{self.usage_point_id}/status/quota_reset_at": quota_reset_at,
f"{self.usage_point_id}/status/last_call": last_call,
f"{self.usage_point_id}/status/ban": ban
}
app.MQTT.publish_multiple(consentement_expiration)
app.LOG.log(" => Finish")


def contract(self):
app.LOG.title(f"[{self.usage_point_id}] Exportation de données dans MQTT.")

Expand Down Expand Up @@ -169,7 +206,7 @@ def daily_annual(self, price):
date_begin = datetime.combine(date_range["begin"], datetime.min.time())
date_end = datetime.combine(date_range["end"], datetime.max.time())
date_begin_current = datetime.combine(date_end.replace(month=1).replace(day=1),
datetime.min.time())
datetime.min.time())
finish = False
while not finish:
sub_prefix = f"{self.usage_point_id}/{self.measurement_direction}/annual/{date_begin_current.strftime('%Y')}"
Expand Down Expand Up @@ -328,7 +365,7 @@ def detail_annual(self, price_hp, price_hc=0):
date_begin = datetime.combine(date_range["begin"], datetime.min.time())
date_end = datetime.combine(date_range["end"], datetime.max.time())
date_begin_current = datetime.combine(date_end.replace(month=1).replace(day=1),
datetime.min.time())
datetime.min.time())
finish = False
while not finish:
sub_prefix = f"{self.usage_point_id}/{self.measurement_direction}/annual/{date_begin_current.strftime('%Y')}"
Expand Down
12 changes: 9 additions & 3 deletions app/models/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,9 @@ def job_import_data(self, wait=True, target=None):
try:
# #######################################################################################################
# # MQTT
LOG.title("Exportation MQTT")
if "enable" in self.mqtt_config and self.mqtt_config["enable"]:
if target == "mqtt" or target is None:
LOG.title("Exportation MQTT")
ExportMqtt(self.usage_point_id).status()
ExportMqtt(self.usage_point_id).contract()
ExportMqtt(self.usage_point_id).address()
Expand Down Expand Up @@ -140,7 +140,9 @@ def job_import_data(self, wait=True, target=None):
"production_detail") and self.usage_point_config.production_detail:
ExportMqtt("production").detail_annual(self.usage_point_config.production_price)
ExportMqtt("production").detail_linear(self.usage_point_config.production_price)
LOG.log(" => Export terminé")
else:
LOG.title("Exportation MQTT")
LOG.log(" => Désactivé dans la configuration (Exemple: https://tinyurl.com/2kbd62s9)")
except Exception as e:
traceback.print_exc()
Expand All @@ -149,15 +151,17 @@ def job_import_data(self, wait=True, target=None):
#######################################################################################################
# HOME ASSISTANT
try:
LOG.title("Exportation Home Assistant")
if "enable" in self.home_assistant_config and str2bool(self.home_assistant_config["enable"]):
if "enable" in self.mqtt_config and str2bool(self.mqtt_config["enable"]):
if target == "home_assistant" or target is None:
LOG.title("Exportation Home Assistant")
HomeAssistant(self.usage_point_id).export()
LOG.log(" => Export terminé")
else:
LOG.critical("L'export Home Assistant est dépendant de MQTT, "
"merci de configurer MQTT avant d'exporter vos données dans Home Assistant")
else:
LOG.title("Exportation Home Assistant")
LOG.log(" => Désactivé dans la configuration (Exemple: https://tinyurl.com/2kbd62s9)")
except Exception as e:
traceback.print_exc()
Expand All @@ -166,10 +170,10 @@ def job_import_data(self, wait=True, target=None):
#######################################################################################################
# INFLUXDB
try:
LOG.title("Exportation InfluxDB")
if "enable" in self.influxdb_config and self.influxdb_config["enable"]:
# app.INFLUXDB.purge_influxdb()
if target == "influxdb" or target is None:
LOG.title("Exportation InfluxDB")
if hasattr(self.usage_point_config,
"consumption") and self.usage_point_config.consumption:
ExportInfluxDB(self.usage_point_id).daily(
Expand All @@ -193,7 +197,9 @@ def job_import_data(self, wait=True, target=None):
self.usage_point_config.production_price,
measurement_direction="production_detail"
)
LOG.log(" => Export terminé")
else:
LOG.title("Exportation InfluxDB")
LOG.log(" => Désactivé dans la configuration (Exemple: https://tinyurl.com/2kbd62s9)")
except Exception as e:
traceback.print_exc()
Expand Down
15 changes: 10 additions & 5 deletions app/models/query_status.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import datetime
import json
import traceback
from os import environ, getenv

import __main__ as app

Expand Down Expand Up @@ -46,9 +47,9 @@ def status(self, usage_point_id):
if hasattr(usage_point_id_config, "cache") and usage_point_id_config.cache:
target += "/cache"
response = Query(endpoint=target, headers=self.headers).get()
status = json.loads(response.text)
if response.status_code == 200:
try:
status = json.loads(response.text)
for key, value in status.items():
app.LOG.log(f"{key}: {value}")
app.DB.usage_point_update(
Expand All @@ -62,15 +63,19 @@ def status(self, usage_point_id):
ban=status["ban"]
)
return status
except LookupError:
traceback.print_exc()
except Exception as e:
if "DEBUG" in environ and getenv("DEBUG"):
traceback.print_exc()
Log().error(e)
return {
"error": True,
"description": "Erreur lors de la récupération du statut du compte."
}
else:
traceback.print_exc()
if "DEBUG" in environ and getenv("DEBUG"):
traceback.print_exc()
Log().error(status["detail"])
return {
"error": True,
"description": "Erreur lors de la récupération du statut du compte."
"description": status["detail"]
}
Binary file added imgs/grafana_geobar78.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit d4d31a3

Please sign in to comment.