1515
1616from logging import getLogger
1717from hashlib import md5
18+ import sys
1819from urllib .parse import urljoin
1920from typing import Any , Dict , List , TypeAlias
20- from datetime import datetime , timedelta
21+ from datetime import timedelta
2122from homeassistant .helpers .update_coordinator import DataUpdateCoordinator
22- from homeassistant .exceptions import ConfigEntryAuthFailed
23- from .exceptions import PetLibroAPIError , PetLibroInvalidAuth
24- from aiohttp import ClientSession , ClientError
23+ from homeassistant .util . dt import utcnow
24+ from .exceptions import PetLibroAPIError
25+ from aiohttp import ClientSession
2526
2627import aiohttp
2728import uuid # To generate unique request IDs
@@ -204,6 +205,10 @@ def __init__(self, session: ClientSession, time_zone: str, region: str, email: s
204205 self ._last_api_call_times = {} # To store last call time per device
205206 self ._cached_responses = {} # To store cached responses for short periods
206207
208+ if "PL_PetAPI" not in sys .modules :
209+ from .pets .api import PL_PetAPI
210+ self .pets = PL_PetAPI (self .hass , self .config_entry , self .session )
211+
207212 @staticmethod
208213 def hash_password (password : str ) -> str :
209214 """Generate the password hash for the API"""
@@ -242,7 +247,7 @@ async def login(self, email: str, password: str) -> str:
242247
243248 async def get_device_real_info (self , device_id : str ) -> dict :
244249 """Fetch real-time information for a device, with caching to prevent frequent requests."""
245- now = datetime . utcnow ()
250+ now = utcnow ()
246251 last_call_time = self ._last_api_call_times .get (f"{ device_id } _realInfo" )
247252
248253 # If we made the request within the last 10 seconds, return cached response
@@ -268,7 +273,7 @@ async def get_device_real_info(self, device_id: str) -> dict:
268273
269274 async def get_device_data_real_info (self , device_id : str ) -> dict :
270275 """Fetch real-time information for a device, with caching to prevent frequent requests."""
271- now = datetime . utcnow ()
276+ now = utcnow ()
272277 last_call_time = self ._last_api_call_times .get (f"{ device_id } _dataRealInfo" )
273278
274279 # If we made the request within the last 10 seconds, return cached response
@@ -294,7 +299,7 @@ async def get_device_data_real_info(self, device_id: str) -> dict:
294299
295300 async def get_device_drink_water (self , device_id : str ) -> dict :
296301 """Fetch real-time information for a device, with caching to prevent frequent requests."""
297- now = datetime . utcnow ()
302+ now = utcnow ()
298303 last_call_time = self ._last_api_call_times .get (f"{ device_id } _drinkWater" )
299304
300305 # If we made the request within the last 10 seconds, return cached response
@@ -320,7 +325,7 @@ async def get_device_drink_water(self, device_id: str) -> dict:
320325
321326 async def get_device_attribute_settings (self , device_id : str ) -> dict :
322327 """Fetch real-time information for a device, with caching to prevent frequent requests."""
323- now = datetime . utcnow ()
328+ now = utcnow ()
324329 last_call_time = self ._last_api_call_times .get (f"{ device_id } _getAttributeSetting" )
325330
326331 # If we made the request within the last 10 seconds, return cached response
@@ -345,7 +350,7 @@ async def get_device_attribute_settings(self, device_id: str) -> dict:
345350
346351 async def get_device_upgrade (self , device_id : str ) -> dict :
347352 """Fetch real-time information for a device, with caching to prevent frequent requests."""
348- now = datetime . utcnow ()
353+ now = utcnow ()
349354 last_call_time = self ._last_api_call_times .get (f"{ device_id } _getUpgrade" )
350355
351356 # If we made the request within the last 10 seconds, return cached response
@@ -370,7 +375,7 @@ async def get_device_upgrade(self, device_id: str) -> dict:
370375
371376 async def get_device_base_info (self , device_id : str ) -> dict :
372377 """Fetch real-time information for a device, with caching to prevent frequent requests."""
373- now = datetime . utcnow ()
378+ now = utcnow ()
374379 last_call_time = self ._last_api_call_times .get (f"{ device_id } _baseInfo" )
375380
376381 # If we made the request within the last 10 seconds, return cached response
@@ -395,7 +400,7 @@ async def get_device_base_info(self, device_id: str) -> dict:
395400
396401 async def get_device_work_record (self , device_id : str ) -> dict :
397402 """Fetch real-time information for a device, with caching to prevent frequent requests."""
398- now = datetime . utcnow ()
403+ now = utcnow ()
399404 last_call_time = self ._last_api_call_times .get (f"{ device_id } _work_record" )
400405
401406 if last_call_time and (now - last_call_time ) < timedelta (seconds = 10 ):
@@ -432,7 +437,7 @@ async def get_device_work_record(self, device_id: str) -> dict:
432437
433438 async def get_device_events (self , device_id : str ) -> dict :
434439 """Fetch real-time information for a device, with caching to prevent frequent requests."""
435- now = datetime . utcnow ()
440+ now = utcnow ()
436441 last_call_time = self ._last_api_call_times .get (f"{ device_id } _events" )
437442
438443 # If we made the request within the last 10 seconds, return cached response
@@ -463,7 +468,7 @@ async def get_default_matrix(self, device_sn: str) -> dict:
463468 :return: The default matrix data.
464469 """
465470 # Check cache for recently fetched data
466- now = datetime . utcnow ()
471+ now = utcnow ()
467472 cache_key = f"{ device_sn } _getDefaultMatrix"
468473 last_call_time = self ._last_api_call_times .get (cache_key )
469474
@@ -542,6 +547,21 @@ async def device_feeding_plan_list(self, serial: str) -> List[Dict[str, Any]]:
542547 async def device_wet_feeding_plan (self , serial : str ) -> Dict [str , Any ]:
543548 return await self .session .post_serial ("/device/wetFeedingPlan/wetListV3" , serial )
544549
550+ async def device_get_bound_pets (self , device_sn : str ) -> list [dict ]:
551+ """Get pets bound to a device."""
552+ _LOGGER .debug ("Requesting pets bound to device sn: %s" , device_sn )
553+
554+ try :
555+ data = await self .session .post ("/device/devicePetRelation/getBoundPets" , json = {"deviceSn" : device_sn })
556+ except Exception as exc :
557+ raise PetLibroAPIError ("Failed to fetch list of bound pets" ) from exc
558+
559+ if data and not isinstance (data , list ):
560+ raise PetLibroAPIError (f"Invalid bound pets response format: { data } " )
561+
562+ _LOGGER .debug ("Bound pets retrieved successfully" )
563+ return data or []
564+
545565 # Support for new switch functions
546566 async def set_feeding_plan (self , serial : str , enable : bool ):
547567 """Set the feeding plan on/off."""
0 commit comments