128 lines
4.6 KiB
Python
128 lines
4.6 KiB
Python
from ast import While
|
|
from dataclasses import dataclass
|
|
from email import header
|
|
import mysql.connector
|
|
from datetime import datetime
|
|
from datetime import timedelta
|
|
|
|
import requests
|
|
import json
|
|
import hashlib
|
|
import random
|
|
import time
|
|
import os
|
|
|
|
print ("Starting program")
|
|
|
|
USERNAME = "hyomiles-username"
|
|
USERPASSWORD = "hoymiles-password"
|
|
API_FREQUENCY_CHECK = 900
|
|
mydb = mysql.connector.connect(
|
|
host = "sql-server-host",
|
|
user = "solar",
|
|
password = "password",
|
|
database = "solar"
|
|
)
|
|
|
|
print ("Checking every " + str(API_FREQUENCY_CHECK) + " seconds for new data from Hoymiles")
|
|
print ("Checking now...")
|
|
|
|
class Energy:
|
|
def __init__(self, username, password):
|
|
self.username = username
|
|
self.password = hashlib.md5(bytes(password,"utf-8")).hexdigest()
|
|
self.today = ""
|
|
self.this_month = ""
|
|
self.this_year = ""
|
|
self.lifetime_energy = ""
|
|
self.current_power = ""
|
|
self.last_update = ""
|
|
self.cookie = self.authentication_cookie()
|
|
self.update()
|
|
|
|
def authentication_cookie(self):
|
|
response_auth = json.loads(requests.post("https://global.hoymiles.com/platform/api/gateway/iam/auth_login", data={'user_name': self.username, 'password': self.password}).text)
|
|
token = response_auth["data"]["token"]
|
|
headers = {"hm_token": token + "; Path=/; Expires=Sat, 18 Mar 2023 19:00:41 GMT;"}
|
|
self.cookie = headers
|
|
print ("Authentication token received!")
|
|
return headers
|
|
|
|
def get_sid(self):
|
|
|
|
response = json.loads(requests.post("https://global.hoymiles.com/platform/api/gateway/pvm/station_select_by_page", cookies=self.cookie).text)
|
|
|
|
if response["message"] == "success":
|
|
site_list = response["data"]["list"]
|
|
site_dict = site_list[0]
|
|
site_id = str(site_dict["id"])
|
|
return site_id
|
|
elif response["message"] == "token verify error.":
|
|
print ("Authentication token not valid. Requesting new token...")
|
|
self.cookie = self.authentication_cookie()
|
|
return False
|
|
else:
|
|
print ("No valid return from API")
|
|
return False
|
|
|
|
def update(self):
|
|
sid = self.get_sid()
|
|
if sid == False:
|
|
return False
|
|
data = { "sid": sid }
|
|
response = json.loads(requests.post("https://global.hoymiles.com/platform/api/gateway/pvm-data/data_count_station_real_data", cookies=self.cookie, json=data).text)
|
|
if response["message"] == "success":
|
|
self.today = str(response["data"]["today_eq"])
|
|
self.this_month = str(response["data"]["month_eq"])
|
|
self.this_year = str(response["data"]["year_eq"])
|
|
self.lifetime_energy = str(response["data"]["total_eq"])
|
|
self.current_power = str(response["data"]["real_power"])
|
|
self.last_update = str(response["data"]["last_data_time"])
|
|
elif response["message"] == "token verify error.":
|
|
print ("Authentication token not valid. Requesting new token...")
|
|
self.cookie = self.authentication_cookie()
|
|
return False
|
|
else:
|
|
print ("No valid return from API")
|
|
return False
|
|
|
|
def insertDB (today, month, year, lifetime, current, lastUpdate):
|
|
mycursor = mydb.cursor()
|
|
sql = "INSERT INTO solardata (today, month, year, lifetime, current, last_update) VALUES (%s, %s, %s, %s, %s, %s)"
|
|
val = (today, month, year, lifetime, current, lastUpdate)
|
|
mycursor.execute(sql, val)
|
|
mydb.commit()
|
|
print (mycursor.rowcount, " record inserted.")
|
|
|
|
hoymiles = Energy(USERNAME,USERPASSWORD)
|
|
|
|
lastUpdate = ""
|
|
energytoday = 0
|
|
|
|
while 1<2:
|
|
|
|
current_time = datetime.now().strftime("%D %H:%M:%S")
|
|
|
|
if lastUpdate != hoymiles.last_update or energytoday != hoymiles.today:
|
|
print ("Update at: ", current_time)
|
|
insertDB(hoymiles.today, hoymiles.this_month, hoymiles.this_year, hoymiles.lifetime_energy, hoymiles.current_power, hoymiles.last_update)
|
|
|
|
lastUpdate = hoymiles.last_update
|
|
energytoday = hoymiles.today
|
|
else:
|
|
print ("No new information at: ", current_time)
|
|
|
|
|
|
thisUpdateTime = datetime.now()
|
|
followingUpdateTime = datetime.now() + timedelta(seconds=API_FREQUENCY_CHECK)
|
|
|
|
if thisUpdateTime.day != followingUpdateTime.day:
|
|
print ("Following update will be after midnight. Setting day-total to 0.")
|
|
#publish(client, "hoymiles/energy_today", "0")
|
|
|
|
time.sleep(API_FREQUENCY_CHECK)
|
|
|
|
result = hoymiles.update()
|
|
|
|
if result == False:
|
|
print ("Error happened. Data not updated!") |