Skip to content

Commit

Permalink
fix the specific mesurements
Browse files Browse the repository at this point in the history
  • Loading branch information
antoinebou12 committed Sep 12, 2023
1 parent 74cfdad commit 569a97b
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 54 deletions.
6 changes: 0 additions & 6 deletions custom_components/renpho/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,6 @@ async def main():
renpho.get_info_sync()
users = await renpho.get_scale_users()
print("Fetched scale users:", users)
metric = await renpho.get_specific_metric_from_user_ID("weight", "bodyfat")
print("Fetched specific metric:", metric)
metric_for_user = await renpho.get_specific_metric_from_user_ID(
"weight", "bodyfat", "<user_id>"
)
print("Fetched specific metric for user:", metric_for_user)
get_device_info = await renpho.get_device_info()
print("Fetched device info:", get_device_info)
list_growth_record = await renpho.list_growth_record()
Expand Down
98 changes: 61 additions & 37 deletions custom_components/renpho/api_renpho.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import time
from base64 import b64encode
from threading import Timer
from typing import Dict, List, Optional, Union
from typing import Callable, Dict, List, Optional, Union

import aiohttp
import requests
Expand Down Expand Up @@ -251,37 +251,40 @@ async def get_specific_metric(
self, metric_type: str, metric: str, user_id: Optional[str] = None
) -> Optional[float]:
"""
Fetch a specific metric for a particular user ID based on the type specified (weight, growth goal, or growth metric).
Fetch a specific metric for a particular user ID based on the type specified.
Parameters:
metric_type (str): The type of metric to fetch ('weight', 'growth_goal', 'growth').
metric (str): The specific metric to fetch (e.g., "height", "growth_rate", "weight").
user_id (str, optional): The user ID for whom to fetch the metric. Defaults to None.
metric_type (str): The type of metric to fetch.
metric (str): The specific metric to fetch.
user_id (Optional[str]): The user ID for whom to fetch the metric. Defaults to None.
Returns:
float, None: The fetched metric value, or None if it couldn't be fetched.
Optional[float]: The fetched metric value, or None if it couldn't be fetched.
"""

METRIC_TYPE_FUNCTIONS = {
METRIC_TYPE_WEIGHT: ("get_measurements", "last_ary"),
METRIC_TYPE_GIRTH: ("list_girth", "girths"),
METRIC_TYPE_GROWTH_GOAL: ("list_growth_goal", "growth_goals"),
METRIC_TYPE_GROWTH_RECORD: ("list_growth_record", "growths"),
}

try:
if user_id:
self.set_user_id(user_id)

if metric_type == METRIC_TYPE_WEIGHT:
last_measurement = await self.get_measurements()
return last_measurement[0].get(metric, None) if last_measurement else None
func_name, last_measurement_key = METRIC_TYPE_FUNCTIONS.get(metric_type, (None, None))

elif metric_type == METRIC_TYPE_GROWTH_GOAL:
growth_goal_info = await self.list_growth_goal()
last_goal = growth_goal_info.get("growth_goals", [])[0] if growth_goal_info.get("growth_goals") else None
return last_goal.get(metric, None) if last_goal else None
if func_name is None:
_LOGGER.error(f"Invalid metric_type: {metric_type}. Must be one of {list(METRIC_TYPE_FUNCTIONS.keys())}.")
return None

elif metric_type == METRIC_TYPE_GROWTH:
growth_info = await self.list_growth()
last_measurement = growth_info.get("growths", [])[0] if growth_info.get("growths") else None
return last_measurement.get(metric, None) if last_measurement else None
# Dynamically call the function
func: Callable = getattr(self, func_name)
metric_info = await func()

else:
_LOGGER.error(f"Invalid metric_type: {metric_type}. Must be one of {METRIC_TYPE_WEIGHT}, {METRIC_TYPE_GROWTH_GOAL}, or {METRIC_TYPE_GROWTH}.")
return None
last_measurement = metric_info.get(last_measurement_key, [])[0] if metric_info.get(last_measurement_key) else None
return last_measurement.get(metric, None) if last_measurement else None

except Exception as e:
_LOGGER.error(f"An error occurred: {e}")
Expand Down Expand Up @@ -342,29 +345,50 @@ async def list_latest_model(self):
url = f"{LATEST_MODEL_URL}?user_id={self.user_id}&last_updated_at={week_ago_timestamp}&locale=en&app_id=Renpho&terminal_user_session_key={self.session_key}"
return await self._request("GET", url)

async def list_girth(self):
async def list_girth(self) -> Optional[dict]:
"""
Asynchronously list girth information.
Returns:
dict: The API response as a dictionary.
Optional[dict]: The API response as a dictionary, or None if the request fails.
"""
week_ago_timestamp = self.get_week_ago_timestamp()
url = f"{GIRTH_URL}?user_id={self.user_id}&last_updated_at={week_ago_timestamp}&locale=en&app_id=Renpho&terminal_user_session_key={self.session_key}"
return await self._request("GET", url)
try:
return await self._request("GET", url)
except Exception as e:
_LOGGER.error(f"An error occurred while listing girth: {e}")
return None

async def list_girth_goal(self):

async def get_specific_girth_metric(
self, metric: str, user_id: Optional[str] = None
) -> Optional[float]:
"""
Asynchronously list girth goal information.
Fetch a specific girth metric for a particular user ID based on the most recent girth information.
Parameters:
metric (str): The specific metric to fetch (e.g., "waist", "hip").
user_id (Optional[str]): The user ID for whom to fetch the metric. Defaults to None.
Returns:
dict: The API response as a dictionary.
Optional[float]: The fetched metric value, or None if it couldn't be fetched.
"""
week_ago_timestamp = self.get_week_ago_timestamp()
url = f"{GIRTH_GOAL_URL}?user_id={self.user_id}&last_updated_at={week_ago_timestamp}&locale=en&app_id=Renpho&terminal_user_session_key={self.session_key}"
return await self._request("GET", url)
try:
if user_id:
self.set_user_id(user_id)
girth_info = await self.list_girth()
last_measurement = (
girth_info.get("girths", [])[0]
if girth_info.get("girths")
else None
)
return last_measurement.get(metric, None) if last_measurement else None
except Exception as e:
_LOGGER.error(f"An error occurred: {e}")
return None

async def list_growth_goal(self):
async def list_girth_goal(self):
"""
Asynchronously list girth goal information.
Expand All @@ -375,26 +399,26 @@ async def list_growth_goal(self):
url = f"{GIRTH_GOAL_URL}?user_id={self.user_id}&last_updated_at={week_ago_timestamp}&locale=en&app_id=Renpho&terminal_user_session_key={self.session_key}"
return await self._request("GET", url)

async def get_specific_growth_goal_metric(
async def get_specific_girth_goal_metric(
self, metric: str, user_id: Optional[str] = None
) -> Optional[float]:
"""
Fetch a specific growth goal metric for a particular user ID from the most recent growth goal information.
Fetch a specific girth goal metric for a particular user ID from the most recent girth goal information.
Parameters:
metric (str): The specific metric to fetch (e.g., "height_goal", "growth_rate_goal").
metric (str): The specific metric to fetch .
user_id (str, optional): The user ID for whom to fetch the metric. Defaults to None.
Returns:
float, None: The fetched metric value, or None if it couldn't be fetched.
"""
try:
if user_id:
self.set_user_id(user_id) # Update the user_id if provided
growth_goal_info = await self.list_growth_goal()
self.set_user_id(user_id)
girth_goal_info = await self.list_girth_goal()
last_goal = (
growth_goal_info.get("growth_goals", [])[0]
if growth_goal_info.get("growth_goals")
girth_goal_info.get("girth_goals", [])[0]
if girth_goal_info.get("girth_goals")
else None
)
return last_goal.get(metric, None) if last_goal else None
Expand Down
2 changes: 1 addition & 1 deletion custom_components/renpho/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from homeassistant import config_entries, exceptions
from homeassistant.core import HomeAssistant

from .const import CONF_EMAIL, CONF_PASSWORD, CONF_PUBLIC_KEY, CONF_USER_ID, DOMAIN
from .const import CONF_EMAIL, CONF_PASSWORD, CONF_PUBLIC_KEY, CONF_REFRESH, CONF_USER_ID, DOMAIN
from .api_renpho import RenphoWeight

_LOGGER = logging.getLogger(__name__)
Expand Down
12 changes: 10 additions & 2 deletions custom_components/renpho/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,16 @@
]

METRIC_TYPE_WEIGHT: Final = "weight"
METRIC_TYPE_GROWTH_GOAL: Final = "growth_goal"
METRIC_TYPE_GROWTH: Final = "growth"
METRIC_TYPE_GROWTH_RECORD: Final = "growth_record"
METRIC_TYPE_GIRTH: Final = "girth"
METRIC_TYPE_GIRTH_GOAL: Final = "girth_goal"

METRIC_TYPE = [
METRIC_TYPE_WEIGHT,
METRIC_TYPE_GROWTH_RECORD,
METRIC_TYPE_GIRTH,
METRIC_TYPE_GIRTH_GOAL,
]

# Public key for encrypting the password
CONF_PUBLIC_KEY: Final = """-----BEGIN PUBLIC KEY-----
Expand Down
15 changes: 7 additions & 8 deletions custom_components/renpho/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import slugify

from .const import CM_TO_INCH, DOMAIN, KG_TO_LBS
from .const import CM_TO_INCH, DOMAIN, KG_TO_LBS, METRIC_TYPE
from .api_renpho import _LOGGER, RenphoWeight


Expand Down Expand Up @@ -757,9 +757,8 @@ def label(self) -> str:

async def async_update(self) -> None:
"""Update the sensor using the event loop for asynchronous code."""
METRIC_TYPES = ["weight", "growth", "growth_goal", ] # Define all the types of metrics
for metric_type in METRIC_TYPES:
try:
try:
for metric_type in METRIC_TYPE:
metric_value = await self._renpho.get_specific_metric(
metric_type=metric_type,
metric=self._metric,
Expand All @@ -777,9 +776,9 @@ async def async_update(self) -> None:

_LOGGER.info(f"Successfully updated {self._name} for metric type {metric_type}")

except (ConnectionError, TimeoutError) as e:
_LOGGER.error(f"{type(e).__name__} occurred while updating {self._name} for metric type {metric_type}: {e}")
except (ConnectionError, TimeoutError) as e:
_LOGGER.error(f"{type(e).__name__} occurred while updating {self._name} for metric type {metric_type}: {e}")

except Exception as e:
_LOGGER.critical(f"An unexpected error occurred while updating {self._name} for metric type {metric_type}: {e}")
except Exception as e:
_LOGGER.critical(f"An unexpected error occurred while updating {self._name} for metric type {metric_type}: {e}")

0 comments on commit 569a97b

Please sign in to comment.