Skip to content

Commit

Permalink
maj
Browse files Browse the repository at this point in the history
  • Loading branch information
m4dm4rtig4n committed Oct 3, 2022
1 parent 82468e4 commit 316c217
Show file tree
Hide file tree
Showing 10 changed files with 605 additions and 373 deletions.
Empty file removed app/__init__.py
Empty file.
7 changes: 2 additions & 5 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')

url = "https://myelectricaldata.fr/api"
url = "https://myelectricaldata.fr"

fail_count = 24

f = open("/app/VERSION", "r")
VERSION = f.read()
f.close()
cycle_minimun = 3600
596 changes: 283 additions & 313 deletions app/main.py

Large diffs are not rendered by default.

30 changes: 21 additions & 9 deletions app/models/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

from dependencies import *
from config import *
from models.log import log, logSep
from models.config import CONFIG
from models.log import log, logSep, logWarn, critical
from models.config import CONFIG, get_version


class Cache:
Expand Down Expand Up @@ -35,15 +35,16 @@ def init_database(self):
"day": datetime.datetime.now().strftime('%Y-%m-%d'),
"call_number": 0,
"max_call": 500,
"version": VERSION
"version": get_version()
})])
self.sqlite.commit()
log(" => Success")
log(" => Initialization success")
except Exception as e:
log("=====> ERROR : Exception <======")
log(e)
log('<!> SQLite Database initialisation failed <!>')
log(" => Reset database")
msg = [
"=====> ERROR : Exception <======", e,
'<!> SQLite Database initialisation failed <!>',
]
critical(msg)

def check(self):
logSep()
Expand Down Expand Up @@ -88,7 +89,7 @@ def check(self):
self.cursor.execute(config_query)
query_result = self.cursor.fetchall()
json.loads(query_result[0][1])
log(" => Success")
log(" => Connection success")
except Exception as e:
log("=====> ERROR : Exception <======")
log(e)
Expand All @@ -107,3 +108,14 @@ def purge_cache(self):
log(" => Success")
else:
log(" => Not cache detected")

def get_contract(self, usage_point_id):
query = f"SELECT * FROM contracts WHERE pdl = '{usage_point_id}'"
self.cursor.execute(query)
query_result = self.cursor.fetchone()
return query_result

def insert_contract(self, usage_point_id, contract, count):
query = f"INSERT OR REPLACE INTO contracts VALUES (?,?,?)'"
self.cursor.execute(query, [usage_point_id, json.dumps(contract), count])
self.sqlite.commit()
63 changes: 31 additions & 32 deletions app/models/config.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import os

import re
from ruamel.yaml import YAML
# import yaml
import sys

from pathlib import Path

import yaml
import json

from models.log import log, critical, logSep


def get_version():
f = open("/app/VERSION", "r")
version = f.read()
f.close()
return version


class Config:

def __init__(self, path="/data"):
Expand Down Expand Up @@ -70,16 +80,16 @@ def __init__(self, path="/data"):

def load(self):
config_file = f'{self.path_file}'
yaml = YAML()
if os.path.exists(config_file):
with open(f'{self.path_file}') as file:
with open(f'{self.path}/config.yaml') as file:
self.config = yaml.load(file, Loader=yaml.FullLoader)
else:
f = open(config_file, "a")
f.write(yaml.dump(self.default))
f.close()
with open(f'{self.path_file}') as file:
with open(f'{self.path}/config.yaml') as file:
self.config = yaml.load(file, Loader=yaml.FullLoader)

if self.config is None:
critical([
"Impossible de charger le fichier de configuration.",
Expand Down Expand Up @@ -151,13 +161,16 @@ def display(self):
if type(dic_value) is dict:
log(f" {dic_key}:")
for dic1_key, dic1_value in dic_value.items():
dic1_value = "** hidden **" if dic1_key == "password" or dic1_key == "token" else 0
if dic1_key == "password" or dic1_key == "token":
dic1_value = "** hidden **"
log(f" {dic1_key}: {dic1_value}")
else:
dic_value = "** hidden **" if dic_key == "password" or dic_key == "token" else 0
if dic_key == "password" or dic_key == "token":
dic_value = "** hidden **"
log(f" {dic_key}: {dic_value}")
else:
value = "** hidden **" if key == "password" or key == "token" else 0
if key == "password" or key == "token":
value = "** hidden **"
log(f" {key}: {value}")

def get(self, path=None):
Expand All @@ -170,29 +183,15 @@ def get(self, path=None):
return self.config

def set(self, path, value):
# file_name = f'{self.path_file}'
# with open(file_name) as f:
# self.config = yaml.safe_load(f)
# self.config[path] = value
# with open(file_name, 'w') as f:
# yaml.safe_dump(self.config, f, default_flow_style=False)
# return self.config

# with open(f'{self.path_file}', 'r+') as f:
# text = f.read()
# text = re.sub(f'^[[:space:]]*{path}:(.*)', f'${value}', text)
# f.seek(0)
# f.write(text)
# f.truncate()
yaml = YAML()
file_name = f'{self.path_file}'
with open(file_name) as f:
current_config = yaml.safe_load(f)

code = yaml.load(current_config)
code[path] = value

yaml.dump(code, self.config)
log(f" => Switch {path} to {value}")
with open(f'{self.path_file}', 'r+') as f:
text = f.read()

text = re.sub(fr'(?<={path}: ).*', str(value).lower(), text)
f.seek(0)
f.write(text)
f.truncate()
self.config = text

def mqtt_config(self):
if "mqtt" in self.config:
Expand Down
28 changes: 19 additions & 9 deletions app/models/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,25 @@ def error(message, detail=None):
logSep()


def warning(message, detail=None):
Log().msg("================================== WARNING ======================================")
if type(message) is list:
for msg in message:
Log().msg(msg)
else:
Log().msg(message)


def critical(message, detail=None):
Log().msg("================================== CRITICAL ======================================")
if type(message) is list:
for msg in message:
Log().msg(msg)
else:
Log().msg(message)
logSep()
sys.exit()

def logg(message, tag=None):
logSep()
if tag is not None:
Expand All @@ -64,13 +83,4 @@ def logWarn():
log("**********************************************************************************")


def critical(message, detail=None):
Log().msg("================================== CRITICAL ======================================")
if type(message) is list:
for msg in message:
Log().msg(msg)
else:
Log().msg(message)
logSep()
sys.exit()

2 changes: 1 addition & 1 deletion app/models/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def connect(self):
self.client.username_pw_set(self.username, self.password)
self.client.connect(self.hostname, self.port)
self.client.loop_start()
log(" => Connected to MQTT Broker!")
log(" => Connection success")
except Exception as e:
critical(["MQTT Connexion failed", e])

Expand Down
141 changes: 141 additions & 0 deletions app/models/myelectricaldata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import json

from models.config import get_version
from models.query import Query
from models.log import log, debug


class MyElectricalData:

def __init__(self, cache, url, usage_point_id, config):
self.cache = cache
self.url = url
self.headers = {
'Content-Type': 'application/json',
'Authorization': config['token'],
'call-service': "myelectricaldata",
'version': get_version()
}

self.usage_point_id = usage_point_id
self.config = config
self.contrat = {}

def contract(self):
name = "contracts"
endpoint = f"{name}/{self.usage_point_id}"
if "cache" in self.config and self.config["cache"]:
endpoint += "/cache"
target = f"{self.url}/{endpoint}"
current_cache = self.cache.get_contract(usage_point_id=self.usage_point_id)
if current_cache is None:
# No cache
log(f" => No cache : {target}")
self.contrat = Query(endpoint=target, headers=self.headers).get(headers=self.headers)
self.cache.insert_contract(usage_point_id=self.usage_point_id, contract=self.contract(), count=0)
else:
if "refresh_contract" in self.config and self.config["refresh_contract"] == True:
log(f" => Refresh Cache : {target}")
self.contrat = Query(endpoint=target, headers=self.headers).get(headers=self.headers)
self.cache.insert_contract(usage_point_id=self.usage_point_id, contract=self.contract(), count=0)
else:
log(f" => Query Cache")
contract = json.loads(query_result[1])
query = f"INSERT OR REPLACE INTO contracts VALUES (?,?,?)"
cur.execute(query, [pdl, json.dumps(contract), 0])
con.commit()

# def queryApi(url, headers, data, count=0):
# contract = f.apiRequest(cur, con, pdl, type="POST", url=f"{url}", headers=headers, data=json.dumps(data))
# if not "error_code" in contract:
# query = f"INSERT OR REPLACE INTO contracts VALUES (?,?,?)"
# cur.execute(query, [pdl, json.dumps(contract), count])
# con.commit()
# return contract
#
# url = main.url
#
# ha_discovery = {pdl: {}}
#
#

# if query_result is None:
# f.log(" => Query API")
# contract = queryApi(url, headers, data)
# else:
# if "refresh_contract" in pdl_config and pdl_config["refresh_contract"] == True:
# f.log(" => Query API (Refresh Cache)")
# contract = queryApi(url, headers, data, 0)
# else:
# f.log(f" => Query Cache")
# contract = json.loads(query_result[1])
# query = f"INSERT OR REPLACE INTO contracts VALUES (?,?,?)"
# cur.execute(query, [pdl, json.dumps(contract), 0])
# con.commit()
#
# if "error_code" in contract:
# f.log(contract["description"])
# ha_discovery = {"error_code": True, "detail": {"message": contract["description"]}}
# f.publish(client, f"{pdl}/contract/error", str(1))
# for key, value in contract.items():
# f.publish(client, f"{pdl}/contract/errorMsg/{key}", str(value))
# else:
# f.publish(client, f"{pdl}/contract/error", str(0))
# if "customer" in contract:
# customer = contract["customer"]
# f.publish(client, f"{pdl}/customer_id", str(customer["customer_id"]))
# for usage_points in customer["usage_points"]:
# for usage_point_key, usage_point_data in usage_points["usage_point"].items():
# f.publish(client, f"{pdl}/contract/{usage_point_key}", str(usage_point_data))
#
# for contracts_key, contracts_data in usage_points["contracts"].items():
# f.publish(client, f"{pdl}/contract/{contracts_key}", str(contracts_data))
#
# if contracts_key == "last_distribution_tariff_change_date":
# f.publish(client, f"{pdl}/last_distribution_tariff_change_date", str(contracts_data))
# ha_discovery[pdl]["last_distribution_tariff_change_date"] = str(contracts_data)
#
# if contracts_key == "last_activation_date":
# f.publish(client, f"{pdl}/last_activation_date", str(contracts_data))
# ha_discovery[pdl]["last_activation_date"] = str(contracts_data)
#
# if contracts_key == "subscribed_power":
# f.publish(client, f"{pdl}/subscribed_power", str(contracts_data.split()[0]))
# ha_discovery[pdl]["subscribed_power"] = str(contracts_data.split()[0])
# config_query = f"INSERT OR REPLACE INTO config VALUES (?, ?)"
# cur.execute(config_query, [f"{pdl}_subscribed_power", f"{str(contracts_data)}"])
# con.commit()
#
# offpeak_hours = []
# if pdl_config["offpeak_hours"] != None:
# offpeak_hours = pdl_config["offpeak_hours"].split(";")
# else:
# if contracts_key == "offpeak_hours":
# offpeak_hours = contracts_data[
# contracts_data.find("(") + 1: contracts_data.find(")")
# ].split(";")
#
# if offpeak_hours != [] and offpeak_hours != [""]:
# ha_discovery[pdl]["offpeak_hours"] = offpeak_hours
# index = 0
# for oh in offpeak_hours:
# f.publish(client, f"{pdl}/offpeak_hours/{index}/start", str(oh.split("-")[0]))
# f.publish(client, f"{pdl}/offpeak_hours/{index}/stop", str(oh.split("-")[1]))
# index += 1
# f.publish(client, f"{pdl}/offpeak_hours", str(offpeak_hours))
# offpeak_hours_store = ""
# offpeak_hours_len = len(offpeak_hours)
# i = 1
# for hours in offpeak_hours:
# offpeak_hours_store += f"{hours}"
# if i < offpeak_hours_len:
# offpeak_hours_store += ";"
# i += 1
#
# # config_query = f"INSERT OR REPLACE INTO config VALUES (?, ?)"
# # cur.execute(config_query, [f"{pdl}_offpeak_hours", f"HC ({str(offpeak_hours_store)})"])
# # con.commit()
#
# else:
# ha_discovery = {"error_code": True, "detail": {"message": contract}}
# return ha_discovery
Loading

0 comments on commit 316c217

Please sign in to comment.