Skip to content

Instantly share code, notes, and snippets.

@melix

melix/conso.py Secret

Created November 26, 2022 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melix/90dce1c44524a368f9186981ec16b475 to your computer and use it in GitHub Desktop.
Save melix/90dce1c44524a368f9186981ec16b475 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
from PIL import Image,ImageDraw,ImageFont
import time
import sys
import os
import json
import time
import requests
import collections.abc
from flask import Flask, Response
import logging
from datetime import datetime
import RPi.GPIO as GPIO
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'epaper/pic')
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'epaper/lib')
if os.path.exists(libdir):
sys.path.append(libdir)
from waveshare_epd import epd4in2bc
logging.basicConfig(level=logging.DEBUG)
EMAIL = "email-compte-total.com"
PASSWORD = "votre mot de passe en clair, beurk!"
MOBILE_ID = "06F7E82D-42E2-419E-8365-62000435A59C" # générez un UUID à la main !
HEADERS = {
"User-Agent": "Atome/1.5.3 (com.directenergie.atome; build:0.0.1; iOS 12.4.0) Alamofire/4.8.2",
"Content-Type": "application/json",
'Accept-Language': 'fr-FR;q=1.0, en-US;q=0.9',
'Accept': '*/*'
}
BASE_URL = "https://esoftlink.esoftthings.com/api"
CONNECTED = False
ID = None
REFERENCE = None
s = requests.session()
font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)
font18 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 18)
MAX_PROD = 6000
MAX_CONSO = 12000
epd = epd4in2bc.EPD()
logging.info("init and Clear")
epd.init()
def power_prod():
return call_server("https://monitoringapi.solaredge.com/site/votre_id_de_site/overview?api_key=votre_cle_api_solaredge")
def live():
result, status = get_live()
return Response(json.dumps(result), mimetype='application/json', status=status)
def consumption():
result, status = get_consumption()
return Response(json.dumps(result), mimetype='application/json', status=status)
def call_server(url):
global CONNECTED
if not CONNECTED and not login():
return 'Error', 500
request = s.get(url)
if request.status_code == 401 or request.status_code == 403:
CONNECTED = False
return call_server(url) # Reconnect
if request.status_code != 200:
return 'Error', request.status_code
return json.loads(request.content), 200
def get_live():
return call_server(f"{BASE_URL}/subscription/{ID}/{REFERENCE}/measure/live.json?mobileId={MOBILE_ID}")
def get_consumption():
return call_server(f"{BASE_URL}/subscription/{ID}/{REFERENCE}/consumption.json?period=sod")
def login():
body = {
"email": EMAIL,
"plainPassword": PASSWORD,
"mobileInformation": json.dumps({
"version": "1.5.3",
"phoneOS": "iOs",
"phoneOSVersion": "12.4",
"phoneBrand": "Android",
"phoneModel": "iPhone 7",
"mobileId": MOBILE_ID,
}) # Can be empty..., maybe good to keep all intact
}
request = s.post(f"{BASE_URL}/user/login.json", json=body, headers=HEADERS)
if request.status_code != 200:
print("Login failed")
return False
result = json.loads(request.content)
global ID, REFERENCE, CONNECTED
CONNECTED = True
ID = result["id"]
REFERENCE = result["subscriptions"][0]["reference"]
return True
def instant_loop():
prod_is_known = True
conso_is_known = True
current_prod = 0
live_conso = 0
try:
current_prod = round(power_prod()[0]['overview']['currentPower']['power'])
except:
prod_is_known = False
try:
live_info = get_live()
if (isinstance(live_info, collections.abc.Sequence)):
live_data = get_live()[0]
connected = live_data['isConnected']
if (connected == False):
prod_is_known = False
else:
live_conso = live_data['last']
except:
prod_is_known = False
if (prod_is_known and conso_is_known):
message = "Tout va bien ! Peut-être lancer une machine ?"
if (live_conso == 0):
if (current_prod<1000):
message = "Tout va bien"
if (live_conso>0):
message = "Production insuffisante !"
if (live_conso>2500):
message = "Attention: conso très importante !"
if (live_conso>5000):
message = "Attention: conso excessive !"
else:
message = "Des données n'ont pas pu être récupérées"
wconso = live_conso/MAX_CONSO * 300
wprod = current_prod/MAX_CONSO * 300
image = Image.new('1', (400, 300), 255)
HRYimage = Image.new('1', (400, 300), 255)
drawblack = ImageDraw.Draw(image)
drawry = ImageDraw.Draw(HRYimage)
now = datetime.now()
current_time = now.strftime("%H:%M")
drawblack.text((10, 0), f"Bilan électrique à {current_time}", font = font24, fill = 0)
drawblack.text((10, 25), 'Production PV', font = font18, fill = 0)
if prod_is_known:
drawry.rectangle((10, 25+18+2, 11+wprod, 25+18+2+30), fill = 0)
drawblack.text((11+wprod+18, 25+18+2), f"{current_prod}W", font = font18, fill = 0)
else:
drawblack.text((10+18, 25+18+2), "Production inconnue", font = font18, fill = 0)
drawblack.text((10, 90), 'Besoin externe', font = font18, fill = 0)
if (conso_is_known):
drawry.rectangle((10, 90+18+2, 11+wconso, 90+18+2+30), fill = 0)
drawblack.text((11+wconso+18, 90+18+2), f"{live_conso}W", font = font18, fill = 0)
else:
drawblack.text((11+18, 90+18+2), "Consommation inconnue", font = font18, fill = 0)
drawblack.text((20, 155), message, font = font18, fill = 0)
#image.show()
epd.Clear()
epd.display(epd.getbuffer(image), epd.getbuffer(HRYimage))
if (prod_is_known and conso_is_known):
return 300
else:
return 60
while True:
delay = instant_loop()
CONNECTED=False
time.sleep(delay)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment