airbeld-api-sdk 0.1.1__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.
- airbeld/__init__.py +31 -0
- airbeld/auth.py +85 -0
- airbeld/client.py +186 -0
- airbeld/exceptions.py +49 -0
- airbeld/models.py +91 -0
- airbeld/py.typed +0 -0
- airbeld/version.py +8 -0
- airbeld_api_sdk-0.1.1.dist-info/METADATA +240 -0
- airbeld_api_sdk-0.1.1.dist-info/RECORD +11 -0
- airbeld_api_sdk-0.1.1.dist-info/WHEEL +4 -0
- airbeld_api_sdk-0.1.1.dist-info/licenses/LICENSE +22 -0
airbeld/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Airbeld API SDK - Async Python client for air quality devices."""
|
|
2
|
+
|
|
3
|
+
from .auth import async_login
|
|
4
|
+
from .client import AirbeldClient
|
|
5
|
+
from .exceptions import AirbeldError, ApiError, AuthError, NetworkError, RateLimitError
|
|
6
|
+
from .models import (
|
|
7
|
+
Device,
|
|
8
|
+
DeviceSummary,
|
|
9
|
+
TelemetryBundle,
|
|
10
|
+
TelemetryMetric,
|
|
11
|
+
TelemetryValue,
|
|
12
|
+
TokenSet,
|
|
13
|
+
)
|
|
14
|
+
from .version import __version__
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"AirbeldClient",
|
|
18
|
+
"AirbeldError",
|
|
19
|
+
"ApiError",
|
|
20
|
+
"AuthError",
|
|
21
|
+
"Device",
|
|
22
|
+
"DeviceSummary",
|
|
23
|
+
"NetworkError",
|
|
24
|
+
"RateLimitError",
|
|
25
|
+
"TelemetryBundle",
|
|
26
|
+
"TelemetryMetric",
|
|
27
|
+
"TelemetryValue",
|
|
28
|
+
"TokenSet",
|
|
29
|
+
"__version__",
|
|
30
|
+
"async_login",
|
|
31
|
+
]
|
airbeld/auth.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Authentication utilities for the Airbeld API."""
|
|
2
|
+
|
|
3
|
+
from urllib.parse import urljoin
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from .exceptions import ApiError, AuthError, NetworkError, RateLimitError
|
|
8
|
+
from .models import TokenSet
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def async_login(
|
|
12
|
+
base_url: str,
|
|
13
|
+
email: str,
|
|
14
|
+
password: str,
|
|
15
|
+
*,
|
|
16
|
+
timeout: float = 10.0,
|
|
17
|
+
) -> TokenSet:
|
|
18
|
+
"""Authenticate with email/password and get access token.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
base_url: Base URL for the API (e.g., "https://api.airbeld.com")
|
|
22
|
+
email: User email address
|
|
23
|
+
password: User password
|
|
24
|
+
timeout: Request timeout in seconds (default: 10.0)
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
TokenSet containing access_token, refresh_token, expires_in, token_type
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
AuthError: Authentication failed (401)
|
|
31
|
+
ApiError: Other API errors (400, 429, 5xx)
|
|
32
|
+
NetworkError: Network connectivity issues
|
|
33
|
+
"""
|
|
34
|
+
url = urljoin(base_url.rstrip("/") + "/api/v1/", "auth/token/")
|
|
35
|
+
|
|
36
|
+
payload: dict[str, str] = {
|
|
37
|
+
"email": email,
|
|
38
|
+
"password": password,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
42
|
+
try:
|
|
43
|
+
response = await client.post(
|
|
44
|
+
url,
|
|
45
|
+
json=payload,
|
|
46
|
+
headers={
|
|
47
|
+
"User-Agent": "airbeld-api-sdk/0.0.0",
|
|
48
|
+
"Content-Type": "application/json",
|
|
49
|
+
},
|
|
50
|
+
)
|
|
51
|
+
_handle_http_errors(response)
|
|
52
|
+
token_data = response.json()
|
|
53
|
+
return TokenSet(**token_data)
|
|
54
|
+
|
|
55
|
+
except httpx.NetworkError as e:
|
|
56
|
+
raise NetworkError(f"Network error: {e}") from e
|
|
57
|
+
except httpx.TimeoutException as e:
|
|
58
|
+
raise NetworkError(f"Request timeout: {e}") from e
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _handle_http_errors(response: httpx.Response) -> None:
|
|
62
|
+
"""Handle HTTP error responses."""
|
|
63
|
+
if response.is_success:
|
|
64
|
+
return
|
|
65
|
+
|
|
66
|
+
status_code = response.status_code
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
error_data = response.json()
|
|
70
|
+
error_message = error_data.get("error", f"HTTP {status_code}")
|
|
71
|
+
except Exception:
|
|
72
|
+
error_message = f"HTTP {status_code}"
|
|
73
|
+
|
|
74
|
+
if status_code == 401:
|
|
75
|
+
raise AuthError(error_message)
|
|
76
|
+
elif status_code == 429:
|
|
77
|
+
retry_after = response.headers.get("Retry-After")
|
|
78
|
+
retry_seconds = int(retry_after) if retry_after else None
|
|
79
|
+
raise RateLimitError(error_message, retry_after=retry_seconds)
|
|
80
|
+
else:
|
|
81
|
+
raise ApiError(
|
|
82
|
+
error_message,
|
|
83
|
+
status_code=status_code,
|
|
84
|
+
response_body=response.text,
|
|
85
|
+
)
|
airbeld/client.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Async HTTP client for the Airbeld API."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import Any
|
|
6
|
+
from urllib.parse import urljoin
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from tenacity import (
|
|
10
|
+
retry,
|
|
11
|
+
retry_if_exception_type,
|
|
12
|
+
stop_after_attempt,
|
|
13
|
+
wait_exponential,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from .exceptions import ApiError, AuthError, NetworkError, RateLimitError
|
|
17
|
+
from .models import DeviceSummary, TelemetryBundle
|
|
18
|
+
from .version import get_user_agent
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AirbeldClient:
|
|
22
|
+
"""Async HTTP client for the Airbeld API."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
token: str,
|
|
27
|
+
base_url: str = "https://api.airbeld.com",
|
|
28
|
+
timeout: float = 10.0,
|
|
29
|
+
) -> None:
|
|
30
|
+
"""Initialize the Airbeld API client.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
token: JWT access token for authentication
|
|
34
|
+
base_url: Base URL for the API (default: https://api.airbeld.com)
|
|
35
|
+
timeout: Request timeout in seconds (default: 10.0)
|
|
36
|
+
"""
|
|
37
|
+
self.base_url = base_url.rstrip("/")
|
|
38
|
+
self.api_prefix = "/api/v1"
|
|
39
|
+
self._client = httpx.AsyncClient(
|
|
40
|
+
timeout=timeout,
|
|
41
|
+
headers={
|
|
42
|
+
"Authorization": f"Bearer {token}",
|
|
43
|
+
"User-Agent": get_user_agent(),
|
|
44
|
+
},
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
async def __aenter__(self) -> "AirbeldClient":
|
|
48
|
+
"""Async context manager entry."""
|
|
49
|
+
return self
|
|
50
|
+
|
|
51
|
+
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
52
|
+
"""Async context manager exit."""
|
|
53
|
+
del exc_type, exc_val, exc_tb # Unused parameters
|
|
54
|
+
await self.aclose()
|
|
55
|
+
|
|
56
|
+
async def aclose(self) -> None:
|
|
57
|
+
"""Close the underlying HTTP client."""
|
|
58
|
+
await self._client.aclose()
|
|
59
|
+
|
|
60
|
+
def set_token(self, new_token: str) -> None:
|
|
61
|
+
"""Update the authorization token at runtime.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
new_token: New JWT access token for authentication
|
|
65
|
+
"""
|
|
66
|
+
self._client.headers["Authorization"] = f"Bearer {new_token}"
|
|
67
|
+
|
|
68
|
+
def _build_url(self, path: str) -> str:
|
|
69
|
+
"""Build full URL from API path."""
|
|
70
|
+
return urljoin(f"{self.base_url}{self.api_prefix}/", path.lstrip("/"))
|
|
71
|
+
|
|
72
|
+
@retry(
|
|
73
|
+
stop=stop_after_attempt(3),
|
|
74
|
+
wait=wait_exponential(multiplier=1, min=1, max=10),
|
|
75
|
+
retry=retry_if_exception_type((NetworkError, RateLimitError)),
|
|
76
|
+
reraise=True,
|
|
77
|
+
)
|
|
78
|
+
async def _request(
|
|
79
|
+
self,
|
|
80
|
+
method: str,
|
|
81
|
+
path: str,
|
|
82
|
+
**kwargs: Any,
|
|
83
|
+
) -> httpx.Response:
|
|
84
|
+
"""Make HTTP request with retries and error handling."""
|
|
85
|
+
url = self._build_url(path)
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
response = await self._client.request(method, url, **kwargs)
|
|
89
|
+
self._handle_http_errors(response)
|
|
90
|
+
return response
|
|
91
|
+
except httpx.NetworkError as e:
|
|
92
|
+
raise NetworkError(f"Network error: {e}") from e
|
|
93
|
+
except httpx.TimeoutException as e:
|
|
94
|
+
raise NetworkError(f"Request timeout: {e}") from e
|
|
95
|
+
except RateLimitError as e:
|
|
96
|
+
# Handle Retry-After header for rate limiting
|
|
97
|
+
if e.retry_after:
|
|
98
|
+
time.sleep(e.retry_after)
|
|
99
|
+
raise
|
|
100
|
+
|
|
101
|
+
def _handle_http_errors(self, response: httpx.Response) -> None:
|
|
102
|
+
"""Handle HTTP error responses."""
|
|
103
|
+
if response.is_success:
|
|
104
|
+
return
|
|
105
|
+
|
|
106
|
+
status_code = response.status_code
|
|
107
|
+
|
|
108
|
+
try:
|
|
109
|
+
error_data = response.json()
|
|
110
|
+
error_message = error_data.get("error", f"HTTP {status_code}")
|
|
111
|
+
except Exception:
|
|
112
|
+
error_message = f"HTTP {status_code}"
|
|
113
|
+
|
|
114
|
+
if status_code in (401, 403):
|
|
115
|
+
raise AuthError(error_message)
|
|
116
|
+
elif status_code == 429:
|
|
117
|
+
retry_after = response.headers.get("Retry-After")
|
|
118
|
+
retry_seconds = int(retry_after) if retry_after else None
|
|
119
|
+
raise RateLimitError(error_message, retry_after=retry_seconds)
|
|
120
|
+
else:
|
|
121
|
+
raise ApiError(
|
|
122
|
+
error_message,
|
|
123
|
+
status_code=status_code,
|
|
124
|
+
response_body=response.text,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
async def async_get_devices(self) -> list[DeviceSummary]:
|
|
128
|
+
"""Get list of all devices.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
List of device summary objects
|
|
132
|
+
|
|
133
|
+
Raises:
|
|
134
|
+
AuthError: Authentication failed (401/403)
|
|
135
|
+
ApiError: Other API errors (4xx/5xx)
|
|
136
|
+
NetworkError: Network connectivity issues
|
|
137
|
+
"""
|
|
138
|
+
response = await self._request("GET", "devices/")
|
|
139
|
+
devices_data = response.json()
|
|
140
|
+
return [DeviceSummary(**device) for device in devices_data]
|
|
141
|
+
|
|
142
|
+
async def async_get_readings_by_date(
|
|
143
|
+
self,
|
|
144
|
+
device_id: int,
|
|
145
|
+
start: datetime,
|
|
146
|
+
end: datetime,
|
|
147
|
+
sensors: list[str] | None = None,
|
|
148
|
+
aggregate: str | None = None,
|
|
149
|
+
) -> TelemetryBundle:
|
|
150
|
+
"""Get telemetry readings for a device within a date range.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
device_id: Device ID (int)
|
|
154
|
+
start: Start datetime (with timezone)
|
|
155
|
+
end: End datetime (with timezone)
|
|
156
|
+
sensors: Optional list of sensor keys to filter (e.g., ["temperature", "pm2p5"])
|
|
157
|
+
aggregate: Optional aggregation level ("hourly" or "daily")
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
TelemetryBundle with sensor readings
|
|
161
|
+
|
|
162
|
+
Raises:
|
|
163
|
+
AuthError: Authentication failed (401/403)
|
|
164
|
+
ApiError: API errors including 404 (device not found), 413 (range too large)
|
|
165
|
+
RateLimitError: Rate limit exceeded (429)
|
|
166
|
+
NetworkError: Network connectivity issues
|
|
167
|
+
"""
|
|
168
|
+
# Build query parameters
|
|
169
|
+
params: dict[str, str] = {
|
|
170
|
+
"start": start.isoformat(),
|
|
171
|
+
"end": end.isoformat(),
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if sensors:
|
|
175
|
+
params["sensors"] = ",".join(sensors)
|
|
176
|
+
|
|
177
|
+
if aggregate:
|
|
178
|
+
params["aggregate"] = aggregate
|
|
179
|
+
|
|
180
|
+
response = await self._request(
|
|
181
|
+
"GET", f"devices/{device_id}/readings_by_date/", params=params
|
|
182
|
+
)
|
|
183
|
+
readings_data = response.json()
|
|
184
|
+
|
|
185
|
+
# Create TelemetryBundle with device_uid for compatibility
|
|
186
|
+
return TelemetryBundle(device_uid=str(device_id), **readings_data)
|
airbeld/exceptions.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Custom exceptions for the Airbeld API SDK."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AirbeldError(Exception):
|
|
5
|
+
"""Base exception for all Airbeld SDK errors."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, message: str) -> None:
|
|
8
|
+
super().__init__(message)
|
|
9
|
+
self.message = message
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AuthError(AirbeldError):
|
|
13
|
+
"""Authentication or authorization error (401/403)."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str = "Authentication failed") -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RateLimitError(AirbeldError):
|
|
20
|
+
"""Rate limit exceeded error (429)."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
message: str = "Rate limit exceeded",
|
|
25
|
+
retry_after: int | None = None,
|
|
26
|
+
) -> None:
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.retry_after = retry_after
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ApiError(AirbeldError):
|
|
32
|
+
"""API error for other 4xx/5xx HTTP status codes."""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
message: str,
|
|
37
|
+
status_code: int,
|
|
38
|
+
response_body: str | None = None,
|
|
39
|
+
) -> None:
|
|
40
|
+
super().__init__(message)
|
|
41
|
+
self.status_code = status_code
|
|
42
|
+
self.response_body = response_body
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class NetworkError(AirbeldError):
|
|
46
|
+
"""Network connectivity or timeout error."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, message: str = "Network error occurred") -> None:
|
|
49
|
+
super().__init__(message)
|
airbeld/models.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Data models for the Airbeld API SDK."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TokenSet(BaseModel):
|
|
10
|
+
"""Authentication token set from POST /api/v1/auth/token/ (camelCase wire format)."""
|
|
11
|
+
|
|
12
|
+
access_token: str = Field(alias="accessToken")
|
|
13
|
+
refresh_token: str = Field(alias="refreshToken")
|
|
14
|
+
expires_in: int = Field(alias="expiresIn")
|
|
15
|
+
token_type: str = Field(alias="tokenType")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DeviceSummary(BaseModel):
|
|
19
|
+
"""Device summary information from GET /api/v1/devices/ (camelCase wire format)."""
|
|
20
|
+
|
|
21
|
+
uid: str = Field(..., min_length=1, max_length=255)
|
|
22
|
+
id: int
|
|
23
|
+
name: str
|
|
24
|
+
display_name: str | None = Field(default=None, alias="displayName")
|
|
25
|
+
description: str
|
|
26
|
+
type: str | None
|
|
27
|
+
is_locked: bool = Field(alias="isLocked")
|
|
28
|
+
status: Literal["online", "offline"]
|
|
29
|
+
sector: str | None
|
|
30
|
+
sector_id: int | None = Field(alias="sectorId")
|
|
31
|
+
location: str | None
|
|
32
|
+
location_id: int | None = Field(alias="locationId")
|
|
33
|
+
timezone: str
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Device(BaseModel):
|
|
37
|
+
"""Device information from the Airbeld API."""
|
|
38
|
+
|
|
39
|
+
uid: str = Field(..., min_length=1, max_length=255)
|
|
40
|
+
name: str
|
|
41
|
+
display_name: str | None = None
|
|
42
|
+
device_type: str
|
|
43
|
+
status: Literal["online", "offline"]
|
|
44
|
+
is_locked: bool
|
|
45
|
+
hardware_model: str | None = None
|
|
46
|
+
hardware_version: str | None = None
|
|
47
|
+
manufacturer: str | None = None
|
|
48
|
+
serial_number: str | None = None
|
|
49
|
+
sector_id: str | None = None
|
|
50
|
+
sector_name: str | None = None
|
|
51
|
+
description: str | None = None
|
|
52
|
+
created_at: datetime
|
|
53
|
+
updated_at: datetime
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class TelemetryValue(BaseModel):
|
|
57
|
+
"""A single telemetry reading with timestamp."""
|
|
58
|
+
|
|
59
|
+
timestamp: datetime
|
|
60
|
+
value: float | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class TelemetryMetric(BaseModel):
|
|
64
|
+
"""Telemetry metric containing metadata and values."""
|
|
65
|
+
|
|
66
|
+
name: str
|
|
67
|
+
display_name: str | None = None
|
|
68
|
+
unit: str
|
|
69
|
+
description: str | None = None
|
|
70
|
+
values: list[TelemetryValue] = Field(default_factory=list)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class TelemetryBundle(BaseModel):
|
|
74
|
+
"""Bundle of telemetry sensors for a device."""
|
|
75
|
+
|
|
76
|
+
device_uid: str
|
|
77
|
+
sensors: dict[str, TelemetryMetric] = Field(default_factory=dict)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def pm2_5(self) -> TelemetryMetric | None:
|
|
81
|
+
"""Access PM 2.5 metric with Pythonic naming."""
|
|
82
|
+
return self.sensors.get("pm2p5")
|
|
83
|
+
|
|
84
|
+
def get_latest_value(self, metric_name: str) -> float | None:
|
|
85
|
+
"""Get the latest value for a specific metric."""
|
|
86
|
+
metric = self.sensors.get(metric_name)
|
|
87
|
+
if not metric or not metric.values:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
latest = max(metric.values, key=lambda v: v.timestamp)
|
|
91
|
+
return latest.value
|
airbeld/py.typed
ADDED
|
File without changes
|
airbeld/version.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: airbeld-api-sdk
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Async Python SDK for the Airbeld backend
|
|
5
|
+
Project-URL: Changelog, https://github.com/Embio-Diagnostics/airbeld-api-sdk/blob/main/CHANGELOG.md
|
|
6
|
+
Project-URL: Documentation, https://github.com/Embio-Diagnostics/airbeld-api-sdk/blob/main/README.md
|
|
7
|
+
Project-URL: Homepage, https://github.com/Embio-Diagnostics/airbeld-api-sdk
|
|
8
|
+
Project-URL: Issues, https://github.com/Embio-Diagnostics/airbeld-api-sdk/issues
|
|
9
|
+
Project-URL: Repository, https://github.com/Embio-Diagnostics/airbeld-api-sdk
|
|
10
|
+
Author-email: Embio Diagnostics Ltd <l.dougiakis@embiodiagnostics.eu>
|
|
11
|
+
License: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: air-quality,airbeld,home-assistant
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: httpx>=0.28.1
|
|
20
|
+
Requires-Dist: pydantic>=2.11.7
|
|
21
|
+
Requires-Dist: tenacity>=9.1.2
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: httpx>=0.27; extra == 'dev'
|
|
24
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
25
|
+
Requires-Dist: pydantic>=2.7; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
29
|
+
Requires-Dist: tenacity>=8.2; extra == 'dev'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# Airbeld Python SDK
|
|
33
|
+
|
|
34
|
+
Async Python SDK for the Airbeld API, providing access to air quality devices and telemetry data.
|
|
35
|
+
|
|
36
|
+
> If you want to **contribute**, read [CONTRIBUTING](CONTRIBUTING.md) and [DEVELOPER](DEVELOPER.md).
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# Using pip
|
|
44
|
+
pip install airbeld-api-sdk
|
|
45
|
+
|
|
46
|
+
# Using uv (recommended)
|
|
47
|
+
uv add airbeld-api-sdk
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Examples
|
|
51
|
+
|
|
52
|
+
### Environment Variables
|
|
53
|
+
|
|
54
|
+
Set these environment variables for the examples:
|
|
55
|
+
|
|
56
|
+
- `AIRBELD_API_BASE`: API base URL (default: `https://api.airbeld.com`)
|
|
57
|
+
- `AIRBELD_API_TOKEN`: JWT access token for authentication
|
|
58
|
+
|
|
59
|
+
### Quickstart Example
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import asyncio
|
|
63
|
+
import os
|
|
64
|
+
from datetime import datetime, timedelta, timezone
|
|
65
|
+
from airbeld import AirbeldClient
|
|
66
|
+
|
|
67
|
+
async def main():
|
|
68
|
+
# Initialize client (JWT token obtained outside SDK)
|
|
69
|
+
base_url = os.environ.get("AIRBELD_API_BASE", "https://api.airbeld.com")
|
|
70
|
+
token = os.environ["AIRBELD_API_TOKEN"]
|
|
71
|
+
|
|
72
|
+
async with AirbeldClient(token=token, base_url=base_url) as client:
|
|
73
|
+
# Get all devices
|
|
74
|
+
devices = await client.async_get_devices()
|
|
75
|
+
print(f"Found {len(devices)} devices")
|
|
76
|
+
|
|
77
|
+
if devices:
|
|
78
|
+
device = devices[0]
|
|
79
|
+
print(f"Device: {device.name} ({device.status})")
|
|
80
|
+
|
|
81
|
+
# Get recent telemetry readings
|
|
82
|
+
end = datetime.now(timezone.utc)
|
|
83
|
+
start = end - timedelta(hours=1)
|
|
84
|
+
|
|
85
|
+
readings = await client.async_get_readings_by_date(
|
|
86
|
+
device_id=device.id,
|
|
87
|
+
start=start,
|
|
88
|
+
end=end,
|
|
89
|
+
sensors=["temperature", "pm2p5"] # Optional sensor filter
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
# Print latest temperature reading
|
|
93
|
+
if "temperature" in readings.sensors:
|
|
94
|
+
latest_temp = readings.get_latest_value("temperature")
|
|
95
|
+
print(f"Latest temperature: {latest_temp}°C")
|
|
96
|
+
|
|
97
|
+
if __name__ == "__main__":
|
|
98
|
+
asyncio.run(main())
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
**Note:** JWT token acquisition happens outside the SDK. The SDK only handles API requests with a ready token.
|
|
102
|
+
|
|
103
|
+
## Authentication Options
|
|
104
|
+
|
|
105
|
+
The SDK supports two authentication paths depending on your use case:
|
|
106
|
+
|
|
107
|
+
### Home Assistant Integration
|
|
108
|
+
|
|
109
|
+
For Home Assistant users, authentication is handled by the integration:
|
|
110
|
+
|
|
111
|
+
- Home Assistant performs OAuth2 flow automatically
|
|
112
|
+
- SDK receives a ready JWT token from the integration
|
|
113
|
+
- See [docs/home-assistant-auth.md](docs/home-assistant-auth.md) for details
|
|
114
|
+
|
|
115
|
+
### Standalone Applications (CLI, Scripts, etc.)
|
|
116
|
+
|
|
117
|
+
For standalone applications, use the built-in authentication:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
import asyncio
|
|
121
|
+
import os
|
|
122
|
+
from airbeld import async_login, AirbeldClient
|
|
123
|
+
|
|
124
|
+
async def main():
|
|
125
|
+
# Authenticate with email/password
|
|
126
|
+
token_set = await async_login(
|
|
127
|
+
base_url="https://api.airbeld.com",
|
|
128
|
+
email=os.environ["AIRBELD_USER_EMAIL"],
|
|
129
|
+
password=os.environ["AIRBELD_USER_PASSWORD"]
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# Create client with access token
|
|
133
|
+
async with AirbeldClient(token=token_set.access_token) as client:
|
|
134
|
+
# List devices
|
|
135
|
+
devices = await client.async_get_devices()
|
|
136
|
+
print(f"Found {len(devices)} devices:")
|
|
137
|
+
|
|
138
|
+
for device in devices:
|
|
139
|
+
print(f" - {device.name} ({device.status})")
|
|
140
|
+
|
|
141
|
+
if __name__ == "__main__":
|
|
142
|
+
asyncio.run(main())
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
**⚠️ Security Warning:** Never commit real credentials or tokens to version control. Use environment variables or secure secret storage systems.
|
|
146
|
+
|
|
147
|
+
### Token Management
|
|
148
|
+
|
|
149
|
+
For applications requiring token refresh or runtime token updates:
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
# Update token at runtime
|
|
153
|
+
client.set_token(new_token)
|
|
154
|
+
|
|
155
|
+
# Or use refresh token (if implemented)
|
|
156
|
+
new_token_set = await async_login(...)
|
|
157
|
+
client.set_token(new_token_set.access_token)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
## Development
|
|
163
|
+
|
|
164
|
+
### Installation
|
|
165
|
+
|
|
166
|
+
Using uv (recommended):
|
|
167
|
+
```bash
|
|
168
|
+
# Clone the repository
|
|
169
|
+
git clone https://github.com/Embio-Diagnostics/airbeld-api-sdk.git
|
|
170
|
+
cd airbeld-api-sdk
|
|
171
|
+
|
|
172
|
+
# Create virtual environment and install dependencies
|
|
173
|
+
uv sync
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Using pip:
|
|
177
|
+
```bash
|
|
178
|
+
# Clone the repository
|
|
179
|
+
git clone https://github.com/Embio-Diagnostics/airbeld-api-sdk.git
|
|
180
|
+
cd airbeld-api-sdk
|
|
181
|
+
|
|
182
|
+
# Create and activate virtual environment
|
|
183
|
+
python -m venv .venv
|
|
184
|
+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
|
185
|
+
|
|
186
|
+
# Install package with dev dependencies
|
|
187
|
+
pip install -e ".[dev]"
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Running Tests
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
# Using uv
|
|
194
|
+
uv run pytest
|
|
195
|
+
|
|
196
|
+
# Or with pip
|
|
197
|
+
pytest
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Linting and Formatting
|
|
201
|
+
|
|
202
|
+
```bash
|
|
203
|
+
# Check code style
|
|
204
|
+
uv run ruff check .
|
|
205
|
+
|
|
206
|
+
# Format code
|
|
207
|
+
uv run ruff format .
|
|
208
|
+
|
|
209
|
+
# Or with pip
|
|
210
|
+
ruff check .
|
|
211
|
+
ruff format .
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Type Checking
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
# Using uv
|
|
218
|
+
uv run mypy src
|
|
219
|
+
|
|
220
|
+
# Or with pip
|
|
221
|
+
mypy src
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### Building the Package
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
# Using uv
|
|
228
|
+
uv build
|
|
229
|
+
|
|
230
|
+
# Or with pip
|
|
231
|
+
python -m build
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
## Resources
|
|
237
|
+
|
|
238
|
+
- **Contributing:** See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines
|
|
239
|
+
- **Changelog:** See [CHANGELOG.md](CHANGELOG.md) for version history
|
|
240
|
+
- **License:** This project is licensed under the MIT License - see [LICENSE](LICENSE) file for details
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
airbeld/__init__.py,sha256=msj0orXHEhJaayMiAFnSbFu8zxfHXMXmz_IjcbeN_Ac,674
|
|
2
|
+
airbeld/auth.py,sha256=DEY2LfSmHHswPtCgSBkooGlMykD_mJuVGyPk6rKAfkc,2513
|
|
3
|
+
airbeld/client.py,sha256=Ryv2PfqIyxy7UumZLteD-s3zQcnawYflmZZ2IQKhyMs,6078
|
|
4
|
+
airbeld/exceptions.py,sha256=dgvmyzfZn-TEPOIteRNAXqeOdoKhZpjZKrIPP2k0mnE,1270
|
|
5
|
+
airbeld/models.py,sha256=QvLQTg9FUTa_fKxqH6uFbiurzEwt-IlEr7qqGPd4R6I,2682
|
|
6
|
+
airbeld/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
airbeld/version.py,sha256=dBxpSmZepVzyDbDf1BL6tGhZBnC1ZJRx9iwj-GLbD6Q,199
|
|
8
|
+
airbeld_api_sdk-0.1.1.dist-info/METADATA,sha256=dF_3iVvF2uY8y1LlWvzOIliI-mpX2bQO6U4JHtrY3Is,6330
|
|
9
|
+
airbeld_api_sdk-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
10
|
+
airbeld_api_sdk-0.1.1.dist-info/licenses/LICENSE,sha256=4iMOLpcFAyaCUTSSg_VBobqEJuQD_GdNlCIEcgA1x5c,1095
|
|
11
|
+
airbeld_api_sdk-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Airbeld
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice (including the next
|
|
13
|
+
paragraph) shall be included in all copies or substantial portions of the
|
|
14
|
+
Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
|
19
|
+
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
|
22
|
+
IN THE SOFTWARE.
|