### Get Username Property Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the username associated with the Dexcom Share account. ```python @property def username(self) -> str | None: """Get username.""" return self._username ``` -------------------------------- ### Get Account ID Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the account ID by making a POST request to the authentication endpoint. Logs the action at the debug level. ```python def _get_account_id(self) -> str: """ Retrieve account ID from the authentication endpoint. See `pydexcom.const.DEXCOM_AUTHENTICATE_ENDPOINT`. """ _LOGGER.debug("Retrieve account ID from the authentication endpoint") return self._post(**self._authenticate_endpoint_arguments) ``` -------------------------------- ### Get Session ID Source: https://gagebenne.github.io/pydexcom/pydexcom.html Fetches the session ID from the login endpoint using a POST request. Includes debug logging for the operation. ```python def _get_session_id(self) -> str: """ Retrieve session ID from the login endpoint. See `pydexcom.const.DEXCOM_LOGIN_ID_ENDPOINT`. """ _LOGGER.debug("Retrieve session ID from the login endpoint") return self._post(**self._login_id_endpoint_arguments) ``` -------------------------------- ### get_current_glucose_reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Get the current glucose reading available within the last 10 minutes. ```APIDOC ## get_current_glucose_reading ### Description Get current available glucose reading, within the last 10 minutes. ### Method GET (Implicit) ### Endpoint (Internal method, specific endpoint not detailed) ### Parameters None ### Response #### Success Response (200) - **GlucoseReading | None** - The current GlucoseReading object or None if no readings are available within the last 10 minutes. ``` -------------------------------- ### Get Latest Glucose Reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the most recent glucose reading available within the last 24 hours. ```python def get_latest_glucose_reading(self) -> GlucoseReading | None: """Get latest available glucose reading, within the last 24 hours.""" return next(iter(self.get_glucose_readings(max_count=1)), None) ``` -------------------------------- ### Get Latest Glucose Reading (pydexcom) Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the most recent glucose reading available within the last 24 hours. It uses `get_glucose_readings` with `max_count=1`. ```python def get_latest_glucose_reading(self) -> GlucoseReading | None: """Get latest available glucose reading, within the last 24 hours.""" return next(iter(self.get_glucose_readings(max_count=1)), None) ``` -------------------------------- ### Get Current Glucose Reading (pydexcom) Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the current glucose reading within the last 10 minutes. This function calls `get_glucose_readings` with specific time constraints. ```python def get_current_glucose_reading(self) -> GlucoseReading | None: """Get current available glucose reading, within the last 10 minutes.""" return next(iter(self.get_glucose_readings(minutes=10, max_count=1)), None) ``` -------------------------------- ### Get Current Glucose Reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the most recent glucose reading available within the last 10 minutes. ```python def get_current_glucose_reading(self) -> GlucoseReading | None: """Get current available glucose reading, within the last 10 minutes.""" return next(iter(self.get_glucose_readings(minutes=10, max_count=1)), None) ``` -------------------------------- ### Get Blood Glucose Trend Direction (Key) Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieve the key for the blood glucose trend direction. This key is found within `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. ```python 74 @property 75 def trend_direction(self) -> str: 76 """ 77 Blood glucose trend direction. 78 79 Key of `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. 80 """ 81 return self._trend_direction ``` -------------------------------- ### Get Blood Glucose Value (mg/dL) Source: https://gagebenne.github.io/pydexcom/pydexcom.html Access the blood glucose value in mg/dL. This property returns an integer representing the glucose level. ```python 50 @property 51 def value(self) -> int: 52 """Blood glucose value in mg/dL.""" 53 return self._value ``` -------------------------------- ### Get Account ID Property Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the account ID associated with the Dexcom Share account. ```python @property def account_id(self) -> str | None: """Get account ID.""" return self._account_id ``` -------------------------------- ### get_latest_glucose_reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Get the most recent glucose reading available within the last 24 hours. ```APIDOC ## get_latest_glucose_reading ### Description Get latest available glucose reading, within the last 24 hours. ### Method GET (Implicit) ### Endpoint (Internal method, specific endpoint not detailed) ### Parameters None ### Response #### Success Response (200) - **GlucoseReading | None** - The latest GlucoseReading object or None if no readings are available. ``` -------------------------------- ### Get Blood Glucose Trend Description Source: https://gagebenne.github.io/pydexcom/pydexcom.html Obtain a descriptive string for the blood glucose trend. This description is mapped from the trend value using `pydexcom.const.TREND_DESCRIPTIONS`. ```python 83 @property 84 def trend_description(self) -> str | None: 85 """ 86 Blood glucose trend information description. 87 88 See `pydexcom.const.TREND_DESCRIPTIONS`. 89 """ 90 return TREND_DESCRIPTIONS[self._trend] ``` -------------------------------- ### Get Glucose Readings Source: https://gagebenne.github.io/pydexcom/pydexcom.html Fetches glucose readings within a specified time frame. It handles session expiration by attempting to refresh the session ID and retrying the request. ```python def get_glucose_readings( self, minutes: int = MAX_MINUTES, max_count: int = MAX_MAX_COUNT, ) -> list[GlucoseReading]: """ Get `max_count` glucose readings within specified number of `minutes`. Catches one instance of a thrown `pydexcom.errors.SessionError` if session ID expired, attempts to get a new session ID and retries. :param minutes: Number of minutes to retrieve glucose readings from (1-1440) :param max_count: Maximum number of glucose readings to retrieve (1-288) """ json_glucose_readings: list[dict[str, Any]] = [] try: # Requesting glucose reading with DEFAULT_UUID returns non-JSON empty string self._validate_session_id() json_glucose_readings = self._get_glucose_readings(minutes, max_count) except SessionError: # Attempt to update expired session ID self._get_session() json_glucose_readings = self._get_glucose_readings(minutes, max_count) return [GlucoseReading(json_reading) for json_reading in json_glucose_readings] ``` -------------------------------- ### Get Blood Glucose Value (mmol/L) Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieve the blood glucose value converted to mmol/L. The value is rounded to one decimal place using the standard conversion factor. ```python 60 @property 61 def mmol_l(self) -> float: 62 """Blood glucose value in mmol/L.""" 63 return round(self.value * MMOL_L_CONVERSION_FACTOR, 1) ``` -------------------------------- ### Get Glucose Reading Datetime Source: https://gagebenne.github.io/pydexcom/pydexcom.html Access the timestamp when the glucose reading was recorded. This property returns a Python `datetime` object. ```python 97 @property 98 def datetime(self) -> datetime: 99 """Glucose reading recorded time as datetime.""" 100 return self._datetime ``` -------------------------------- ### Get Blood Glucose Value (mg/dL) - Alias Source: https://gagebenne.github.io/pydexcom/pydexcom.html An alias property to retrieve the blood glucose value in mg/dL. It functions identically to the 'value' property. ```python 55 @property 56 def mg_dl(self) -> int: 57 """Blood glucose value in mg/dL.""" 58 return self._value ``` -------------------------------- ### Get Blood Glucose Trend Information Source: https://gagebenne.github.io/pydexcom/pydexcom.html Access the blood glucose trend information. The value corresponds to constants defined in `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. ```python 65 @property 66 def trend(self) -> int: 67 """ 68 Blood glucose trend information. 69 70 Value of `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. 71 """ 72 return self._trend ``` -------------------------------- ### get_glucose_readings Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieve glucose readings from the glucose readings endpoint. This method handles session expiration by attempting to get a new session ID and retrying the request. ```APIDOC ## get_glucose_readings ### Description Get `max_count` glucose readings within specified number of `minutes`. Catches one instance of a thrown `pydexcom.errors.SessionError` if session ID expired, attempts to get a new session ID and retries. ### Method GET (Implicit) ### Endpoint (Internal method, specific endpoint not detailed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **minutes** (int) - Number of minutes to retrieve glucose readings from (1-1440) * **max_count** (int) - Maximum number of glucose readings to retrieve (1-288) ### Response #### Success Response (200) - **list[GlucoseReading]** - A list of GlucoseReading objects. ``` -------------------------------- ### Get Current Glucose Reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieve the latest glucose reading from the Dexcom Share service. Access various attributes of the reading like value, mmol/L equivalent, trend, and timestamp. ```python glucose_reading = dexcom.get_current_glucose_reading() print(glucose_reading) ``` ```python print(glucose_reading.value) 85 ``` ```python print(glucose_reading.mmol_l) 4.7 ``` ```python print(glucose_reading.trend) 4 ``` ```python print(glucose_reading.trend_direction) 'Flat' ``` ```python print(glucose_reading.trend_description) 'steady' ``` ```python print(glucose_reading.trend_arrow) '→' ``` ```python print(bg.datetime) 2023-08-07 20:40:58 ``` ```python print(glucose_reading.json) {'WT': 'Date(1691455258000)', 'ST': 'Date(1691455258000)', 'DT': 'Date(1691455258000-0400)', 'Value': 85, 'Trend': 'Flat'} ``` -------------------------------- ### Get Raw JSON Glucose Reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieve the original JSON object representing the glucose reading from the Dexcom Share API. This provides access to all raw data fields. ```python 102 @property 103 def json(self) -> dict[str, Any]: 104 """JSON glucose reading from Dexcom Share API.""" 105 return self._json ``` -------------------------------- ### Get Blood Glucose Trend Arrow Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieve the unicode arrow representing the blood glucose trend. The arrow is determined by the trend value and mapped using `pydexcom.const.TREND_ARROWS`. ```python 92 @property 93 def trend_arrow(self) -> str: 94 """Blood glucose trend as unicode arrow (`pydexcom.const.TREND_ARROWS`).""" 95 return TREND_ARROWS[self._trend] ``` -------------------------------- ### Dexcom Initialization Source: https://gagebenne.github.io/pydexcom/pydexcom.html Initialize the Dexcom client with your credentials. You can provide either a username or an account ID. ```APIDOC ## Dexcom ### Description Initialize `Dexcom` with Dexcom Share credentials. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **username** (str | None) - username for the Dexcom Share user, *not follower*. * **account_id** (str | None) - account ID for the Dexcom Share user, *not follower*. * **password** (str) - password for the Dexcom Share user. * **region** (Region) - the region to use, one of `"us"`, `"ous"`, `"jp"`. ``` -------------------------------- ### Initialize Dexcom Client Source: https://gagebenne.github.io/pydexcom/pydexcom.html Initialize the Dexcom client with your Dexcom Share credentials. Requires username, account ID, password, and optionally the region. ```python def __init__( self, *, password: str, account_id: str | None = None, username: str | None = None, region: Region = Region.US, ) -> None: """ Initialize `Dexcom` with Dexcom Share credentials. :param username: username for the Dexcom Share user, *not follower*. :param account_id: account ID for the Dexcom Share user, *not follower*. :param password: password for the Dexcom Share user. :param region: the region to use, one of `"us"`, `"ous"`, `"jp"`. """ self._validate_region(region) self._validate_user_ids(account_id, username) self._base_url = DEXCOM_BASE_URLS[region] self._application_id = DEXCOM_APPLICATION_IDS[region] self._password = password self._username: str | None = username self._account_id: str | None = account_id self._session_id: str | None = None self._session = requests.Session() self._get_session() ``` -------------------------------- ### Initialize GlucoseReading from JSON Source: https://gagebenne.github.io/pydexcom/pydexcom.html Initialize GlucoseReading with JSON glucose reading from Dexcom Share API. Handles potential errors during parsing. ```python ) if match: self._datetime = datetime.fromtimestamp( int(match.group("timestamp")) / 1000.0, tz=datetime.strptime(match.group("timezone"), "%z").tzinfo, ) except (KeyError, TypeError, ValueError) as error: raise ArgumentError(ArgumentErrorEnum.GLUCOSE_READING_INVALID) from error ``` -------------------------------- ### Initialize Dexcom class Source: https://gagebenne.github.io/pydexcom/pydexcom.html Initializes the Dexcom class with user credentials and region. Requires username, account ID, password, and optionally the region. The session is automatically established upon initialization. ```python class Dexcom: """Class for communicating with Dexcom Share API.""" def __init__( self, *, password: str, account_id: str | None = None, username: str | None = None, region: Region = Region.US, ) -> None: """ Initialize `Dexcom` with Dexcom Share credentials. :param username: username for the Dexcom Share user, *not follower*. :param account_id: account ID for the Dexcom Share user, *not follower*. :param password: password for the Dexcom Share user. :param region: the region to use, one of `"us"`, `"ous"`, `"jp"`. """ self._validate_region(region) self._validate_user_ids(account_id, username) self._base_url = DEXCOM_BASE_URLS[region] self._application_id = DEXCOM_APPLICATION_IDS[region] self._password = password self._username: str | None = username self._account_id: str | None = account_id self._session_id: str | None = None self._session = requests.Session() self._get_session() ``` -------------------------------- ### Initialize Dexcom API Client Source: https://gagebenne.github.io/pydexcom/pydexcom.html Instantiate the Dexcom client using various credential formats like username/password, phone number, email, or account ID. Specify the region if not in the US. ```python from pydexcom import Dexcom dexcom = Dexcom(username="username", password="password") # `region="ous"` if outside of US, `region="jp"` if Japan ``` ```python dexcom = Dexcom(username="+11234567890", password="password") # phone number ``` ```python dexcom = Dexcom(username="user@email.com", password="password") # email address ``` ```python dexcom = Dexcom(account_id="12345678-90ab-cdef-1234-567890abcdef", password="password") # account ID (advanced) ``` -------------------------------- ### Initialize DexcomError with Enum Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Demonstrates how to create a `DexcomError` instance using an associated `DexcomErrorEnum`. This provides a structured way to represent and communicate specific error conditions. ```python def __init__(self, enum: DexcomErrorEnum | None = None) -> None: """ Create `DexcomError` from `DexcomErrorEnum`. :param enum: associated `DexcomErrorEnum` """ if enum is not None: super().__init__(enum.value) else: super().__init__() self._enum = enum ``` -------------------------------- ### Initialize GlucoseReading (pydexcom) Source: https://gagebenne.github.io/pydexcom/pydexcom.html Initializes a `GlucoseReading` object by parsing JSON data from the Dexcom Share API. It handles potential errors during parsing. ```python def __init__(self, json_glucose_reading: dict[str, Any]) -> None: """ Initialize `GlucoseReading` with JSON glucose reading from Dexcom Share API. :param json_glucose_reading: JSON glucose reading from Dexcom Share API """ self._json = json_glucose_reading try: self._value = int(json_glucose_reading["Value"]) self._trend_direction: str = json_glucose_reading["Trend"] # Dexcom Share API returns `str` direction now, previously `int` trend self._trend: int = DEXCOM_TREND_DIRECTIONS[self._trend_direction] match = re.match( r"Date\((?P\d+)(?P[+-]\d{4})\)", json_glucose_reading["DT"], ) ``` -------------------------------- ### Dexcom Class Initialization Source: https://gagebenne.github.io/pydexcom/pydexcom.html Initializes the Dexcom class with user credentials and region. This is the primary entry point for interacting with the Dexcom Share API. ```APIDOC ## Dexcom Class ### Description Class for communicating with Dexcom Share API. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pydexcom import Dexcom, Region dexcom = Dexcom(username="YOUR_USERNAME", password="YOUR_PASSWORD", account_id="YOUR_ACCOUNT_ID", region=Region.US) ``` ### Response #### Success Response (200) None (initialization does not return a value) #### Response Example None ``` -------------------------------- ### Authenticate Endpoint Arguments Source: https://gagebenne.github.io/pydexcom/pydexcom.html Provides the arguments required for the authentication endpoint, including the endpoint URL and JSON payload with account credentials. ```python @property def _authenticate_endpoint_arguments(self) -> dict[str, Any]: return { "endpoint": DEXCOM_AUTHENTICATE_ENDPOINT, "json": { "accountName": self._username, "password": self._password, "applicationId": self._application_id, }, } ``` -------------------------------- ### Create Dexcom Share API Session Source: https://gagebenne.github.io/pydexcom/pydexcom.html Establishes a session with the Dexcom Share API by validating credentials, retrieving account and session IDs, and performing necessary validations. ```python def _get_session(self) -> None: """Create Dexcom Share API session.""" self._validate_password() if self._account_id is None: self._validate_username() self._account_id = self._get_account_id() self._validate_account_id() self._session_id = self._get_session_id() self._validate_session_id() ``` -------------------------------- ### Glucose Readings Endpoint Arguments Source: https://gagebenne.github.io/pydexcom/pydexcom.html Generates the arguments for fetching glucose readings, including the endpoint and parameters like session ID, minutes, and max count. ```python def _glucose_readings_endpoint_arguments( self, minutes: int = MAX_MINUTES, max_count: int = MAX_MAX_COUNT, ) -> dict[str, Any]: return { "endpoint": DEXCOM_GLUCOSE_READINGS_ENDPOINT, "params": { "sessionId": self._session_id, "minutes": minutes, "maxCount": max_count, }, } ``` -------------------------------- ### Login ID Endpoint Arguments Source: https://gagebenne.github.io/pydexcom/pydexcom.html Returns the arguments for the login ID endpoint, specifying the endpoint URL and the JSON payload containing account ID, password, and application ID. ```python @property def _login_id_endpoint_arguments(self) -> dict[str, Any]: return { "endpoint": DEXCOM_LOGIN_ID_ENDPOINT, "json": { "accountId": self._account_id, "password": self._password, "applicationId": self._application_id, }, } ``` -------------------------------- ### Import pydexcom library components Source: https://gagebenne.github.io/pydexcom/pydexcom.html Imports necessary classes and constants from the pydexcom library. Ensure these imports are present for using the library's functionalities. ```python from .const import Region from .dexcom import Dexcom from .glucose_reading import GlucoseReading __all__ = [ "Dexcom", "GlucoseReading", "Region", "const", "errors", ] ``` -------------------------------- ### Dexcom POST Request Helper Source: https://gagebenne.github.io/pydexcom/pydexcom.html Internal helper method for sending POST requests to the Dexcom Share API. This method handles request formatting, sending, and basic response parsing. ```APIDOC ## Dexcom POST Request Helper ### Description Send post request to Dexcom Share API. ### Method _post ### Endpoint N/A (internal method) ### Parameters #### Path Parameters None #### Query Parameters - **endpoint** (str) - URL of the post request - **params** (dict[str, Any] | None) - `dict` to send in the query string of the post request - **json** (dict[str, Any] | None) - JSON to send in the body of the post request ### Request Example ```python # This is an internal method and not intended for direct user calls. # Example of how it might be used internally: # response_data = dexcom._post("/v2/users/login", json=login_payload) ``` ### Response #### Success Response (200) - **Any** - The JSON response from the API. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Validate Account ID Source: https://gagebenne.github.io/pydexcom/pydexcom.html Verifies that the account ID is a valid non-empty UUID string and not the default placeholder. Raises an ArgumentError for invalid or default account IDs. ```python def _validate_account_id(self) -> None: """Validate account ID.""" if any( [ not isinstance(self._account_id, str), not self._account_id, not valid_uuid(self._account_id), ], ): raise ArgumentError(ArgumentErrorEnum.ACCOUNT_ID_INVALID) if self._account_id == DEFAULT_UUID: raise ArgumentError(ArgumentErrorEnum.ACCOUNT_ID_DEFAULT) ``` -------------------------------- ### Handle Dexcom API POST requests Source: https://gagebenne.github.io/pydexcom/pydexcom.html Internal method for sending POST requests to the Dexcom Share API. Handles response parsing, status checks, and error translation. Use this for custom API interactions. ```python def _post( self, endpoint: str, params: dict[str, Any] | None = None, json: dict[str, Any] | None = None, ) -> Any: # noqa: ANN401 """ Send post request to Dexcom Share API. :param endpoint: URL of the post request :param params: `dict` to send in the query string of the post request :param json: JSON to send in the body of the post request """ response = self._session.post( f"{self._base_url}{endpoint}", headers=HEADERS, params=params, json={} if json is None else json, ) try: response_json = response.json() response.raise_for_status() except requests.HTTPError as http_error: raise self._handle_error_code(response_json) from http_error except requests.JSONDecodeError as json_error: _LOGGER.exception("JSON decode error: %s", response.text) raise ServerError(ServerErrorEnum.INVALID_JSON) from json_error else: return response_json ``` -------------------------------- ### Validate Username Source: https://gagebenne.github.io/pydexcom/pydexcom.html Ensures that the username is a non-empty string. Raises an ArgumentError if the username is invalid. ```python def _validate_username(self) -> None: """Validate username.""" if any([not isinstance(self._username, str), not self._username]): raise ArgumentError(ArgumentErrorEnum.USERNAME_INVALID) ``` -------------------------------- ### Validate Minutes and Max Count Source: https://gagebenne.github.io/pydexcom/pydexcom.html Ensures that the provided minutes and max_count are non-negative integers within specified limits. Raises an ArgumentError for invalid values. ```python def _validate_minutes_max_count(self, minutes: int, max_count: int) -> None: if not isinstance(minutes, int) or any([minutes < 0, minutes > MAX_MINUTES]): raise ArgumentError(ArgumentErrorEnum.MINUTES_INVALID) if not isinstance(max_count, int) or any( [max_count < 0, max_count > MAX_MAX_COUNT], ): raise ArgumentError(ArgumentErrorEnum.MAX_COUNT_INVALID) ``` -------------------------------- ### Validate User IDs Source: https://gagebenne.github.io/pydexcom/pydexcom.html Validates that exactly one user identifier (account ID or username) is provided. Raises an ArgumentError if zero or multiple user IDs are given. ```python def _validate_user_ids(self, account_id: str | None, username: str | None) -> None: user_ids = sum(user_id is not None for user_id in [account_id, username]) if user_ids == 0: raise ArgumentError(ArgumentErrorEnum.USER_ID_REQUIRED) if user_ids != 1: raise ArgumentError(ArgumentErrorEnum.USER_ID_MULTIPLE) ``` -------------------------------- ### Region Enum Source: https://gagebenne.github.io/pydexcom/pydexcom.html Enumeration for supported Dexcom regions. ```APIDOC ## Region Enum ### Description Enumeration for supported Dexcom regions. ### Members - **US** ('us') - **OUS** ('ous') - **JP** ('jp') ``` -------------------------------- ### Define ServerError Exception Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Specific exception class for errors related to unexpected or malformed server responses from the Dexcom API. Inherits from DexcomError. ```python class ServerError(DexcomError): """Errors involving unexpected or malformed server responses.""" pass ``` -------------------------------- ### Retrieve Glucose Readings Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves glucose readings from the Dexcom Share API. Handles session expiration by attempting to refresh the session ID. ```python def get_glucose_readings( self, minutes: int = MAX_MINUTES, max_count: int = MAX_MAX_COUNT, ) -> list[GlucoseReading]: """ Get `max_count` glucose readings within specified number of `minutes`. Catches one instance of a thrown `pydexcom.errors.SessionError` if session ID expired, attempts to get a new session ID and retries. :param minutes: Number of minutes to retrieve glucose readings from (1-1440) :param max_count: Maximum number of glucose readings to retrieve (1-288) """ json_glucose_readings: list[dict[str, Any]] = [] try: # Requesting glucose reading with DEFAULT_UUID returns non-JSON empty string self._validate_session_id() json_glucose_readings = self._get_glucose_readings(minutes, max_count) except SessionError: # Attempt to update expired session ID self._get_session() json_glucose_readings = self._get_glucose_readings(minutes, max_count) return [GlucoseReading(json_reading) for json_reading in json_glucose_readings] ``` -------------------------------- ### Define AccountError Exception Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Specific exception class for errors related to Dexcom Share API credentials. Inherits from DexcomError. ```python class AccountError(DexcomError): """Errors involving Dexcom Share API credentials.""" pass ``` -------------------------------- ### get_glucose_readings Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves a specified number of glucose readings within a given time frame. It handles session expiration by attempting to refresh the session ID. ```APIDOC ## get_glucose_readings ### Description Get `max_count` glucose readings within specified number of `minutes`. Catches one instance of a thrown `pydexcom.errors.SessionError` if session ID expired, attempts to get a new session ID and retries. ### Method ```python def get_glucose_readings(self, minutes: int = 1440, max_count: int = 288) -> list[GlucoseReading]: ``` ### Parameters #### Query Parameters - **minutes** (int) - Optional - Number of minutes to retrieve glucose readings from (1-1440). Defaults to 1440. - **max_count** (int) - Optional - Maximum number of glucose readings to retrieve (1-288). Defaults to 288. ### Response #### Success Response (list[GlucoseReading]) - A list of `GlucoseReading` objects. ### Response Example ```json [ { "value": 100, "unit": "mg/dL", "trend": "flat", "time": "2023-10-27T10:00:00" } ] ``` ``` -------------------------------- ### Dexcom Username Property Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the username associated with the Dexcom Share account. ```APIDOC ## Dexcom Username Property ### Description Get username. ### Method username (getter) ### Endpoint N/A (property) ### Parameters None ### Request Example ```python print(dexcom.username) ``` ### Response #### Success Response (200) - **username** (str | None) - The username of the Dexcom Share account. #### Response Example ``` "YOUR_USERNAME" ``` ``` -------------------------------- ### Define AccountErrorEnum for pydexcom Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines specific error strings related to account authentication and session management. Use these for failed authentication or exceeding maximum attempts. ```python class AccountErrorEnum(DexcomErrorEnum): """`AccountError` strings.""" FAILED_AUTHENTICATION = "Failed to authenticate" MAX_ATTEMPTS = "Maximum authentication attempts exceeded" ``` -------------------------------- ### Validate Password Source: https://gagebenne.github.io/pydexcom/pydexcom.html Checks if the password is a non-empty string. Raises an ArgumentError if the password is invalid. ```python def _validate_password(self) -> None: """Validate password.""" if any([not isinstance(self._password, str), not self._password]): raise ArgumentError(ArgumentErrorEnum.PASSWORD_INVALID) ``` -------------------------------- ### Define SessionError Exception Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Specific exception class for errors related to Dexcom Share API sessions. Inherits from DexcomError. ```python class SessionError(DexcomError): """Errors involving Dexcom Share API session.""" pass ``` -------------------------------- ### AccountError Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Represents errors specifically related to Dexcom Share API credentials. Inherits from `DexcomError`. ```APIDOC ## AccountError ### Description Errors involving Dexcom Share API credentials. ### Inheritance Inherits from `DexcomError`. ``` -------------------------------- ### ServerError Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Represents errors arising from unexpected or malformed responses received from the Dexcom server. Inherits from `DexcomError`. ```APIDOC ## ServerError ### Description Errors involving unexpected or malformed server responses. ### Inheritance Inherits from `DexcomError`. ``` -------------------------------- ### Validate Session ID Source: https://gagebenne.github.io/pydexcom/pydexcom.html Checks if the session ID is a valid non-empty UUID string and not the default placeholder. Raises an ArgumentError for invalid or default session IDs. ```python def _validate_session_id(self) -> None: """Validate session ID.""" if any( [ not isinstance(self._session_id, str), not self._session_id, not valid_uuid(self._session_id), ], ): raise ArgumentError(ArgumentErrorEnum.SESSION_ID_INVALID) if self._session_id == DEFAULT_UUID: raise ArgumentError(ArgumentErrorEnum.SESSION_ID_DEFAULT) ``` -------------------------------- ### Define Base Dexcom Error Class Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Establishes the base exception class for all pydexcom-specific errors. This class can optionally be initialized with a `DexcomErrorEnum` to provide a more specific error message. ```python class DexcomError(Exception): """Base class for all `pydexcom` errors.""" def __init__(self, enum: DexcomErrorEnum | None = None) -> None: """ Create `DexcomError` from `DexcomErrorEnum`. :param enum: associated `DexcomErrorEnum` """ if enum is not None: super().__init__(enum.value) else: super().__init__() self._enum = enum @property def enum(self) -> DexcomErrorEnum | None: """ Get `DexcomErrorEnum` associated with error. :return: `DexcomErrorEnum` """ return self._enum ``` -------------------------------- ### Define SessionErrorEnum for pydexcom Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines error strings for session-related issues. Use these when a session ID is not found or when a session is invalid or has timed out. ```python class SessionErrorEnum(DexcomErrorEnum): """`SessionError` strings.""" NOT_FOUND = "Session ID not found" INVALID = "Session not active or timed out" ``` -------------------------------- ### SessionError Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Represents errors that occur during a Dexcom Share API session. Inherits from `DexcomError`. ```APIDOC ## SessionError ### Description Errors involving Dexcom Share API session. ### Inheritance Inherits from `DexcomError`. ``` -------------------------------- ### GlucoseReading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Represents a single glucose reading from the Dexcom Share API. ```APIDOC ## GlucoseReading ### Description Class for parsing glucose reading from Dexcom Share API. ### Initialization ```python GlucoseReading(json_glucose_reading: dict[str, typing.Any]) ``` #### Parameters * **json_glucose_reading** (dict[str, typing.Any]) - Required - JSON glucose reading from Dexcom Share API ### Properties * **value** (int) - Blood glucose value in mg/dL. * **mg_dl** (int) - Blood glucose value in mg/dL. * **mmol_l** (float) - Blood glucose value in mmol/L. * **trend** (int) - Blood glucose trend information. Value of `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. * **trend_direction** (str) - Blood glucose trend direction. Key of `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. * **trend_description** (str | None) - Blood glucose trend information description. See `pydexcom.const.TREND_DESCRIPTIONS`. * **trend_arrow** (str) - Blood glucose trend as unicode arrow (`pydexcom.const.TREND_ARROWS`). * **datetime** (datetime) - Glucose reading recorded time as datetime. * **json** (dict[str, Any]) - JSON glucose reading from Dexcom Share API. ``` -------------------------------- ### ServerError Class Definition Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines the ServerError class, inheriting from DexcomError. Use this for errors related to unexpected or malformed responses from the Dexcom server. ```python 89class ServerError(DexcomError): 90 """Errors involving unexpected or malformed server responses.""" ``` -------------------------------- ### Define ServerErrorEnum for pydexcom Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines error strings for issues related to server responses. Use these for invalid JSON, unknown error codes, or unexpected server responses. ```python class ServerErrorEnum(DexcomErrorEnum): """`ServerErrorEnum` strings.""" INVALID_JSON = "Invalid or malformed JSON in server response" UNKNOWN_CODE = "Unknown error code in server response" UNEXPECTED = "Unexpected server response" ``` -------------------------------- ### get_current_glucose_reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the most recent glucose reading available within the last 10 minutes. ```APIDOC ## get_current_glucose_reading ### Description Get current available glucose reading, within the last 10 minutes. ### Method ```python def get_current_glucose_reading(self) -> GlucoseReading | None: """Get current available glucose reading, within the last 10 minutes.""" return next(iter(self.get_glucose_readings(minutes=10, max_count=1)), None) ``` ``` -------------------------------- ### get_latest_glucose_reading Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the most recent glucose reading available within the last 24 hours. ```APIDOC ## get_latest_glucose_reading ### Description Get latest available glucose reading, within the last 24 hours. ### Method ```python def get_latest_glucose_reading(self) -> GlucoseReading | None: """Get latest available glucose reading, within the last 24 hours.""" return next(iter(self.get_glucose_readings(max_count=1)), None) ``` ``` -------------------------------- ### Glucose Reading Properties Source: https://gagebenne.github.io/pydexcom/pydexcom.html Provides access to various attributes of a glucose reading, including its value, unit conversions, trend information, and timestamp. ```APIDOC ## Glucose Reading Properties ### Description Provides access to various attributes of a glucose reading, including its value, unit conversions, trend information, and timestamp. ### Properties - **value** (int) - Blood glucose value in mg/dL. - **mg_dl** (int) - Blood glucose value in mg/dL. - **mmol_l** (float) - Blood glucose value in mmol/L. - **trend** (int) - Blood glucose trend information. Value of `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. - **trend_direction** (str) - Blood glucose trend direction. Key of `pydexcom.const.DEXCOM_TREND_DIRECTIONS`. - **trend_description** (str | None) - Blood glucose trend information description. See `pydexcom.const.TREND_DESCRIPTIONS`. - **trend_arrow** (str) - Blood glucose trend as unicode arrow (`pydexcom.const.TREND_ARROWS`). - **datetime** (datetime) - Glucose reading recorded time as datetime. - **json** (dict[str, typing.Any]) - JSON glucose reading from Dexcom Share API. ``` -------------------------------- ### ArgumentError Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Represents errors related to invalid arguments passed to `pydexcom` functions or methods. Inherits from `DexcomError`. ```APIDOC ## ArgumentError ### Description Errors involving `pydexcom` arguments. ### Inheritance Inherits from `DexcomError`. ``` -------------------------------- ### Define ArgumentErrorEnum for pydexcom Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines error strings for invalid arguments passed to pydexcom functions. Covers issues with minutes, max count, username, password, region, and IDs. ```python class ArgumentErrorEnum(DexcomErrorEnum): ""`ArgumentError` strings.""" MINUTES_INVALID = "Minutes must be and integer between 1 and 1440" MAX_COUNT_INVALID = "Max count must be and integer between 1 and 288" USERNAME_INVALID = "Username must be non-empty string" USER_ID_MULTIPLE = "Only one of account_id, username should be provided" USER_ID_REQUIRED = "At least one of account_id, username should be provided" PASSWORD_INVALID = "Password must be non-empty string" # noqa: S105 REGION_INVALID = "Region must be 'us', 'ous, or 'jp'" ACCOUNT_ID_INVALID = "Account ID must be UUID" ACCOUNT_ID_DEFAULT = "Account ID default" SESSION_ID_INVALID = "Session ID must be UUID" SESSION_ID_DEFAULT = "Session ID default" GLUCOSE_READING_INVALID = "JSON glucose reading incorrectly formatted" ``` -------------------------------- ### Define Server Error Enum Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines enumeration for server-side errors encountered during API communication. Use these to represent specific issues with the Dexcom server's responses. ```python class ServerErrorEnum(DexcomErrorEnum): """`ServerErrorEnum` strings.""" INVALID_JSON = "Invalid or malformed JSON in server response" UNKNOWN_CODE = "Unknown error code in server response" UNEXPECTED = "Unexpected server response" ``` -------------------------------- ### Define ArgumentError Exception Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Specific exception class for errors related to invalid arguments passed to pydexcom functions. Inherits from DexcomError. ```python class ArgumentError(DexcomError): """Errors involving `pydexcom` arguments.""" pass ``` -------------------------------- ### Define Dexcom API Regions Source: https://gagebenne.github.io/pydexcom/pydexcom.html Enum class for specifying Dexcom API regions. Use these constants when configuring API access to ensure correct regional endpoints are used. ```python 7class Region(str, Enum): 8 """Regions.""" 9 10 US = "us" 11 OUS = "ous" 12 JP = "jp" ``` -------------------------------- ### Define Base DexcomError Exception Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html The base exception class for all errors raised by the pydexcom library. It can optionally be initialized with a DexcomErrorEnum value. ```python class DexcomError(Exception): """Base class for all `pydexcom` errors.""" def __init__(self, enum: DexcomErrorEnum | None = None) -> None: """ Create `DexcomError` from `DexcomErrorEnum`. :param enum: associated `DexcomErrorEnum` """ if enum is not None: super().__init__(enum.value) else: super().__init__() self._enum = enum @property def enum(self) -> DexcomErrorEnum | None: """ Get `DexcomErrorEnum` associated with error. :return: `DexcomErrorEnum` """ return self._enum ``` -------------------------------- ### Validate Region Source: https://gagebenne.github.io/pydexcom/pydexcom.html Ensures that the provided region is a valid enumeration member. Raises an ArgumentError if the region is invalid. ```python def _validate_region(self, region: Region) -> None: if region not in list(Region): raise ArgumentError(ArgumentErrorEnum.REGION_INVALID) ``` -------------------------------- ### AccountError Class Definition Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines the AccountError class, inheriting from DexcomError. Use this for errors related to Dexcom Share API credentials. ```python 77class AccountError(DexcomError): 78 """Errors involving Dexcom Share API credentials.""" ``` -------------------------------- ### SessionError Class Definition Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines the SessionError class, inheriting from DexcomError. Use this for errors related to Dexcom Share API session management. ```python 81class SessionError(DexcomError): 82 """Errors involving Dexcom Share API session.""" ``` -------------------------------- ### Access DexcomErrorEnum from DexcomError Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html This property allows retrieval of the specific DexcomErrorEnum associated with a DexcomError instance. Useful for detailed error analysis. ```python 67 @property 68 def enum(self) -> DexcomErrorEnum | None: 69 """ 70 Get `DexcomErrorEnum` associated with error. 71 72 :return: `DexcomErrorEnum` 73 """ 74 return self._enum ``` -------------------------------- ### Dexcom Account ID Property Source: https://gagebenne.github.io/pydexcom/pydexcom.html Retrieves the account ID associated with the Dexcom Share account. ```APIDOC ## Dexcom Account ID Property ### Description Get account ID. ### Method account_id (getter) ### Endpoint N/A (property) ### Parameters None ### Request Example ```python print(dexcom.account_id) ``` ### Response #### Success Response (200) - **account_id** (str | None) - The account ID of the Dexcom Share account. #### Response Example ``` "YOUR_ACCOUNT_ID" ``` ``` -------------------------------- ### Dexcom Error Handling Source: https://gagebenne.github.io/pydexcom/pydexcom.html Internal method to parse API error responses and raise appropriate DexcomError exceptions. It maps specific error codes from the API to custom error types. ```APIDOC ## Dexcom Error Handling ### Description Parse `requests.Response` JSON for `pydexcom.errors.DexcomError`. ### Method _handle_error_code ### Endpoint N/A (internal method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **json** (dict[str, Any]) - `requests.Response` JSON to parse ### Request Example ```python # This is an internal method and not intended for direct user calls. # Example of how it might be used internally: # try: # response.raise_for_status() # except requests.HTTPError as http_error: # raise self._handle_error_code(response_json) from http_error ``` ### Response #### Success Response (200) - **DexcomError** - An instance of a DexcomError subclass. #### Response Example ```python # Raises specific DexcomError subclasses like SessionError, AccountError, ArgumentError, ServerError ``` ``` -------------------------------- ### ArgumentError Class Definition Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html Defines the ArgumentError class, inheriting from DexcomError. Use this for errors arising from invalid arguments passed to pydexcom functions. ```python 85class ArgumentError(DexcomError): 86 """Errors involving `pydexcom` arguments.""" ``` -------------------------------- ### Parse Dexcom API error codes Source: https://gagebenne.github.io/pydexcom/pydexcom.html Internal method to parse JSON responses from the Dexcom Share API and translate them into specific `pydexcom.errors.DexcomError` exceptions. This helps in handling API-level errors gracefully. ```python def _handle_error_code(self, json: dict[str, Any]) -> DexcomError: # noqa: C901, PLR0911 """ Parse `requests.Response` JSON for `pydexcom.errors.DexcomError`. :param response: `requests.Response` JSON to parse """ _LOGGER.debug("%s", json) code, message = json.get("Code"), json.get("Message") if code == "SessionIdNotFound": return SessionError(SessionErrorEnum.NOT_FOUND) if code == "SessionNotValid": return SessionError(SessionErrorEnum.INVALID) if code == "AccountPasswordInvalid": return AccountError(AccountErrorEnum.FAILED_AUTHENTICATION) if code == "SSO_AuthenticateMaxAttemptsExceeded": return AccountError(AccountErrorEnum.MAX_ATTEMPTS) if code == "SSO_InternalError": # noqa: SIM102 if message and ( "Cannot Authenticate by AccountName" in message or "Cannot Authenticate by AccountId" in message ): return AccountError(AccountErrorEnum.FAILED_AUTHENTICATION) if code == "InvalidArgument": if message and "accountName" in message: return ArgumentError(ArgumentErrorEnum.USERNAME_INVALID) if message and "password" in message: return ArgumentError(ArgumentErrorEnum.PASSWORD_INVALID) if message and "UUID" in message: return ArgumentError(ArgumentErrorEnum.ACCOUNT_ID_INVALID) if code and message: _LOGGER.error("%s: %s", code, message) return ServerError(ServerErrorEnum.UNKNOWN_CODE) ``` -------------------------------- ### DexcomError Enum Property Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html The `enum` property allows you to retrieve the specific `DexcomErrorEnum` associated with a `DexcomError` instance. This provides more granular details about the nature of the error. ```APIDOC ## DexcomError.enum ### Description Get `DexcomErrorEnum` associated with error. ### Method `property` ### Returns - `DexcomErrorEnum` | None: The associated Dexcom error enumeration, or None if not applicable. ``` -------------------------------- ### Define Base Error Enum for pydexcom Source: https://gagebenne.github.io/pydexcom/pydexcom/errors.html This is the base enumeration class for all error strings used in pydexcom. It inherits from Python's Enum. ```python from __future__ import annotations from enum import Enum class DexcomErrorEnum(Enum): """Base class for all `pydexcom` error strings.""" pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.