Skip to content

Commit

Permalink
feat(api): upgrade to API v2
Browse files Browse the repository at this point in the history
  • Loading branch information
rokam committed May 29, 2024
1 parent 9fc0f25 commit 7f4cabf
Show file tree
Hide file tree
Showing 13 changed files with 374 additions and 397 deletions.
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
dateutil
requests
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
long_description = fh.read()

requires = [
"dateutil",
"requests",
]

Expand Down
24 changes: 10 additions & 14 deletions sunweg/api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""API Helper."""

import json
from datetime import datetime
from dateutil import parser
from typing import Any

from requests import Response, session
Expand Down Expand Up @@ -118,7 +118,7 @@ def authenticate(self) -> bool:
:rtype: bool
"""
user_data = json.dumps(
{"usuario": self._username, "senha": self._password},
{"usuario": self._username, "senha": self._password, "rememberMe": True},
default=lambda o: o.__dict__,
)

Expand All @@ -131,8 +131,8 @@ def authenticate(self) -> bool:
def _headers(self):
"""Retrieve headers with authentication token."""
if self._token is None:
return {}
return {"X-Auth-Token-Update": self._token}
return {"Content-Type": "application/json"}
return {"Content-Type": "application/json", "X-Auth-Token-Update": self._token}

def listPlants(self, retry=True) -> list[Plant]:
"""
Expand All @@ -148,7 +148,7 @@ def listPlants(self, retry=True) -> list[Plant]:
try:
result = self._get(SUNWEG_PLANT_LIST_PATH)
ret_list = []
for plant in result["usinas"]:
for plant in result["conectadas"]:
if (plant := self.plant(plant["id"])) is not None:
ret_list.append(plant)
return ret_list
Expand All @@ -173,25 +173,21 @@ def plant(self, id: int, retry=True) -> Plant | None:
result = self._get(SUNWEG_PLANT_DETAIL_PATH + str(id))

(today_energy, today_energy_metric) = separate_value_metric(
result["energiaGeradaHoje"], "kWh"
result["energiadia"], "kWh"
)
total_power = separate_value_metric(result["AcumuladoPotencia"])[0]
plant = Plant(
id=id,
name=result["usinas"]["nome"],
total_power=total_power,
kwh_per_kwp=float(str(result["KWHporkWp"]).replace(",", "."))
if result["KWHporkWp"] != ""
else float(0),
performance_rate=result["taxaPerformance"],
kwh_per_kwp=float(0),
performance_rate=float(0),
saving=result["economia"],
today_energy=today_energy,
today_energy_metric=today_energy_metric,
total_energy=float(result["energiaacumuladanumber"]),
total_carbon_saving=result["reduz_carbono_total_number"],
last_update=datetime.strptime(
result["ultimaAtualizacao"], "%Y-%m-%d %H:%M:%S"
)
last_update=parser.parse(result["ultimaAtualizacao"])
if result["ultimaAtualizacao"] is not None
else None,
)
Expand Down Expand Up @@ -351,7 +347,7 @@ def month_stats_production_by_id(
)
return [
ProductionStats(
datetime.strptime(item["tempoatual"], "%Y-%m-%d").date(),
parser.parse(item["tempoatual"]).date(),
float(item["energiapordia"]),
float(item["prognostico"]),
)
Expand Down
15 changes: 8 additions & 7 deletions sunweg/const.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
"""Sunweg API constants."""
SUNWEG_URL = "https://api.sun.weg.net/"

SUNWEG_URL = "https://api.sun.weg.net/v2/"
"""SunWEG API URL"""
SUNWEG_LOGIN_PATH = "login/autenticacao"
"""SunWEG API login path"""
SUNWEG_PLANT_LIST_PATH = (
"usinas/getpaineloperacao?procurar="
+ "&integrador=&franqueado=&portal=&alarme=&"
+ "planos=%5B%220%22,%221%22,%222%22,%223%22,%224%22%5D&"
+ "status=%5B%221%22,%222%22,%223%22,%224%22,%225%22%5D"
"getpaineloperacao?procurar=&integrador="
+ "&franqueado=&manutencao=&portal=&alarme=&"
+ "planos=%5B0,1,2,3,4%5D&status=%5B1,2,3,4,5%5D&"
+ "limite=100&situacao=&paginaAtual=1"
)
"""SunWEG API list plants path"""
SUNWEG_PLANT_DETAIL_PATH = "usinas/view?idusina="
SUNWEG_PLANT_DETAIL_PATH = "viewresumov2?agrupado=false&id="
"""SunWEG API plant details path"""
SUNWEG_INVERTER_DETAIL_PATH = "inversores/view?id="
"""SunWEG API inverter details path"""
SUNWEG_MONTH_STATS_PATH = "usinas/getgraficomes?"
SUNWEG_MONTH_STATS_PATH = "usinas/graficomes?"
"""SunWEG API month history path"""
13 changes: 13 additions & 0 deletions sunweg/plant.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Sunweg API plant."""

from datetime import datetime
import warnings

from .device import Inverter

Expand Down Expand Up @@ -94,21 +95,33 @@ def total_power(self) -> float:
@property
def kwh_per_kwp(self) -> float:
"""
Deprecated as API v2 doesn't return it anymore.
Get plant kWh/kWp.
:return: plant kWh/kWp
:rtype: float
"""
warnings.warn(
"The 'kwh_per_kwp' property is deprecated and will return 0.",
DeprecationWarning,
stacklevel=2,
)
return self._kwh_per_kwp

@property
def performance_rate(self) -> float:
"""
Deprecated as API v2 doesn't return it anymore.
Get plant performance rate.
:return: plant performance rate
:rtype: float
"""
warnings.warn(
"The 'performance_rate' property is deprecated and will return 0.",
DeprecationWarning,
stacklevel=2,
)
return self._performance_rate

@property
Expand Down
2 changes: 1 addition & 1 deletion tests/responses/list_plant_success_1_response.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"success":true,"usinas":[{"id":16925}]}
{"success":true,"conectadas":[{"id":16925}]}
2 changes: 1 addition & 1 deletion tests/responses/list_plant_success_2_response.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"success":true,"usinas":[{"id":16925},{"id":16926}]}
{"success":true,"conectadas":[{"id":16925},{"id":16926}]}
2 changes: 1 addition & 1 deletion tests/responses/list_plant_success_none_response.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"success":true,"usinas":[]}
{"success":true,"conectadas":[]}
Loading

0 comments on commit 7f4cabf

Please sign in to comment.