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."""
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

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):
@ -14,7 +14,7 @@ class MultipleDevicesException(Exception):
class UnsupportedMethodException(Exception):
"""Raised when an unsupported method is used."""
"""Raised when an unsupported HTTP method is used."""
pass
@ -25,12 +25,6 @@ class InvalidPlanException(Exception):
pass
class TariffException(Exception):
"""Raised when the tariff is not valid."""
pass
class ReadingRequestFailedException(Exception):
"""Raised when the reading request fails."""
@ -41,3 +35,9 @@ class ReadingResponseInvalidException(Exception):
"""Raised when the reading response is invalid."""
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
from datetime import datetime, timedelta
from time import sleep
from typing import Dict, List, Optional, TypedDict
from typing import Optional
import requests
from .constants import HTTP_200_OK, TRIPHASIC
from .constants import API_VERSION_1, API_VERSION_2, TRIPHASIC
from .exceptions import (
InvalidPlanException,
InvalidPowerFactorException,
@ -35,53 +35,11 @@ from .exceptions import (
TariffException,
UnsupportedMethodException,
)
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]
from .models import ActiveEnergy
class UTEClient:
"""
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
"""
"""UTE (Administración Nacional de Usinas y Trasmisiones Eléctricas) API Wrapper."""
def __init__(
self,
@ -198,10 +156,6 @@ class UTEClient:
"""
Login to UTE.
Args:
email (str): User email for authentication
phone_number (str): User phone number for authentication
Returns:
str: Authorization token
"""
@ -215,12 +169,12 @@ class UTEClient:
self.authorization = response.text
return self.authorization
def get_devices_list(self) -> List[dict]:
def get_devices_list(self) -> list[dict]:
"""
Get UTE devices list.
Returns:
List[dict]: List of devices
list[dict]: List of devices
"""
if not self.authorization:
self._login()
@ -254,7 +208,7 @@ class UTEClient:
peak_by_id_url = f"{API_VERSION_1}/accounts/{self.device_id}/peak"
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.
@ -341,12 +295,12 @@ class UTEClient:
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.
Args:
readings (List[dict]): List of readings
readings (list[dict]): List of readings
Returns:
float: Power in watts
@ -394,7 +348,7 @@ class UTEClient:
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")
response = self._make_request("GET", reading_url).json()

View File

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