Skip to content

Commit

Permalink
fix: receive none when expecting value and metric
Browse files Browse the repository at this point in the history
  • Loading branch information
rokam committed Dec 20, 2023
1 parent 27ab49c commit b30d21e
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 32 deletions.
69 changes: 38 additions & 31 deletions sunweg/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,27 @@ def convert_situation_status(situation: int) -> Status:
return Status.WARN


def separate_value_metric(value_with_metric: str | None, default_metric: str = "") -> tuple[float, str]:
"""
Separate the value from the metric.
:param value_with_metric: value with metric separated by space
:type value_with_metric: str | None
:param default_metric: metric that should be returned if `value_with_metric` is None
:type default_metric: str
:return: tuple with value and metric
:rtype: tuple[float, str]
"""
if value_with_metric is None or len(value_with_metric) == 0:
return (0.0, default_metric)
split = value_with_metric.split(" ")
return (
float(split[0].replace(",", ".")),
default_metric if len(split) < 2 else split[1]
)



class APIHelper():
"""Class to call sunweg.net api."""

Expand Down Expand Up @@ -146,23 +167,19 @@ def plant(self, id: int, retry=True) -> Plant | None:
try:
result = self._get(SUNWEG_PLANT_DETAIL_PATH + str(id))

(today_energy, today_energy_metric) = separate_value_metric(result["energiaGeradaHoje"], "kWh")
total_power = separate_value_metric(result["AcumuladoPotencia"])[0]
plant = Plant(
id=id,
name=result["usinas"]["nome"],
total_power=float(
str(result["AcumuladoPotencia"])
.replace(" kW", "")
.replace(",", ".")
),
total_power=total_power,
kwh_per_kwp=float(str(result["KWHporkWp"]).replace(",", "."))
if result["KWHporkWp"] != ""
else float(0),
performance_rate=result["taxaPerformance"],
saving=result["economia"],
today_energy=float(
str(result["energiaGeradaHoje"]).split(" ")[0].replace(",", ".")
),
today_energy_metric=str(result["energiaGeradaHoje"]).split(" ")[1],
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(
Expand Down Expand Up @@ -202,22 +219,21 @@ def inverter(self, id: int, retry=True) -> Inverter | None:
"""
try:
result = self._get(SUNWEG_INVERTER_DETAIL_PATH + str(id))
(total_energy, total_energy_metric) = separate_value_metric(result["energiaacumulada"], "kWh")
(today_energy, today_energy_metric) = separate_value_metric(result["energiadodia"], "kWh")
(power, power_metric) = separate_value_metric(result["potenciaativa"], "kW")
inverter = Inverter(
id=id,
name=result["inversor"]["nome"],
sn=result["inversor"]["esn"],
total_energy=float(
result["energiaacumulada"].split(" ")[0].replace(",", ".")
),
total_energy_metric=result["energiaacumulada"].split(" ")[1],
today_energy=float(
result["energiadodia"].split(" ")[0].replace(",", ".")
),
today_energy_metric=result["energiadodia"].split(" ")[1],
total_energy=total_energy,
total_energy_metric=total_energy_metric,
today_energy=today_energy,
today_energy_metric=today_energy_metric,
power_factor=float(result["fatorpotencia"].replace(",", ".")),
frequency=float(result["frequencia"].replace(",", ".")),
power=float(result["potenciaativa"].split(" ")[0].replace(",", ".")),
power_metric=result["potenciaativa"].split(" ")[1],
power=power,
power_metric=power_metric,
status=Status(int(result["statusInversor"])),
temperature=result["temperatura"],
)
Expand All @@ -242,20 +258,11 @@ def complete_inverter(self, inverter: Inverter, retry=True) -> None:
"""
try:
result = self._get(SUNWEG_INVERTER_DETAIL_PATH + str(inverter.id))
inverter.total_energy = float(
result["energiaacumulada"].split(" ")[0].replace(",", ".")
)
inverter.total_energy_metric = result["energiaacumulada"].split(" ")[1]
inverter.today_energy = float(
result["energiadodia"].split(" ")[0].replace(",", ".")
)
inverter.today_energy_metric = result["energiadodia"].split(" ")[1]
(inverter.total_energy, inverter.total_energy_metric) = separate_value_metric(result["energiaacumulada"], "kWh")
(inverter.today_energy, inverter.today_energy_metric) = separate_value_metric(result["energiadodia"], "kWh")
(inverter.power, inverter.power_metric) = separate_value_metric(result["potenciaativa"], "kW")
inverter.power_factor = float(result["fatorpotencia"].replace(",", "."))
inverter.frequency = float(result["frequencia"].replace(",", "."))
inverter.power = float(
result["potenciaativa"].split(" ")[0].replace(",", ".")
)
inverter.power_metric = result["potenciaativa"].split(" ")[1]

self._populate_MPPT(result=result, inverter=inverter)
except LoginError:
Expand Down
43 changes: 42 additions & 1 deletion tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from requests import Response

from sunweg.api import APIHelper, convert_situation_status, SunWegApiError
from sunweg.api import APIHelper, convert_situation_status, SunWegApiError, separate_value_metric
from sunweg.device import Inverter, String
from sunweg.util import Status

Expand All @@ -34,6 +34,7 @@ def setUp(self) -> None:
response._content = "".join(f.readlines()).encode()
self.responses[filename] = response


def test_convert_situation_status(self) -> None:
"""Test the conversion from situation to status."""
status_ok: Status = convert_situation_status(1)
Expand All @@ -44,6 +45,46 @@ def test_convert_situation_status(self) -> None:
assert status_err == Status.ERROR
assert status_wrn == Status.WARN


def test_separate_value_metric_comma(self) -> None:
"""Test the separation from value and metric of string with comma."""
(value,metric) = separate_value_metric("0,0")
assert value == 0
assert metric == ""
(value,metric) = separate_value_metric("1,0", "W")
assert value == 1.0
assert metric == "W"
(value,metric) = separate_value_metric("0,2 kW", "W")
assert value == 0.2
assert metric == "kW"


def test_separate_value_metric_dot(self) -> None:
"""Test the separation from value and metric of string with dot."""
(value,metric) = separate_value_metric("0.0")
assert value == 0
assert metric == ""
(value,metric) = separate_value_metric("1.0", "W")
assert value == 1.0
assert metric == "W"
(value,metric) = separate_value_metric("0.2 kW", "W")
assert value == 0.2
assert metric == "kW"


def test_separate_value_metric_none_int(self) -> None:
"""Test the separation from value and metric of string with dot."""
(value,metric) = separate_value_metric(None)
assert value == 0
assert metric == ""
(value,metric) = separate_value_metric("1", "W")
assert value == 1.0
assert metric == "W"
(value,metric) = separate_value_metric("2 kW", "W")
assert value == 2.0
assert metric == "kW"


def test_error500(self) -> None:
"""Test error 500."""
with patch(
Expand Down

0 comments on commit b30d21e

Please sign in to comment.