Refactored code to make it more readable

This commit is contained in:
Roger Gonzalez 2024-03-09 18:52:18 -03:00
parent e79b9fe213
commit 65b016664c
Signed by: rogs
GPG Key ID: C7ECE9C6C36EC2E6
5 changed files with 49 additions and 67 deletions

View File

@ -1,4 +1,6 @@
"""Constants used in the application.""" """Constants used in the application."""
HTTP_200_OK = 200 TRIPHASIC = 3
API_VERSION_1 = "https://rocme.ute.com.uy/api/v1"
API_VERSION_2 = "https://rocme.ute.com.uy/api/v2"
TRIPHASIC = 3 TRIPHASIC = 3

View File

@ -1,4 +1,4 @@
"""This module contains all the exceptions used in the project.""" """Custom exceptions for the UTE wrapper."""
class InvalidPowerFactorException(Exception): class InvalidPowerFactorException(Exception):
@ -14,7 +14,7 @@ class MultipleDevicesException(Exception):
class UnsupportedMethodException(Exception): class UnsupportedMethodException(Exception):
"""Raised when an unsupported method is used.""" """Raised when an unsupported HTTP method is used."""
pass pass
@ -25,12 +25,6 @@ class InvalidPlanException(Exception):
pass pass
class TariffException(Exception):
"""Raised when the tariff is not valid."""
pass
class ReadingRequestFailedException(Exception): class ReadingRequestFailedException(Exception):
"""Raised when the reading request fails.""" """Raised when the reading request fails."""
@ -41,3 +35,9 @@ class ReadingResponseInvalidException(Exception):
"""Raised when the reading response is invalid.""" """Raised when the reading response is invalid."""
pass pass
class TariffException(Exception):
"""Raised when the tariff is not valid."""
pass

26
src/ute_wrapper/models.py Normal file
View File

@ -0,0 +1,26 @@
"""Models for the UTE Wrapper."""
from typing import TypedDict
class EnergyEntry(TypedDict):
"""Energy entry dict."""
kwh: float
aproximated_cost_in_uyu: float
day_in_week: str
class TotalEntry(TypedDict, total=False):
"""Total entry dict."""
sum_in_kwh: float
aproximated_cost_in_uyu: float
daily_average_cost: float
class ActiveEnergy(TypedDict, total=False):
"""Active energy dict."""
total: TotalEntry
dates: dict[str, EnergyEntry]

View File

@ -21,11 +21,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
from time import sleep from time import sleep
from typing import Dict, List, Optional, TypedDict from typing import Optional
import requests import requests
from .constants import HTTP_200_OK, TRIPHASIC from .constants import API_VERSION_1, API_VERSION_2, TRIPHASIC
from .exceptions import ( from .exceptions import (
InvalidPlanException, InvalidPlanException,
InvalidPowerFactorException, InvalidPowerFactorException,
@ -35,53 +35,11 @@ from .exceptions import (
TariffException, TariffException,
UnsupportedMethodException, UnsupportedMethodException,
) )
from .models import ActiveEnergy
API_VERSION_1 = "https://rocme.ute.com.uy/api/v1"
API_VERSION_2 = "https://rocme.ute.com.uy/api/v2"
class EnergyEntry(TypedDict):
"""Energy entry dict."""
kwh: float
aproximated_cost_in_uyu: float
day_in_week: str
class TotalEntry(TypedDict, total=False):
"""Total entry dict."""
sum_in_kwh: float
aproximated_cost_in_uyu: float
daily_average_cost: float
class ActiveEnergy(TypedDict, total=False):
"""Active energy dict."""
total: TotalEntry
dates: Dict[str, EnergyEntry]
class UTEClient: class UTEClient:
""" """UTE (Administración Nacional de Usinas y Trasmisiones Eléctricas) API Wrapper."""
UTE (Administración Nacional de Usinas y Trasmisiones Eléctricas) API Wrapper.
Args:
email (str): User email for authentication
phone_number (str): User phone number for authentication
device_id (str): UTE Device id
average_cost_per_kwh (float): Average cost per kwh
power_factor (float): Power factor
Raises:
InvalidPowerFactorException: If the power factor is not between 0 and 1
MultipleDevicesException: If there are multiple devices associated with the account
UnsupportedMethodException: If an unsupported method is used
InvalidPlanException: If the plan is not valid
ReadingRequestException: If the reading request is not valid
TariffException: If the tariff is not valid
"""
def __init__( def __init__(
self, self,
@ -198,10 +156,6 @@ class UTEClient:
""" """
Login to UTE. Login to UTE.
Args:
email (str): User email for authentication
phone_number (str): User phone number for authentication
Returns: Returns:
str: Authorization token str: Authorization token
""" """
@ -215,12 +169,12 @@ class UTEClient:
self.authorization = response.text self.authorization = response.text
return self.authorization return self.authorization
def get_devices_list(self) -> List[dict]: def get_devices_list(self) -> list[dict]:
""" """
Get UTE devices list. Get UTE devices list.
Returns: Returns:
List[dict]: List of devices list[dict]: List of devices
""" """
if not self.authorization: if not self.authorization:
self._login() self._login()
@ -254,7 +208,7 @@ class UTEClient:
peak_by_id_url = f"{API_VERSION_1}/accounts/{self.device_id}/peak" peak_by_id_url = f"{API_VERSION_1}/accounts/{self.device_id}/peak"
return self._make_request("GET", peak_by_id_url).json()["data"] return self._make_request("GET", peak_by_id_url).json()["data"]
def get_network_status(self) -> List[dict]: def get_network_status(self) -> list[dict]:
""" """
Get UTE network status from device id. Get UTE network status from device id.
@ -341,12 +295,12 @@ class UTEClient:
return active_energy return active_energy
def _convert_powers_to_power_in_watts(self, readings: List[dict]) -> float: def _convert_powers_to_power_in_watts(self, readings: list[dict]) -> float:
""" """
Convert powers to power in watts and determine the system type (monophasic, biphasic, triphasic) automatically. Convert powers to power in watts and determine the system type (monophasic, biphasic, triphasic) automatically.
Args: Args:
readings (List[dict]): List of readings readings (list[dict]): List of readings
Returns: Returns:
float: Power in watts float: Power in watts
@ -394,7 +348,7 @@ class UTEClient:
reading_request = self._make_request("POST", reading_request_url, data=data) reading_request = self._make_request("POST", reading_request_url, data=data)
if reading_request.status_code != HTTP_200_OK: if reading_request.status_code != requests.codes.ok:
raise ReadingRequestFailedException("Error getting reading request") raise ReadingRequestFailedException("Error getting reading request")
response = self._make_request("GET", reading_url).json() response = self._make_request("GET", reading_url).json()

View File

@ -6,7 +6,7 @@ import pytest
import requests import requests
from pytest_mock import MockerFixture from pytest_mock import MockerFixture
from src.ute_wrapper.ute import ( from src.ute_wrapper.exceptions import (
InvalidPlanException, InvalidPlanException,
InvalidPowerFactorException, InvalidPowerFactorException,
MultipleDevicesException, MultipleDevicesException,
@ -14,8 +14,8 @@ from src.ute_wrapper.ute import (
ReadingResponseInvalidException, ReadingResponseInvalidException,
TariffException, TariffException,
UnsupportedMethodException, UnsupportedMethodException,
UTEClient,
) )
from src.ute_wrapper.ute import UTEClient
@pytest.fixture @pytest.fixture