PyFlumeNG 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyflume/constants.py ADDED
@@ -0,0 +1,31 @@
1
+ """Constants to support PyFlume."""
2
+
3
+ # Time-related constants
4
+ API_LIMIT = 60
5
+ DEFAULT_TIMEOUT = 30
6
+
7
+ # Operation constants
8
+ CONST_OPERATION = "SUM"
9
+ CONST_UNIT_OF_MEASUREMENT = "GALLONS"
10
+
11
+ # Base URL
12
+ API_BASE_URL = "https://api.flumetech.com"
13
+
14
+ # Endpoints
15
+ URL_OAUTH_TOKEN = f"{API_BASE_URL}/oauth/token"
16
+ API_QUERY_URL = f"{API_BASE_URL}/users/{{user_id}}/devices/{{device_id}}/query"
17
+ API_DEVICES_URL = f"{API_BASE_URL}/users/{{user_id}}/devices"
18
+ API_NOTIFICATIONS_URL = f"{API_BASE_URL}/users/{{user_id}}/notifications"
19
+ API_LEAK_URL = f"{API_BASE_URL}/users/{{user_id}}/devices/{{device_id}}/leaks/active"
20
+ API_USAGE_URL = f"{API_BASE_URL}/users/{{user_id}}/usage-alerts"
21
+ API_USAGE_RULES_URL = (
22
+ f"{API_BASE_URL}/users/{{user_id}}/devices/{{device_id}}/rules/usage-alerts"
23
+ )
24
+ API_USAGE_RULE_URL = f"{API_BASE_URL}/users/{{user_id}}/devices/{{device_id}}/rules/usage-alerts/{{rule_id}}"
25
+
26
+ # Portal API (same backend, portal OAuth client + login flow)
27
+ PORTAL_API_URL = "https://api.flumewater.com"
28
+ PORTAL_OAUTH_AUTHORIZE_URL = f"{PORTAL_API_URL}/oauth/authorize"
29
+ PORTAL_OAUTH_TOKEN_URL = f"{PORTAL_API_URL}/oauth/token"
30
+ PORTAL_CLIENT_ID = "customer-portal"
31
+ PORTAL_REDIRECT_URI = "https://portal.flumewater.com"
pyflume/data.py ADDED
@@ -0,0 +1,226 @@
1
+ """Retrieve data from Flume API."""
2
+
3
+ import sys
4
+ from datetime import datetime, timedelta, timezone
5
+ from typing import Any, List, Optional, Union, cast
6
+
7
+ from ratelimit import limits, sleep_and_retry
8
+ from requests import Session
9
+
10
+ from .auth import FlumeAuth, FlumePortalAuth # noqa: WPS300
11
+ from .constants import ( # noqa: WPS300
12
+ API_LIMIT,
13
+ API_QUERY_URL,
14
+ CONST_OPERATION,
15
+ CONST_UNIT_OF_MEASUREMENT,
16
+ DEFAULT_TIMEOUT,
17
+ )
18
+ from .types import QueryPayload, QuerySpec, QueryValues, ResourceId # noqa: WPS300
19
+ from .utils import ( # noqa: WPS300
20
+ configure_logger,
21
+ flume_response_error,
22
+ format_start_month,
23
+ format_start_today,
24
+ format_start_week,
25
+ format_time,
26
+ )
27
+
28
+ if sys.version_info >= (3, 9):
29
+ from zoneinfo import ZoneInfo # noqa: WPS433
30
+ else: # pragma: no cover - exercised on Python 3.8
31
+ from backports.zoneinfo import ZoneInfo # noqa: WPS433,WPS440
32
+
33
+ # Configure logging
34
+ LOGGER = configure_logger(__name__)
35
+
36
+
37
+ class FlumeData:
38
+ """Get the latest data and update the states."""
39
+
40
+ def __init__( # noqa: WPS211
41
+ self,
42
+ flume_auth: Union[FlumeAuth, FlumePortalAuth],
43
+ device_id: ResourceId,
44
+ device_tz: str,
45
+ scan_interval: timedelta,
46
+ update_on_init: bool = True,
47
+ http_session: Optional[Session] = None,
48
+ timeout: float = DEFAULT_TIMEOUT,
49
+ query_payload: Optional[QueryPayload] = None,
50
+ ) -> None:
51
+ """
52
+
53
+ Initialize the data object.
54
+
55
+ Args:
56
+ flume_auth: Authentication object.
57
+ device_id: flume device id.
58
+ device_tz: timezone of device
59
+ scan_interval: duration of scan, ex: 60 minutes.
60
+ update_on_init: update on initialization.
61
+ http_session: Requests Session()
62
+ timeout: Requests timeout for throttling.
63
+ query_payload: Specific query_payload to request for device.
64
+
65
+ """
66
+ self._timeout: float = timeout
67
+ self._flume_auth: Union[FlumeAuth, FlumePortalAuth] = flume_auth
68
+ self._scan_interval: timedelta = scan_interval
69
+ self.device_id: ResourceId = device_id
70
+ self.device_tz: str = device_tz
71
+ self.values: QueryValues = {} # noqa: WPS110
72
+ if query_payload is None:
73
+ self.query_payload = self._generate_api_query_payload(
74
+ self._scan_interval,
75
+ device_tz,
76
+ )
77
+ else:
78
+ self.query_payload = query_payload
79
+ if http_session is None:
80
+ self._http_session: Session = Session()
81
+ else:
82
+ self._http_session = http_session
83
+ self._query_keys: List[str] = [
84
+ query["request_id"] for query in self.query_payload["queries"]
85
+ ]
86
+ if update_on_init:
87
+ self.update()
88
+
89
+ @sleep_and_retry
90
+ @limits(calls=2, period=API_LIMIT)
91
+ def update(self) -> None:
92
+ """
93
+ Return updated value for session.
94
+
95
+ Returns:
96
+ Returns status of update
97
+
98
+ """
99
+ return self.update_force()
100
+
101
+ def update_force(self) -> None:
102
+ """Return updated value for session without auto retry or limits."""
103
+ self.query_payload = self._generate_api_query_payload(
104
+ self._scan_interval,
105
+ self.device_tz,
106
+ )
107
+
108
+ url = API_QUERY_URL.format(
109
+ user_id=self._flume_auth.user_id,
110
+ device_id=self.device_id,
111
+ )
112
+ response = self._http_session.post(
113
+ url,
114
+ json=cast(Any, self.query_payload),
115
+ headers=self._flume_auth.authorization_header,
116
+ timeout=self._timeout,
117
+ )
118
+
119
+ LOGGER.debug("Update URL: %s", url) # noqa: WPS323
120
+ LOGGER.debug("Update query_payload: %s", self.query_payload) # noqa: WPS323
121
+ LOGGER.debug("Update Response: %s", response.text) # noqa: WPS323
122
+
123
+ # Check for response errors.
124
+ flume_response_error(
125
+ "Can't update flume data for user id {0}".format(self._flume_auth.user_id),
126
+ response,
127
+ )
128
+
129
+ responses = response.json()["data"][0]
130
+
131
+ # Step 1: Initialize an empty dictionary
132
+ values_dict: QueryValues = {}
133
+
134
+ # Step 2: Loop through each key in self._query_keys
135
+ for key in self._query_keys:
136
+ # Step 3: Check the length of the responses for the current key
137
+ if len(responses[key]) == 1:
138
+ # Step 4: Assign the value to the dictionary if the condition is met
139
+ values_dict[key] = responses[key][0]["value"]
140
+ else:
141
+ # Step 5: Assign None to the dictionary if the condition is not met
142
+ values_dict[key] = None
143
+
144
+ # Step 6: Assign the result to self.values
145
+ self.values = values_dict # noqa: WPS110
146
+
147
+ def _generate_api_query_payload(
148
+ self,
149
+ scan_interval: timedelta,
150
+ device_tz: str,
151
+ ) -> QueryPayload:
152
+ """Generate API Query payload to support getting data from Flume API.
153
+
154
+ Args:
155
+ scan_interval (_type_): Interval to scan.
156
+ device_tz (_type_): Time Zone of Flume device.
157
+
158
+ Returns:
159
+ JSON: API Query to retrieve API details.
160
+ """
161
+ datetime_localtime = datetime.now(timezone.utc).astimezone(ZoneInfo(device_tz))
162
+
163
+ queries: List[QuerySpec] = [
164
+ {
165
+ "request_id": "current_interval",
166
+ "bucket": "MIN",
167
+ "since_datetime": format_time(
168
+ (datetime_localtime - scan_interval).replace(second=0),
169
+ ),
170
+ "until_datetime": format_time(datetime_localtime.replace(second=0)),
171
+ "operation": CONST_OPERATION,
172
+ "units": CONST_UNIT_OF_MEASUREMENT,
173
+ },
174
+ {
175
+ "request_id": "today",
176
+ "bucket": "DAY",
177
+ "since_datetime": format_start_today(datetime_localtime),
178
+ "until_datetime": format_time(datetime_localtime),
179
+ "operation": CONST_OPERATION,
180
+ "units": CONST_UNIT_OF_MEASUREMENT,
181
+ },
182
+ {
183
+ "request_id": "week_to_date",
184
+ "bucket": "DAY",
185
+ "since_datetime": format_start_week(datetime_localtime),
186
+ "until_datetime": format_time(datetime_localtime),
187
+ "operation": CONST_OPERATION,
188
+ "units": CONST_UNIT_OF_MEASUREMENT,
189
+ },
190
+ {
191
+ "request_id": "month_to_date",
192
+ "bucket": "MON",
193
+ "since_datetime": format_start_month(datetime_localtime),
194
+ "until_datetime": format_time(datetime_localtime),
195
+ "units": CONST_UNIT_OF_MEASUREMENT,
196
+ },
197
+ {
198
+ "request_id": "last_60_min",
199
+ "bucket": "MIN",
200
+ "since_datetime": format_time(
201
+ datetime_localtime - timedelta(minutes=60),
202
+ ),
203
+ "until_datetime": format_time(datetime_localtime),
204
+ "operation": CONST_OPERATION,
205
+ "units": CONST_UNIT_OF_MEASUREMENT,
206
+ },
207
+ {
208
+ "request_id": "last_24_hrs",
209
+ "bucket": "HR",
210
+ "since_datetime": format_time(datetime_localtime - timedelta(hours=24)),
211
+ "until_datetime": format_time(datetime_localtime),
212
+ "operation": CONST_OPERATION,
213
+ "units": CONST_UNIT_OF_MEASUREMENT,
214
+ },
215
+ {
216
+ "request_id": "last_30_days",
217
+ "bucket": "DAY",
218
+ "since_datetime": format_time(
219
+ datetime_localtime - timedelta(days=30), # noqa: WPS432
220
+ ),
221
+ "until_datetime": format_time(datetime_localtime),
222
+ "operation": CONST_OPERATION,
223
+ "units": CONST_UNIT_OF_MEASUREMENT,
224
+ },
225
+ ]
226
+ return {"queries": queries}
pyflume/devices.py ADDED
@@ -0,0 +1,70 @@
1
+ """Retrieve devices from the Flume API."""
2
+
3
+ from typing import List, Optional, Union
4
+
5
+ from requests import Session
6
+
7
+ from .auth import FlumeAuth, FlumePortalAuth # noqa: WPS300
8
+ from .constants import API_DEVICES_URL, DEFAULT_TIMEOUT # noqa: WPS300
9
+ from .models import Device, modelize # noqa: WPS300
10
+ from .utils import configure_logger, flume_response_error # noqa: WPS300
11
+
12
+ # Configure logging
13
+ LOGGER = configure_logger(__name__)
14
+
15
+
16
+ class FlumeDeviceList:
17
+ """Get Flume Device List from API."""
18
+
19
+ def __init__(
20
+ self,
21
+ flume_auth: Union[FlumeAuth, FlumePortalAuth],
22
+ http_session: Optional[Session] = None,
23
+ timeout: float = DEFAULT_TIMEOUT,
24
+ ) -> None:
25
+ """
26
+
27
+ Initialize the data object.
28
+
29
+ Args:
30
+ flume_auth: Authentication object.
31
+ http_session: Requests Session()
32
+ timeout: Requests timeout for throttling.
33
+
34
+ """
35
+ self._timeout: float = timeout
36
+ self._flume_auth: Union[FlumeAuth, FlumePortalAuth] = flume_auth
37
+
38
+ if http_session is None:
39
+ self._http_session: Session = Session()
40
+ else:
41
+ self._http_session = http_session
42
+
43
+ self.device_list = self.get_devices()
44
+
45
+ def get_devices(self) -> List[Device]:
46
+ """
47
+ Return all available devices from Flume API.
48
+
49
+ Returns:
50
+ Json device list.
51
+
52
+ """
53
+
54
+ url = API_DEVICES_URL.format(user_id=self._flume_auth.user_id)
55
+ query_string = {"user": "true", "location": "true"}
56
+
57
+ response = self._http_session.request(
58
+ "GET",
59
+ url,
60
+ headers=self._flume_auth.authorization_header,
61
+ params=query_string,
62
+ timeout=self._timeout,
63
+ )
64
+
65
+ LOGGER.debug("get_devices Response: %s", response.text) # noqa: WPS323
66
+
67
+ # Check for response errors.
68
+ flume_response_error("Impossible to retreive devices", response)
69
+
70
+ return modelize(response.json()["data"], Device)
pyflume/errors.py ADDED
@@ -0,0 +1,57 @@
1
+ """Exceptions raised by PyFlumeNG."""
2
+
3
+ from typing import Optional
4
+
5
+ from requests import Response
6
+
7
+ from .types import JSONDict, JSONValue
8
+
9
+
10
+ class FlumeError(Exception):
11
+ """Base exception for PyFlumeNG."""
12
+
13
+
14
+ class FlumeAuthError(FlumeError):
15
+ """Raised when authentication or token exchange fails."""
16
+
17
+
18
+ class FlumeCapabilityError(FlumeError):
19
+ """Raised when an auth flow lacks a required API capability."""
20
+
21
+
22
+ class FlumeHTTPError(FlumeError):
23
+ """Raised for a non-successful Flume API response."""
24
+
25
+ def __init__(
26
+ self,
27
+ message: str,
28
+ response: Optional[Response] = None,
29
+ envelope: Optional[JSONDict] = None,
30
+ ) -> None:
31
+ self.message: str = message
32
+ self.response: Optional[Response] = response
33
+ self.envelope: JSONDict = envelope or {}
34
+ self.status_code: Optional[int] = getattr(response, "status_code", None)
35
+ code = self.envelope.get("code")
36
+ self.code: Optional[int] = code if isinstance(code, int) else None
37
+ self.detailed: Optional[JSONValue] = self.envelope.get("detailed")
38
+ detail = self.envelope.get("message") or self.detailed or message
39
+ super().__init__(
40
+ "{0} (HTTP {1}, Flume code {2}): {3}".format(
41
+ message,
42
+ self.status_code,
43
+ self.code,
44
+ detail,
45
+ ),
46
+ )
47
+
48
+
49
+ class FlumeRateLimitError(FlumeHTTPError):
50
+ """Raised when Flume rejects a request because of rate limiting."""
51
+
52
+ @property
53
+ def retry_after(self) -> Optional[str]:
54
+ """Return the server Retry-After value, when provided."""
55
+ if self.response is None:
56
+ return None
57
+ return self.response.headers.get("Retry-After")
pyflume/leak.py ADDED
@@ -0,0 +1,83 @@
1
+ """Retrieve leak notifications from the Flume API."""
2
+
3
+ from typing import List, Optional, Union
4
+
5
+ from requests import Session
6
+
7
+ from .auth import FlumeAuth, FlumePortalAuth # noqa: WPS300
8
+ from .constants import API_LEAK_URL, DEFAULT_TIMEOUT # noqa: WPS300
9
+ from .models import Leak, modelize # noqa: WPS300
10
+ from .types import ResourceId # noqa: WPS300
11
+ from .utils import configure_logger, flume_response_error # noqa: WPS300
12
+
13
+ # Configure logging
14
+ LOGGER = configure_logger(__name__)
15
+
16
+
17
+ class FlumeLeakList:
18
+ """Get Flume Flume Leak Notifications from API."""
19
+
20
+ def __init__( # noqa: WPS211
21
+ self,
22
+ flume_auth: Union[FlumeAuth, FlumePortalAuth],
23
+ device_id: ResourceId,
24
+ http_session: Optional[Session] = None,
25
+ timeout: float = DEFAULT_TIMEOUT,
26
+ read: str = "false",
27
+ ) -> None:
28
+ """
29
+
30
+ Initialize the data object.
31
+
32
+ Args:
33
+ flume_auth: Authentication object.
34
+ device_id: The Device ID to query.
35
+ http_session: Requests Session()
36
+ timeout: Requests timeout for throttling.
37
+ read: state of leak notification list, have they been read, not read.
38
+
39
+ """
40
+ self._timeout: float = timeout
41
+ self._flume_auth: Union[FlumeAuth, FlumePortalAuth] = flume_auth
42
+ self._read: str = read
43
+ self.device_id: ResourceId = device_id
44
+
45
+ if http_session is None:
46
+ self._http_session: Session = Session()
47
+ else:
48
+ self._http_session = http_session
49
+
50
+ self.leak_alert_list = self.get_leaks()
51
+
52
+ def get_leaks(self) -> List[Leak]:
53
+ """Return all leak alerts from devices owned by the user.
54
+
55
+ Returns:
56
+ Returns JSON list of leak notifications.
57
+ """
58
+
59
+ url = API_LEAK_URL.format(
60
+ user_id=self._flume_auth.user_id,
61
+ device_id=self.device_id,
62
+ )
63
+
64
+ query_string = {
65
+ "limit": "50",
66
+ "offset": "0",
67
+ "sort_direction": "ASC",
68
+ "read": self._read,
69
+ }
70
+
71
+ response = self._http_session.request(
72
+ "GET",
73
+ url,
74
+ headers=self._flume_auth.authorization_header,
75
+ params=query_string,
76
+ timeout=self._timeout,
77
+ )
78
+
79
+ LOGGER.debug(f"get_leaks Response: {response.text}")
80
+
81
+ # Check for response errors.
82
+ flume_response_error("Impossible to retrieve leak alerts", response)
83
+ return modelize(response.json()["data"], Leak)