Download tasks/data/forward/ahayworth__python_awair.683cb06/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 73.4 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/ahayworth__python_awair.683cb06/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/ahayworth__python_awair.683cb06/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/ahayworth__python_awair.683cb06/instruction.md
ahayworth/python_awair
Project Overview
python_awair is an asynchronous, typed Python client library for the Awair REST API, the cloud service behind Awair's line of indoor air-quality monitors. Built on asyncio and aiohttp, it exists primarily to support the Home Assistant integration for Awair devices, and it deliberately scopes itself to the API surface that integration needs: read-only access to the 'user' portion of the Awair API. Applications authenticate with an access token from the Awair developer console (supplied directly or via a pluggable authenticator that provides an HTTP Bearer token) and can then list the Awair devices on an account, retrieve user information, and query sensor readings over various timeframes. Device metadata and measurements are returned as objects, and each device offers query methods for its latest reading plus five-minute, fifteen-minute, and raw datapoint samplings with configurable bounds and ordering. The library also covers both cloud-connected devices and local devices reached at an on-network IP or DNS address. Out of scope are the device API, the organization API, and device management such as changing a device's display. Architecturally, the small package centers on an entry Awair class wrapping an AwairClient, which performs authenticated HTTP requests and translates HTTP statuses and API error payloads into a dedicated exception hierarchy (auth, rate-limit, query, and not-found errors); voluptuous validates response payloads, which become models for devices, users, indices, sensors, and air data. The project is in maintenance mode, packaged with Poetry as python-awair on PyPI, documented with Sphinx on Read the Docs, and developed with tox running pytest, linters, and mypy.
Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.
Submission Constraints (read carefully — the evaluation depends on these)
This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.py/conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.
Install / Reconstruction Contract
Follow this contract before implementing the documented APIs:
- Project root:
/workspace/repoat runtime; the submitted repository root is.. - Package/distribution name:
python-awair - Package roots:
. - Install strategy:
editable-install - Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- Provision commands:
python3 -m pip install -U pip 'setuptools<82' wheel python3 -m pip install poetry-core ( programgen_install_report="$(mktemp)" trap 'rm -f "$programgen_install_report"' EXIT SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" python3 -c 'import json,subprocess,sys; report=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"')); requirements=list(dict.fromkeys(requirement for item in report.get('"'"'install'"'"', []) for requirement in item.get('"'"'metadata'"'"', {}).get('"'"'requires_dist'"'"', []))); subprocess.run([sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None' "$programgen_install_report" ) - Runtime setup:
{ [ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; }; SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; } - Project root for installation:
. - Build-version environment:
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0,PDM_BUILD_SCM_VERSION=0.0.0,POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0,UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 - Test directory:
tests - Test command:
bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_python_awair.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_python_awair.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_python_awair.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?' - Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.
Environment & Project Structure
- Language: python
- Build system: python
- Test command:
bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_python_awair.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_python_awair.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_python_awair.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?
Project Directory Structure
.coveragerc
.flake8
.github/workflows/ci.yaml
.gitignore
.isort.cfg
.lvimrc
.pylintrc
.readthedocs.yml
LICENSE
README.md
docs/Makefile
docs/conf.py
docs/examples.rst
docs/index.rst
docs/python_awair.rst
docs/requirements.txt
examples/local.py
examples/remote.py
mypy.ini
poetry.lock
pyproject.toml
python_awair/__init__.py
python_awair/air_data.py
python_awair/attrdict.py
python_awair/auth.py
python_awair/client.py
python_awair/const.py
python_awair/devices.py
python_awair/exceptions.py
python_awair/indices.py
python_awair/sensors.py
python_awair/user.py
API Usage Guide
Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.
Capability: Asynchronous Awair API client construction and configuration
What this capability provides
Awair and AwairLocal are the only entry points an application instantiates. Both take an aiohttp ClientSession (never created or closed for you) and build an AwairClient synchronously inside __init__, exposed as the instance attribute client. No network traffic happens at construction; every request is issued later, per awaited method call, as an authenticated GET through that one client.
Construction rules and precedence
Awair(session, access_token=None, authenticator=None): a suppliedauthenticatoralways wins. Otherwise a truthyaccess_tokenis wrapped inAccessTokenAuth. If neither is supplied, construction raisesAwairError("No authentication supplied!")immediately (the literal string is the extra message appended to the base message). Passingaccess_token=""counts as "not supplied" - empty strings are falsy.AwairLocal(session, device_addrs): the address list must be non-empty or construction raisesAwairError("No local Awair device addresses supplied!"). The client is built asAwairClient(AccessTokenAuth(""), session)- an intentionally empty bearer token - because local devices do not validate credentials, yet every request still carries anAuthorization: Bearerheader. Addresses must be bare hosts (192.168.1.42,device.local, optionallyhost:port); the library prependshttp://and appends/settings/config/dataitself, so an address containing a scheme yields a malformed URL. The list is stored by reference (no copy) and re-read on everydevices()call, so post-construction mutation of the caller's list is honored (see State, ordering, edge cases).- A custom authenticator is anything whose
get_bearer_token()is awaitable and returns the token string; subclassingAwairAuth(ABC with an abstract async method) is the typed route. It is consulted fresh on every request, so rotating tokens work without rebuilding the client.
Request pipeline (shared by both entry classes)
AwairClient.query(url) resolves headers per call (Authorization: Bearer <token>, Content-Type: application/json), issues session.get(url, headers), and maps failures: 400 -> QueryError, 401/403 -> AuthError, 404 -> NotFoundError, 429 -> RatelimitError, any other non-200 -> base AwairError. On HTTP 200, a text/html content type is read as text and parsed with json.loads (an Awair Omni Ethernet-backpack quirk); anything else uses resp.json(). After parsing, a GraphQL-style errors array in the body is still honored: each entry's message is read directly (error["message"]) for the case-sensitive Too many requests substring check, so an entry lacking a message key raises a raw KeyError there, not an AwairError - the error.get("message", "Unknown error") default that follows is unreachable dead code. If no entry trips the rate-limit check, the entry messages are joined with ", " and raised as AwairError. An empty errors list raises nothing. Success returns the parsed JSON verbatim (Any), which the entry classes feed straight into model constructors.
Realistic workflows
- Cloud:
user = await Awair(session, token).user()GETsconst.USER_URLand wraps the body asAwairUser(client=..., attributes=response); the user retains that client, soawait user.devices()hitsconst.DEVICE_URLwith identical authentication. "Self" is defined by the credential: with a custom authenticator (OAuth, a proxy, tests) the returned user is whatever that bearer token identifies. - Local:
await AwairLocal(session, addrs).devices()fans out one GET per address concurrently viaasyncio.gatherand returnsAwairLocalDeviceobjects in the same order as the address list as it stands atdevices()call time - the list is consulted live, not snapshotted at construction. Any single failing address raises out of the gather.
const and AttrDict: the shared foundation
const is a flat contract of exact values: BASE_URL = "https://developer-apis.awair.is/v1", USER_URL = BASE_URL + "/users/self", DEVICE_URL = USER_URL + "/devices", DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ", SENSOR_TO_ALIAS (temp->temperature, humid->humidity, co2->carbon_dioxide, voc->volatile_organic_compounds, pm25->particulate_matter_2_5, lux->illuminance, spl_a->sound_pressure_level), and AWAIR_MODELS (awair->Awair, awair-element->Awair Element, awair-glow->Awair Glow, awair-glow-c->Awair Glow C, awair-mint->Awair Mint, awair-omni->Awair Omni, awair-r2->Awair 2nd Edition).
AttrDict subclasses Dict[str, Any] and is the base of the sensor/index models. __getattr__ returns self[name] or raises AttributeError - never KeyError (so hasattr/getattr defaults behave); that AttributeError-on-miss behavior applies only to reads. __setattr__ adds or overwrites dict items, including brand-new keys, while __delattr__ delegates to dict deletion, so del obj.missing raises KeyError, not AttributeError. __dir__ lists keys. Alias renaming happens only in __init__: constructing with {"temp": 21} stores temperature, but a later d.temp = 30 stores the literal key temp unrenamed. Construction copies the input mapping, so later mutation of the source dict does not affect the model.
State, ordering, edge cases
- Missing-credential validation raises synchronously at construction (
AwairErrorwhen no authenticator and no truthy token); credential rejection by the server still surfaces asAuthError(401/403) per awaited request, not at construction. - Authenticator beats token when both are given; the unchosen token is ignored entirely.
AwairLocalkeepsdevice_addrsas a live reference and re-reads it inside eachdevices()call, so post-construction mutation (append, clear, reorder) changes the fan-out; the non-empty check runs only in__init__, so a list emptied after successful construction still issues a request set - an empty gather returns[]. "Input order" means list state atdevices()call time, not construction time.- The errors-array scan runs even on a 200;
Too many requestsis a case-sensitive substring check that reads each entry'smessagekey directly, so an entry without that key raisesKeyErrorbefore any default can apply. - On a 200, the HTML-content-type fallback reads the body as text and parses it with
json.loads; non-JSON HTML surfaces as a rawjson.JSONDecodeError, not anAwairError. Any other non-JSON, non-text/htmlcontent type goes throughresp.json(), which raises aiohttp'sContentTypeError(notAwairError) before the errors-array scan; the scan is only reached for successfully parsed bodies. - The client holds no per-request state: no retries, timeouts, or backoff live inside the library; the caller owns session lifecycle.
Exact API Reference
python_awair.Awair
- Import Path:
from python_awair import Awair - Required Test Import Paths:
- python_awair.Awair
- Exact Test Import Statements:
- from python_awair import Awair, AwairLocal, const
- Kind: class
- Signature:
class Awair:
client: AwairClient
def __init__(self, session: ClientSession, access_token: Optional[str]=None, authenticator: Optional[AwairAuth]=None) -> None
async def user(self) -> AwairUser
- Raises (implementation must reproduce these exact messages):
No authentication supplied!
- Behavior: Entry class for the Awair API.
python_awair.AwairLocal
- Import Path:
from python_awair import AwairLocal - Required Test Import Paths:
- python_awair.AwairLocal
- Exact Test Import Statements:
- from python_awair import Awair, AwairLocal, const
- Kind: class
- Signature:
class AwairLocal:
client: AwairClient
def __init__(self, session: ClientSession, device_addrs: List[str]) -> None
async def devices(self) -> List[AwairLocalDevice]
- Raises (implementation must reproduce these exact messages):
No local Awair device addresses supplied!
- Behavior: Entry class for the local sensors Awair API.
python_awair.attrdict.AttrDict
- Import Path:
from python_awair.attrdict import AttrDict - Required Test Import Paths:
- python_awair.attrdict.AttrDict
- Exact Test Import Statements:
- from python_awair.attrdict import AttrDict
- Kind: class
- Signature:
class AttrDict(Dict[str, Any]):
def __init__(self, attrs: Dict[str, Any]) -> None
- Behavior: Dict with attribute-like access.
python_awair.auth.AccessTokenAuth
- Import Path:
from python_awair.auth import AccessTokenAuth - Signature:
class AccessTokenAuth:
def get_bearer_token(self) -> str
- Behavior: Authentication that uses an Awair access token.
python_awair.client.AwairClient
- Import Path:
from python_awair.client import AwairClient - Required Test Import Paths:
- python_awair.client.AwairClient
- Exact Test Import Statements:
- from python_awair.client import AwairClient
- Kind: class
- Signature:
class AwairClient:
def __init__(self, authenticator: AwairAuth, session: ClientSession) -> None
async def query(self, url: str) -> Any
- Behavior: Python asyncio client for the Awair GraphQL API.
python_awair.indices.Indices
- Import Path:
from python_awair.indices import Indices - Signature:
class Indices
- Behavior: Indices of an AwairDevice.
python_awair.sensors.Sensors
- Import Path:
from python_awair.sensors import Sensors - Signature:
class Sensors
- Behavior: Sensors of an AwairDevice.
python_awair.const
- Import Path:
from python_awair import const - Required Test Import Paths:
- python_awair.const
- Exact Test Import Statements:
- from python_awair import Awair, AwairLocal, const
- Kind: module
- Behavior: Module required during hidden-test collection.
python_awair.const.USER_URL
- Import Path:
from python_awair.const import USER_URL - Required Test Import Paths:
- python_awair.const.USER_URL
- Exact Test Import Statements:
- from python_awair import Awair, AwairLocal, const
- Kind: constant
- Signature:
USER_URL: str
- Behavior: Module-level value required by the test import contract.
python_awair.exceptions.NotFoundError
- Import Path:
from python_awair.exceptions import NotFoundError - Required Test Import Paths:
- python_awair.exceptions.NotFoundError
- Exact Test Import Statements:
- from python_awair.exceptions import AuthError, AwairError, NotFoundError, QueryError
- Kind: exception
- Signature:
class NotFoundError(AwairError):
message: str
def __init__(self, extra_message: Optional[str]=None) -> None
- Behavior: The requested endpoint is gone.
Capability: Bearer-token authentication strategies
Why this capability exists
python_awair never hard-codes a credential into its HTTP layer. The client depends on the abstract AwairAuth interface, and AccessTokenAuth is simply the stock strategy that hands back the access token from the Awair developer console. Splitting the two lets any asynchronous credential source — a static token, a token re-read from disk, a refreshed OAuth token — be swapped in without touching request code, and it gives tests a natural seam: a fake authenticator returning a canned token is the standard way to drive the client offline and assert on the outgoing headers.
How the pieces interact
AwairClient holds the authenticator it was constructed with and consults it inside every query() call. The sequencing is the test-sensitive part:
get_bearer_token()is awaited once per request, before the GET is issued. The client does not cache the token, so a strategy that rotates or re-reads its credential is honored on the very next call; conversely, a credential revoked server-side keeps failing until the strategy itself returns something different.- The returned string is interpolated verbatim into
Authorization: Bearer {token}. The client adds theBearerscheme and the single separating space, so the strategy must return the bare token — not a preformed header value and not a value with surrounding whitespace it expects to be cleaned. - The same header dict always sets
Content-Type: application/json; a custom strategy influences only the Authorization value and cannot add, replace, or suppress other headers. - Because header construction precedes network I/O, an exception raised inside
get_bearer_token()propagates out ofquery()before any bytes are sent.
Contract details that matter to a re-implementation
AwairAuth is an ABC with exactly one abstract method, and that method is a coroutine. Two consequences follow. First, AwairAuth itself cannot be instantiated, and a subclass that forgets the override fails at construction time with TypeError. Second, an override must be a coroutine function, but the ABC check does not enforce that: a plain def returning a str still satisfies the abstract-method check — Python's machinery clears __abstractmethods__ for any name override, sync or async — so construction succeeds. The failure lands at request time instead: the client awaits the call's result, and awaiting a plain string raises TypeError at request time, not at import or construction.
AccessTokenAuth is intentionally minimal: the constructor stores the token as the public attribute access_token, and get_bearer_token() returns it unchanged. No trimming, escaping, URL-encoding, or validation happens, so an empty or whitespace-only token is sent as-is and only surfaces as a server-side rejection. The attribute is mutable — reassigning auth.access_token between requests changes the Authorization header of all subsequent requests without constructing anything new.
Auth failures
A credential problem is reported as AuthError. The client maps both HTTP 401 and HTTP 403 to it — 403 covers the "valid token, but no access to the requested data" case, which the exception's fixed message reflects. The check is status-first: AuthError is raised before the response body is parsed and before the legacy GraphQL-style errors array is inspected, so a 401 or 403 carrying an HTML or JSON error body still yields AuthError and never a parse error. AuthError extends AwairError, so a broad except AwairError catches it together with rate-limit, query, and not-found failures, while except AuthError alone will not catch a 429 or a malformed query. The message is the class-level literal, and any extra context string passed to the constructor is appended after a single space. The exception carries no status code or response object, so callers distinguish auth failures from other errors by exception type only.
Non-obvious behaviors
- The token is re-fetched even for consecutive requests to the same URL; a strategy with call-counting side effects sees exactly one invocation per
query(). - The Authorization header is sent unconditionally — there is no "omit the header when unauthenticated" path; unauthenticated behavior must be modeled by a strategy, not by
None. - All requests on this path are GETs; the authenticator is consulted identically regardless of the endpoint being queried.
- Because the abstract method is async, strategy implementations may freely
await(file reads, token refresh HTTP calls) — the client already runs inside an event loop and awaits the result.
Exact API Reference
python_awair.exceptions.AuthError
- Import Path:
from python_awair.exceptions import AuthError - Required Test Import Paths:
- python_awair.exceptions.AuthError
- Exact Test Import Statements:
- from python_awair.exceptions import AuthError, AwairError, NotFoundError, QueryError
- Kind: exception
- Signature:
class AuthError(AwairError):
message: Any
def __init__(self, extra_message: Optional[str]=None) -> None
- Behavior: Some kind of authorization or authentication failure.
python_awair.auth.AwairAuth
- Import Path:
from python_awair.auth import AwairAuth - Required Test Import Paths:
- python_awair.auth.AwairAuth
- Exact Test Import Statements:
- from python_awair.auth import AwairAuth
- Kind: class
- Signature:
class AwairAuth(ABC):
@abstractmethod
async def get_bearer_token(self) -> str
- Behavior: Abstract authentication that provides a Bearer token.
Capability: HTTP query execution and error translation
HTTP query execution and error translation
AwairClient.query is the single funnel through which every read-only Awair request flows: Awair, AwairLocal, device models, and the Indices/Sensors helpers all resolve to a call like client.query(f"{const.API_URL}/user/{user_uuid}/devices") (or a device.query_... variant that prefixes the device URL). The method is deliberately tiny: it attaches authentication headers, performs a GET, guarantees a parsed-JSON return value, and converts every failure mode the Awair cloud can produce into one of the typed exceptions in python_awair.exceptions. Re-implementing this capability means reproducing both the happy path (returning the raw decoded payload for voluptuous schema validation upstream) and the exact error-translation ladder.
Request flow and ordering
- Headers first. Before any network I/O,
queryawaits the authenticator's bearer token and builds{"Authorization": f"Bearer {token}", "Content-Type": "application/json"}. This meansget_bearer_token()is awaited on every query, so an authenticator that rotates or refreshes tokens affects per-request behavior, and an authenticator that raises propagates out ofquerybefore a request is ever issued. - Status gate before body parsing. The response status is checked inside the
async withblock before the body is read. Any non-200 status short-circuits: the body is never decoded, and__handle_non_200_erroralways raises (itsNoReturncontract). There is no retry, no backoff, and no attempt to read error detail from the response body. - Content-type-aware JSON decoding. On a 200, the client checks
resp.content_type. Awair Omni devices with the Ethernet backpack answer withtext/htmlbodies that are nonetheless valid JSON, so in that case the client readsawait resp.text()and appliesjson.loadsexplicitly. For any other content type it usesawait resp.json()directly — which means a 200 answered with any non-JSON content type (e.g.text/plain) raises aiohttp's ownContentTypeError, uncaught. This is a test-sensitive quirk: a mock response declaringtext/htmlmust still yield parseable JSON text, orjson.JSONDecodeErrorescapes uncaught — the library makes no effort to translate malformed bodies or unusable content types intoAwairError. - Errors-array inspection. After successful decoding, the parsed payload is checked with the bare membership expression
"errors" in json— a holdover from the older GraphQL API. The check is shape-sensitive: it is a key lookup only when the payload is a dict. A dict without the key is returned as-is (Any). A list payload is membership-tested by element equality, so a list whose elements never equal the string"errors"also flows through untouched, while a list containing a literal"errors"element passes the check and then fails with an uncaughtTypeErrorat the subsequentjson["errors"]indexing. Non-iterable scalar payloads (int, float, bool, None) never reach a return at all: the membership test itself raises an uncaughtTypeError. A string payload undergoes substring matching — one containing"errors"passes the check and then raisesTypeErrorat the indexing; one that does not is returned as-is. - Return. The decoded payload is returned unchanged (for the shapes that survive step 4); all shaping into
AirData,Device, etc. happens in higher layers.
Status-to-exception mapping
The translation ladder for non-200 responses is exact and order-independent by status code:
400→QueryError("The supplied parameters were invalid.")401or403→AuthError404→NotFoundError429→RatelimitError- anything else (including 5xx) → base
AwairError
Every one of these is raised with no extra_message, so str(exc) is exactly the class-level message attribute — tests assert on these literal strings, and the message composition rule is: final = message + (" " + extra_message if extra_message else ""), with the space joining prefix and suffix. Since all five classes subclass AwairError, an except AwairError clause catches the entire ladder, and a Home Assistant-style integration can rely on AuthError/RatelimitError for retry/credential flows while treating the base class as the catch-all.
Embedded errors array semantics
The errors-array path has two non-obvious behaviors:
- Rate-limit detection wins — and the scan indexes directly. While iterating, the scan reads
error["message"](direct indexing, not.get) and raises a bareRatelimitError()immediately when that message contains the substring"Too many requests"; remaining messages are discarded and never joined. The check is a substring test, not equality, and it happens even if other error entries would have contributed text. Because the access is direct indexing, an entry lacking a"message"key raises an uncaughtKeyErrorat the scan, before that entry can contribute any text. - Aggregation otherwise. Every entry that survives the scan contributes
error.get("message", "Unknown error")— but that fallback is unreachable: any entry without a"message"key has already raised an uncaughtKeyErrorat the rate-limit scan, so an entry reaching aggregation always contributes its actualmessagevalue. If the collected list is non-empty,AwairError(", ".join(messages))is raised with the joined text as the extra message, producing"Error querying the Awair API. <msg1>, <msg2>". - A 200 payload containing an empty
errorslist ([]) passes through:messagesstays empty and no exception is raised. This pass-through is guaranteed for dict payloads; every other payload shape is governed by the step-4 caveats above.
Edge cases to honor
- The status gate fires before body reads, so a 500 response with a garbage body still raises base
AwairError, never a decode error. text/htmlis matched on the exact content type;application/jsontakes the normalresp.json()path (aiohttp's own decoder, honoring its content-type check). Any other 200 content type — e.g.text/plain— makesresp.json()raiseaiohttp.ContentTypeErroruncaught, mirroring the existing uncaughtjson.JSONDecodeErrorescape for malformed bodies: neither is ever translated intoAwairError.- The bearer token is interpolated into the
Authorizationheader verbatim; no scheme rewriting or whitespace stripping occurs. queryaccepts any URL string — cloud endpoints and local-device URLs (AwairLocalpointed at an IP/DNS address) share the identical code path, so local devices that answer 4xx get the same exception translation.- There is exactly one HTTP method: GET, with no body, params, or timeout handling at this layer.
A faithful re-implementation is roughly: fetch headers → GET → non-200 ladder → text/html fallback decode → errors-array scan → return payload.
Exact API Reference
python_awair.exceptions.AwairError
- Import Path:
from python_awair.exceptions import AwairError - Required Test Import Paths:
- python_awair.exceptions.AwairError
- Exact Test Import Statements:
- from python_awair.exceptions import AuthError, AwairError, NotFoundError, QueryError
- Kind: exception
- Signature:
class AwairError(Exception):
message: str
def __init__(self, extra_message: Optional[str]=None) -> None
- Behavior: Base awair exception class.
python_awair.exceptions.QueryError
- Import Path:
from python_awair.exceptions import QueryError - Required Test Import Paths:
- python_awair.exceptions.QueryError
- Exact Test Import Statements:
- from python_awair.exceptions import AuthError, AwairError, NotFoundError, QueryError
- Kind: exception
- Signature:
class QueryError(AwairError):
message: str
def __init__(self, extra_message: Optional[str]=None) -> None
- Behavior: The query was somehow malformed.
Capability: User profile, quota, and usage inspection
What this capability covers
This is the read-side "who am I and what have I consumed" slice of the client. It resolves the identity behind the configured access token by querying const.USER_URL (https://developer-apis.awair.is/v1/users/self) and materializes the JSON payload as an AwairUser. The same object anchors a second endpoint, const.DEVICE_URL (.../v1/users/self/devices), which lists the devices the token-holder can see. Both URLs are derived from the shared BASE_URL, so they inherit whatever API root the client targets.
How the pieces fit together
The normal flow is: build an AwairClient (directly or via the entry Awair object), call Awair.user(), and receive an AwairUser whose client attribute is that same client instance. AwairUser is deliberately passive: everything except devices() is computed once, at construction, from the attribute mapping. A user object is therefore a snapshot of the profile as of the /users/self call - quota and usage numbers never refresh on their own; call Awair.user() again to re-read them.
Hand construction (AwairUser(client, attributes)) is supported and is exactly what the test suite does: attributes must look like the /users/self response body. This makes the class testable with no HTTP layer at all; only devices() needs a real (or mocked) client.
Field mapping and defaults
user_idcomes from the required"id"key; a payload without it raisesKeyErrorat construction. No type coercion is performed, souser_idstores the payload's"id"value verbatim: the API documents the field as a string (and the class annotates it asstr), but a payload supplying digits without quotes yields a non-struser_idat runtime. Therepris unchanged either way, since the value is formatted through an f-string.email,first_name(payload key"firstName"),last_name("lastName"),sex, andtierdefault toNonewhen absent.sexis conventionally one of'MALE','FEMALE', or'UNKNOWN';tiernominally drives quotas, but the library performs no tier-based logic.dobbecomes adatetime.dateonly when all three of"dobDay","dobMonth","dobYear"are present and truthy; otherwise it isNone. There is no partial-date support - one missing or zero-valued component discards the whole date. Absent/falsy is the only route toNone: truthy components that do not form a valid calendar date (e.g.dobMonth=2withdobDay=30, or a non-leap Feb 29) are not coerced toNone- the constructor callsdatetime.date(day=..., month=..., year=...), so out-of-range truthy values raiseValueErrorat construction, and non-numeric truthy values raiseTypeError.usagesmapsscope -> usageandpermissionsmapsscope -> quota. Both are dict comprehensions over the payload's"usages"/"permissions"lists; if those payload keys are missing you get empty dicts. Each list item must carry a"scope"key plus"usage"(respectively"quota"), so a malformed item raisesKeyErrorrather than being skipped. Duplicate"scope"entries in the payload lists are resolved last-wins: the later item silently overwrites the earlier one, with no error or aggregation.- No validation or type coercion happens beyond this mapping; the class trusts the endpoint shape. Note the camelCase payload keys versus snake_case attribute names.
Quota and usage semantics
permissions values are per-window maxima for the call type named by the scope; usages values are how many times that call type has been used in the current window. A scope appears in usages only once it has been used, so a freshly reset account can have empty usages even though permissions is fully populated. When computing remaining budget, use usages.get(scope, 0) - do not index. The window resets at midnight; the timezone is deliberately not pinned down by the library, so neither code nor tests should assume a specific one. Nothing enforces quotas client-side: exceeding a quota surfaces later as a rate-limit error from the client, not from AwairUser.
devices() behavior
await user.devices() issues one GET to DEVICE_URL through the stored client and wraps each entry of the response's "devices" list in an AwairDevice bound to that same client, so device queries reuse the same authentication. If the response has no "devices" key the result is [] - the only lenient list handling here, in contrast to the strict key access during construction. Returned order is exactly the API's order; the library does not sort or deduplicate. HTTP failures propagate through the client's normal error translation (auth, rate-limit, query, not-found); AwairUser adds none of its own. For organization-affiliated tokens the endpoint returns devices the user can view rather than strictly owns; the organization API itself remains out of scope.
Representation and identity
repr(user) is deterministic: <AwairUser: user_id=...>, appending email=... only when the email is not None. There is no __eq__, so user objects compare by identity - compare user_id values instead. All fields are plain instance attributes, so tests may construct an AwairUser from a canned payload and freely inspect or mutate it, or substitute a stub client before calling devices().
Test-sensitive checklist
"id"missing causesKeyErrorin the constructor; so does a usage/permission item lacking"scope"or its value key.- Falsy DOB components (e.g.
0) are treated as absent, yieldingdob = None; truthy-but-invalid or non-numeric DOB components instead propagateValueError(orTypeError) from the constructor. - Missing
"usages"or"permissions"payload keys yield{}; missing"devices"in the device response yields[]. Duplicate scopes are last-wins. - The
repremail clause appears iff the email is present. devices()is a coroutine - constructing a user never triggers network I/O.user_idstores the payload's"id"value verbatim with no type coercion: digits without quotes yield a non-struser_id(thereproutput is unchanged, since f-string formatting is used).
Exact API Reference
python_awair.user.AwairUser
- Import Path:
from python_awair.user import AwairUser - Required Test Import Paths:
- python_awair.user.AwairUser
- Exact Test Import Statements:
- from python_awair.user import AwairUser
- Kind: class
- Signature:
class AwairUser:
user_id: str
email: Optional[str]
first_name: Optional[str]
last_name: Optional[str]
sex: Optional[str]
dob: Optional[date]
tier: Optional[str]
usages: Dict[str, int]
permissions: Dict[str, int]
client: AwairClient
def __init__(self, client: AwairClient, attributes: Dict[str, Any]) -> None
def __repr__(self) -> str
async def devices(self) -> List[AwairDevice]
- Behavior: An Awair user.
Capability: Device discovery and metadata for cloud and local devices
What this capability does
Turns raw device payloads into typed, queryable objects. Two discovery paths converge on one base class:
- Cloud:
AwairUser.devices()issues a single request to/users/self/devicesand wraps each returned mapping in anAwairDevice, preserving server order. There are no filters, pagination, or parameters; nothing is cached, so every call is a fresh fetch of a static metadata snapshot. - Local:
AwairLocal.devices()fans out one concurrentGET http://{addr}/settings/config/dataper supplied address (viaasyncio.gather) and wraps each response in anAwairLocalDevice, carrying the matching address. Output order equals input order because gather preserves argument order. The local path needs no real credential — the client is built with an empty Bearer token.
Failure model differs by stage: an empty address list is rejected at construction time by AwairLocal (raising AwairError), whereas a runtime failure on any single address — unreachable host, bad status — propagates out of gather with no per-device isolation, so one bad IP fails the whole discovery call.
Metadata attributes
AwairBaseDevice.__init__ copies camelCase API keys onto the object. Required: deviceId, deviceUUID, deviceType (absent keys raise KeyError). Optional, defaulting to None: macAddress, latitude, longitude, name, preference, roomType, spaceType, timezone. The client reference is retained for later queries.
Non-obvious details:
modelis a property, computed on access fromdevice_typeviaconst.AWAIR_MODELS:awair→Awair,awair-element→Awair Element,awair-glow→Awair Glow,awair-glow-c→Awair Glow C,awair-mint→Awair Mint,awair-omni→Awair Omni,awair-r2→Awair 2nd Edition. Unknown device types fall back to the rawdevice_typestring, somodelis neverNone. (The docstring table labelsawair-mintasAwair Baby; the constant mapping is what actually runs.)location_nameis declared (annotation and docstring) onAwairBaseDevice, but__init__never reads alocationNamekey and never assigns the attribute. On any discovered or hand-built device,device.location_nameraisesAttributeError— despite the "defaults toNone" list above, this is not a populated optional field.- Local devices do not receive IDs from the wire.
AwairLocalDevice.__init__requiresdevice_uuidin the config payload and derives all three identifiers by splitting on the first underscore:awair-element_123becomes typeawair-elementand numeric id123(coerced withint, so a non-numeric suffix or a uuid without_fails).wifi_macmaps tomac_address(optional);fw_versionis stored as an extra attribute — firmware version is exposed only on local devices.device_addris stored verbatim, IP or DNS. repr()is identical for both subclasses:<AwairDevice: uuid=... model=...>.room_type/space_type/preference/timezoneare free-form server strings (LIVING_ROOM,HOME,GENERAL); no validation or aliasing happens in this layer.
Shared query machinery (test-sensitive)
The base class also owns the air-data plumbing; the subclasses differ exactly in URL shape and response extraction:
- URL:
{base}/air-data/{kind}. Cloud base is{DEVICE_URL}/{device_type}/{device_id}underhttps://developer-apis.awair.is/v1/users/self/devices; local base is barehttp://{device_addr}(plain HTTP, no path). - Extraction: cloud reads
response["data"], treating a missing key as an empty list; local reshapes the flat response — every key excepttimestampandscorebecomes{comp: key, value: value}undersensors— and yields exactly one datapoint per response. A local response missingtimestamp/scoreraisesKeyError. - Arguments are shared, with a local override. Accepted kwargs:
fahrenheit,desc,limit,from_date,to_date. Anything else is rejected, not stripped: the voluptuous schema is built with the defaultextra=PREVENT_EXTRA, so an unexpected key raisesvol.Invalid("extra keys not allowed @ data[...]").fahrenheit/descare coerced to lowercase strings (true/false);limitis int-ranged 1–360 (raw), 1–288 (five-minute), 1–672 (fifteen-minute). - Dates are validated by hand against naive
datetime.now(), with three failure modes: (1) an object lacking anowattribute — e.g. a string or an int — raises theinstances of datetimeerror (the check is duck-typed, notisinstance); (2) a future date, an inverted range, or a span beyond the window (1 h raw, 24 h five-minute, 168 h fifteen-minute) raises its own distinct message; (3) a timezone-aware datetime passes the duck-type check (everydatetimeexposesnowvia its class) and then fails at the future-date comparison — an offset-aware datetime compared against naivedatetime.now()raisesTypeError("can't compare offset-naive and offset-aware datetimes"), not theinstances of datetimemessage. Only supplied dates are stringified withstr()and URL-encoded — the validation defaults are never sent, so omittingfrom_date/to_datedefers the default window to the server. Empty kwargs produce no query string at all. - Ordering:
descis forwarded only when explicitly supplied (coerced totrue/false); when omitted it is not sent, so the docstring'sTrue/newest-first default is an API-level behavior not enforced or sent by this library — exactly parallel to thefrom_date/to_datedefaults note above. - Local quirks:
fahrenheit=TrueraisesValueError(fahrenheit is not supported for local sensors yet); a falsyfahrenheitis deleted rather than forwarded, because any URL parameter at all corrupts the local timestamp, and the remaining kwargs are then validated by the base schema — so unknown kwargs raisevol.Invalidon the local path too. Datapoint caps still apply: 288 points / 24 h for five-minute, 672 / 7 days for fifteen-minute, 360 / 1 h for raw.
Realistic workflow
Authenticate once (Awair(session, access_token=...)) and call user().devices() for the cloud inventory; build AwairLocal(session, addrs) separately for on-network units; merge both lists and branch on isinstance (or on device_type/model) when behavior differs; then use the inherited query methods uniformly. Metadata is point-in-time: display-name or firmware changes require re-listing. Note you can construct device objects by hand from a fixture mapping (useful in tests), but the supported path is discovery through the entry classes.
Exact API Reference
python_awair.devices.AwairBaseDevice
- Import Path:
from python_awair.devices import AwairBaseDevice - Signature:
class AwairBaseDevice:
def model(self) -> str
def air_data_latest(self, fahrenheit: bool=False) -> Optional[AirData]
def air_data_five_minute(self, **kwargs: AirDataParam) -> List[AirData]
def air_data_fifteen_minute(self, **kwargs: AirDataParam) -> List[AirData]
def air_data_raw(self, **kwargs: AirDataParam) -> List[AirData]
- Raises (implementation must reproduce these exact messages):
expected subclass to define overrideExpected 'from_date' and/or 'to_date' to be instances of datetimeDates cannot be in the future!'from_date' cannot be greater than 'to_date'.
- Behavior: An Awair device.
python_awair.devices.AwairDevice
- Import Path:
from python_awair.devices import AwairDevice - Required Test Import Paths:
- python_awair.devices.AwairDevice
- Exact Test Import Statements:
- from python_awair.devices import AwairDevice
- Kind: class
- Signature:
class AwairDevice(AwairBaseDevice):
device_id: int
uuid: str
device_type: str
mac_address: Optional[str]
latitude: Optional[float]
location_name: Optional[str]
longitude: Optional[float]
name: Optional[str]
preference: Optional[str]
room_type: Optional[str]
space_type: Optional[str]
timezone: Optional[str]
client: AwairClient
def __init__(self, client: AwairClient, attributes: Dict[str, Any]) -> None
def __repr__(self) -> str
@property
def model(self) -> str
async def air_data_latest(self, fahrenheit: bool=False) -> Optional[AirData]
async def air_data_five_minute(self, **kwargs: AirDataParam) -> List[AirData]
async def air_data_fifteen_minute(self, **kwargs: AirDataParam) -> List[AirData]
async def air_data_raw(self, **kwargs: AirDataParam) -> List[AirData]
@staticmethod
def _format_args(kind: str, **kwargs: AirDataParam) -> str
- Behavior: A cloud-based Awair device.
python_awair.devices.AwairLocalDevice
- Import Path:
from python_awair.devices import AwairLocalDevice - Signature:
class AwairLocalDevice
- Raises (implementation must reproduce these exact messages):
fahrenheit is not supported for local sensors yet
- Behavior: A local Awair device.
Capability: Air-data modeling of scores, sensors, and indices
Purpose
Every Awair reading the API returns — a latest datapoint, a five-minute or fifteen-minute aggregate, or a raw datapoint — arrives as one JSON object with a UTC timestamp, an overall score, and lists of sensor measurements and computed indices. AirData is the single model that converts such a payload into a typed record: a parsed datetime, a numeric score, and two dict-like mappings (sensors, indices) from pollutant component name to value. Device query methods hand the validated payload straight to this constructor, so re-implementing the capability means reproducing exactly how AirData shapes and exposes that data.
How the pieces fit
An AirData is constructed from a single attributes dict. From it the constructor derives four fields:
timestamp— the"timestamp"string is parsed withdatetime.strptimeusingconst.DATE_FORMAT("%Y-%m-%dT%H:%M:%S.%fZ"). The result is a naive datetime: the trailingZis a literal in the format string, so no timezone info is attached even though the value is UTC. Tests that compare timestamps typically do so againstdatetime.strptime(payload["timestamp"], const.DATE_FORMAT)— an aware datetime or a hand-builtdatetime(...)withtzinfowill not compare equal. The%fcomponent is mandatory: a timestamp without fractional seconds fails to parse.score— stored verbatim from"score"; it is the device's overall air-quality score (higher is better, unlike indices). No rounding is applied to the stored value;__repr__renders the score asround(score, 2)— a rounded float displayed with Python's normal float repr, notf"{score:.2f}"fixed formatting (score 2.0 renders as2.0, not2.00).sensors— aSensorsmapping built fromattributes.get("sensors", []); each list entry contributesentry["comp"] -> entry["value"].indices— anIndicesmapping built identically fromattributes.get("indices", []).
Both lists are read with a default of [], so a payload containing only a timestamp and score produces an AirData with empty Sensors/Indices rather than an error. Conversely, "timestamp" and "score" are unguarded: a missing key raises KeyError, and a malformed timestamp raises the ValueError that strptime produces. AirData itself performs no schema validation and no type coercion — it trusts whatever the client layer passed in. Entries with extra keys (e.g. "unit") are tolerated because only comp and value are read; if the same comp appears twice, the later entry wins because the mapping is built with a dict comprehension.
Sensors and Indices semantics
Sensors and Indices are dict subclasses (AttrDict), so stored values are reachable by subscripting with the raw API component name and by attribute (dot) access. Attribute access resolves through the underlying dict: mapped aliases (temp→temperature, humid→humidity, co2→carbon_dioxide, voc→volatile_organic_compounds, pm25→particulate_matter_2_5, plus lux→illuminance and spl_a→sound_pressure_level for sensors) resolve via dot access, and a raw stored key with no alias — e.g. the first-generation device's aggregate dust, or a future API addition — still resolves via dot access under its raw name (air.sensors.dust) as well as by subscript (air.sensors["dust"]). A name that is neither an alias nor a stored key raises the AttrDict's attribute-not-found failure. Because the underlying object is a dict, iteration, len, in, and equality with plain dicts of the same keys behave like ordinary dict semantics, and the entries appear in the payload's original order — the constructor neither sorts nor deduplicates beyond last-write-wins.
Semantically, sensor values are the raw measurements (e.g. °C, %RH, ppm, µg/m³), while index values are quality scores in roughly [-4, 4] where the magnitude matters: closer to 0 is better, closer to ±4 is worse. Do not assume symmetry between the two mappings — a sensor present in sensors may have no matching entry in indices, and index dictionaries only alias the temperature/humidity/CO₂/VOC/PM2.5 family.
Realistic workflow, state, and edge cases
In practice you never build AirData manually in production code: AwairDevice/AwairLocalDevice query methods (get_latest, the five- and fifteen-minute samplings, and raw datapoint queries) return AirData objects one per datapoint, in the order the API returned them (newest-first for latest-style endpoints, ascending time for ranged queries — the model preserves that order and adds none). Each object is a point-in-time snapshot; the library does not mutate an AirData after construction, though the underlying AttrDict mappings do permit dot-notation assignment and deletion of sensor/index values — treat that as a re-implementer's obligation (the behavior exists), not a recommended usage.
Edge cases worth honoring:
- Empty
sensors/indiceslists, or absent keys, yield empty mappings;air.sensors.temperatureon an empty mapping raises theAttrDict's attribute-not-found error, andair.sensors["temp"]raisesKeyError. - A
sensorsentry missing"comp"or"value"raisesKeyErrorduring construction; a non-dict entry raises aTypeErrorfrom the subscript. repr(AirData)must produce<AirData@{timestamp}: score={rounded score} sensors={sensors}>, where the rounded score isround(score, 2)shown with Python's float repr (so 2.0 renders2.0, not2.00), and the mappings render asSensors({...})/Indices({...})around the dict repr — tests assert on these exact shapes.- The stored score keeps full float precision; only the repr rounds.
Exact API Reference
python_awair.air_data.AirData
- Import Path:
from python_awair.air_data import AirData - Signature:
class AirData
- Behavior: Wrapper class for awair airdata responses.
Detailed Implementation Nodes
Node: Asynchronous Awair API client construction and configuration
Functional constraints
Awair(session, access_token=None, authenticator=None): sync__init__; selection order is authenticator ->AccessTokenAuth(access_token)-> raiseAwairError("No authentication supplied!"); stores the client as.client.AwairLocal(session, device_addrs): non-empty list required at construction, elseAwairError("No local Awair device addresses supplied!"); the list is retained by reference and re-read at eachdevices()call, so post-construction mutation is honored and a list emptied after construction yields an empty gather returning[]; order follows the list state at call time. Client isAwairClient(AccessTokenAuth(""), session).devices()GETshttp://<addr>/settings/config/dataper address concurrently (asyncio.gather) and returnsAwairLocalDeviceobjects in input order.AwairClient(authenticator, session).query(url): headersAuthorization: Bearer <await authenticator.get_bearer_token()>plusContent-Type: application/json; non-200 maps 400 ->QueryError, 401/403 ->AuthError, 404 ->NotFoundError, 429 ->RatelimitError, elseAwairError; a 200 withtext/htmlis parsed viajson.loads(await resp.text()), elseresp.json()- a 200 with any other non-JSON content type raises aiohttp'sContentTypeErrorbefore the errors-array scan; a bodyerrorskey raisesRatelimitErrorif any entry'smessagecontainsToo many requests- that check readserror["message"]directly, so an entry lackingmessageraisesKeyError, and the.get("message", "Unknown error")default is unreachable dead code - elseAwairError(", ".join(messages))(empty list -> no raise); returns the parsed JSON.AccessTokenAuth(access_token): asyncget_bearer_token()returns the stored token unchanged;AwairAuthis an ABC with an abstract asyncget_bearer_token.AttrDict(attrs): copies the mapping and renames anyconst.SENSOR_TO_ALIASkey at init only; dot access mirrors dict items; missing attributes raiseAttributeErroron reads, while deleting a missing key raisesKeyError(dict deletion semantics);dir()lists keys.const:BASE_URL = "https://developer-apis.awair.is/v1",USER_URL = BASE_URL + "/users/self",DEVICE_URL = USER_URL + "/devices",DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ", plusSENSOR_TO_ALIASandAWAIR_MODELSwith the exact keys/values listed in the guide.- All exceptions derive from
AwairError(base message "Error querying the Awair API." with the optional extra space-joined after it):AuthError,QueryError,NotFoundError,RatelimitError.
Example
import aiohttp
from python_awair import Awair, AwairLocal, const
async def demo():
async with aiohttp.ClientSession() as session:
awair = Awair(session, access_token="secret") # or authenticator=...
user = await awair.user() # GET const.USER_URL
devices = await user.devices() # GET const.DEVICE_URL, same client
local = AwairLocal(session, ["192.168.1.42", "glow.local"])
locals_ = await local.devices() # concurrent GETs, input order kept
Data flows one way: entry class -> AwairClient.query -> parsed JSON -> model constructors (AwairUser, AwairLocalDevice, and via AttrDict the sensor/index models); no response is cached and no client state mutates after construction.
Node: Bearer-token authentication strategies
Functional constraints
AwairAuthis an ABC with a single abstract coroutineget_bearer_token() -> str; instantiating it, or a subclass without the override, raisesTypeErrorat construction.- The override must be a coroutine function; the client awaits its result, so a sync
defreturningstrfails at request time, not at import. AwairClientawaitsget_bearer_token()on every request and buildsAuthorization: Bearer {token}plusContent-Type: application/json; the token is never cached and theBearerprefix is added by the client.- The returned value is used verbatim: no trimming, encoding, or validation; exceptions raised by the strategy abort the request before any network I/O.
AccessTokenAuth(access_token)stores the token as the public, mutable attributeaccess_tokenand returns it unchanged, so reassigning the attribute changes later requests.- HTTP 401 and 403 both raise
AuthError(subclass ofAwairError) before response-body parsing; its literal message isThe supplied access token is invalid or does not have access to the requested data, with any constructor argument appended after a single space.
Usage
from python_awair.auth import AccessTokenAuth, AwairAuth
from python_awair.client import AwairClient
from python_awair.exceptions import AuthError
class ReloadableAuth(AwairAuth):
async def get_bearer_token(self) -> str:
return self._path.read_text().strip() # re-read on every request
auth = AccessTokenAuth("console-token") # or ReloadableAuth(...)
client = AwairClient(auth, session)
try:
data = await client.query(url) # sends "Authorization: Bearer console-token"
except AuthError: # HTTP 401 or 403
...
Node: HTTP query execution and error translation
Functional constraints
AwairClient.query(url)awaitsget_bearer_token()before each request; headers are exactlyAuthorization: Bearer <token>andContent-Type: application/json.- Status checked before body:
400→QueryError,401/403→AuthError,404→NotFoundError,429→RatelimitError, all other non-200→baseAwairError. Raised bare (no extra message), sostr(exc)equals the classmessageexactly. - 200 bodies with content type
text/html(Omni Ethernet backpack) are decoded viaawait resp.text()+json.loads; every other content type goes throughawait resp.json(), which raises uncaughtaiohttp.ContentTypeErrorfor any non-JSON content type (e.g.text/plain) — the same uncaught-escape behavior asjson.JSONDecodeErrorfor malformed JSON. - After decoding, if the payload contains key
"errors": the scan indexes each entry directly (error["message"]), so any entry whosemessagecontains the substring"Too many requests"raisesRatelimitError()immediately (later entries ignored), and an entry lacking a"message"key raises an uncaughtKeyErrorat the scan. Entries that do reach aggregation contributeerror.get("message", "Unknown error")— the fallback literal is unreachable because the scan already raised on message-less entries — and a non-empty list raisesAwairError(", ".join(messages)), yielding"Error querying the Awair API. <joined>". - Message composition for all exceptions:
message + " " + extra_messagewhenextra_messageis truthy, elsemessagealone. Every error type subclassesAwairError. - The errors-array gate is the bare expression
"errors" in jsonwith no type guard: a dict without the key is returned unchanged; a list whose elements never equal"errors"is returned unchanged; a non-iterable scalar (int, float, bool, None) raises uncaughtTypeErrorat the membership test itself; a string payload is substring-matched, and one containing"errors"passes the test and then fails with uncaughtTypeErroratjson["errors"](a list containing the literal element"errors"fails the same way at the indexing). - Malformed JSON (including from a
text/htmlbody) raisesjson.JSONDecodeErroruncaught; the status ladder never inspects the body. - GET only; no retries, timeouts, or parameter encoding at this layer; local-device URLs use the same path.
Example
from aiohttp import ClientSession
from python_awair.client import AwairClient
from python_awair.exceptions import (
AwairError, AuthError, NotFoundError, QueryError, RatelimitError,
)
client = AwairClient(authenticator, ClientSession())
try:
payload = await client.query(f"{const.API_URL}/user/{uuid}/devices")
except QueryError:
... # HTTP 400: bad parameters
except (AuthError, NotFoundError, RatelimitError, AwairError):
... # 401/403, 404, 429 / GraphQL-style errors array, other statuses
Node: User profile, quota, and usage inspection
Functional constraints
- Construct as
AwairUser(client, attributes)whereattributesmirrors the/users/selfbody; in production, obtain instances viaAwair.user()instead. Construction performs no I/O. attributes["id"]is mandatory and becomesuser_id, stored verbatim with no type coercion - it is astronly because the API's payload shape documents it that way, so a payload supplying digits without quotes yields a non-strat runtime. All other profile fields are optional and default toNone:email,first_name(firstName),last_name(lastName),sex,tier.dobis adatetime.dateonly whendobDay,dobMonth, anddobYearare all present and truthy; otherwiseNone. Truthy-but-invalid components are not coerced toNone: the constructor callsdatetime.date(day=..., month=..., year=...), so out-of-range calendar values (e.g.dobMonth=2withdobDay=30, or a non-leap Feb 29) raiseValueErrorat construction, and non-numeric truthy components raiseTypeError; only absent/falsy components yielddob=None.usagesandpermissionsare scope-keyed dicts built from payload lists whose items must containscopeplususage/quota. Missing payload keys yield empty dicts; missing item keys raiseKeyError. Duplicatescopeentries in the payload lists are resolved last-wins, with no error or accumulation.- Counts are per usage window (resets at midnight, timezone unspecified).
permissionsholds per-scope maxima,usagesholds consumption; scopes with zero use may be absent fromusages, so read them with.get(scope, 0). No client-side enforcement. await user.devices()GETsDEVICE_URL(USER_URL + "/devices") with the stored client and maps the response'sdeviceslist toAwairDeviceobjects sharing that client; a missingdeviceskey yields[]. Ordering is the API's order.- HTTP failures (auth, rate-limit, query, not-found) propagate from the client unchanged;
AwairUseradds no errors of its own around HTTP. repris<AwairUser: user_id=<id>>, appendingemail=<email>only when known. No equality beyond object identity.
Example
client = AwairClient(session=session, authenticator=AccessTokenAuth(token="abc"))
user = AwairUser(client, {
"id": "42", "email": "a@b.c", "tier": "dev",
"permissions": [{"scope": "air-data", "quota": 300}],
"usages": [{"scope": "air-data", "usage": 12}],
})
assert user.permissions["air-data"] - user.usages.get("air-data", 0) == 288
assert repr(user) == "<AwairUser: user_id=42 email=a@b.c>"
devices = await user.devices()
Node: Device discovery and metadata for cloud and local devices
Functional constraints
AwairBaseDeviceis an ABC; instantiating it — or a subclass that does not override_get_airdata_base_urland_extract_airdata— fails. The abstract methods themselves raiseTypeError(expected subclass to define override) if invoked on a hand-built instance.- Cloud construction requires the
deviceId,deviceUUID,deviceTypekeys; every other metadata field defaults toNonewhen the key is absent. Exception:location_nameis declared onAwairBaseDevicebut__init__never reads alocationNamekey or assigns the attribute, so accessing it raisesAttributeErroron every device (cloud, local, or hand-built). - Local construction requires
device_uuidof the form{device_type}_{int}; the type/id are split on the first underscore and the id isint-coerced.wifi_macbecomesmac_address;fw_versionanddevice_addrexist only onAwairLocalDevice. modelresolves asAWAIR_MODELS.get(device_type, device_type)— neverNone, falls back to the API type string.- Air-data URLs: cloud
/users/self/devices/{device_type}/{device_id}/air-data/{kind}; localhttp://{device_addr}/air-data/{kind}. Cloud responses readdata(default[]); local responses reshape all non-timestamp/scorekeys into a singlesensorsdatapoint. - Shared kwargs
fahrenheit,desc,limit,from_date,to_date: booleans lowercased to strings,limitbounded to 360/288/672 by kind, date windows 1 h/24 h/168 h by kind, four distinct validation errors for bad datetimes, future dates, inverted ranges, and oversized spans. Unknown kwargs are rejected, not dropped: the schema uses voluptuous' defaultextra=PREVENT_EXTRA, so an extra key raisesvol.Invalid("extra keys not allowed @ data[...]"). Shared call path:AwairLocalDevice._format_argsdeletes a falsyfahrenheit(raising on a truthy one) and then delegates to the base_format_args/schema, so the same rejection applies on the local path. No kwargs means no?query string. - The
kwargs is not Nonecheck in__get_airdatais always true —**kwargscan never beNone— so the only empty-kwargs behavior is the empty query string returned by_format_args; there is noNone-handling path. fahrenheit=Trueon a local device raisesValueError; falsyfahrenheitis silently removed before delegating to the base formatter.AwairLocal.devices()queries all addresses concurrently and returns devices indevice_addrsorder; any single address failure aborts the whole call.
Usage
from aiohttp import ClientSession
from python_awair import Awair, AwairLocal
async def list_devices(session: ClientSession, token, addrs):
user = await Awair(session, access_token=token).user()
cloud = await user.devices() # list[AwairDevice]
local = await AwairLocal(session, addrs).devices() # list[AwairLocalDevice]
return cloud + local
# shared on both: .model .uuid .device_type .mac_address
# .name .room_type .space_type .timezone
Node: Air-data modeling of scores, sensors, and indices
Functional constraints
AirData(attributes)takes one dict. Required keys:"timestamp"(string inconst.DATE_FORMAT,%Y-%m-%dT%H:%M:%S.%fZ) and"score"(number). Missing either →KeyError; unparseable timestamp →ValueErrorfromstrptime. The%ffield is required, so timestamps without fractional seconds fail.- Parsed
timestampis a naive UTC datetime — notzinfois attached (theZis a format literal). Compare againstdatetime.strptime, not aware datetimes. scoreis stored unrounded; only__repr__renders it asround(score, 2)— a rounded float in Python's normal float repr, notf"{score:.2f}"fixed formatting (score 2.0 renders as2.0, not2.00).sensorsandindicescome fromattributes.get(..., []): absent or empty lists yield empty mappings, never errors.- Each list entry contributes
entry["comp"] -> entry["value"]; extra keys are ignored, duplicatecomps resolve last-wins, and entries missingcomp/valueraiseKeyError. SensorsandIndicesare dict subclasses; attribute access resolves through the underlying dict. Per mapping: mapped aliases (temperature,humidity,carbon_dioxide,volatile_organic_compounds,particulate_matter_2_5, and additionallyilluminance/sound_pressure_levelfor sensors) resolve via dot access; a raw stored key without an alias (e.g.dust) resolves both by subscript (air.sensors["dust"]) and by raw-name dot access (air.sensors.dust) via theAttrDictdict-key fallback; a name that is neither an alias nor a stored key raises theAttrDict's attribute lookup failure. Raw API keys (temp,co2, …) are the stored keys.- Index values are signed floats in roughly
[-4, 4]; magnitude is severity (0 best, |4| worst). A sensor need not have an index. - Exact reprs:
AirData→<AirData@{timestamp}: score={round(score, 2) as float repr} sensors={sensors}>; mappings →Sensors({...})/Indices({...}). - Construction is synchronous and pure; no network, no validation beyond key access.
Usage example
from datetime import datetime
from python_awair.air_data import AirData
payload = {
"timestamp": "2022-04-04T22:11:17.359Z",
"score": 88.4580357142857,
"sensors": [{"comp": "temp", "value": 21.51}, {"comp": "co2", "value": 613.0}],
"indices": [{"comp": "co2", "value": 0.6}],
}
air = AirData(payload)
assert air.timestamp == datetime.strptime(payload["timestamp"], "%Y-%m-%dT%H:%M:%S.%fZ")
assert air.score == 88.4580357142857 # full precision kept
assert air.sensors["temp"] == air.sensors.temperature == 21.51
assert air.indices["co2"] == air.indices.carbon_dioxide == 0.6
assert dict(air.sensors) == {"temp": 21.51, "co2": 613.0} # raw keys stored
assert AirData({"timestamp": payload["timestamp"], "score": 1.0}).sensors == {}
API Reference (required components)
python_awair.const.DEVICE_URL
- Import Path:
from python_awair.const import DEVICE_URL - Required Test Import Paths:
- python_awair.const
- python_awair.const.DEVICE_URL
- Exact Test Import Statements:
- from python_awair import const
- from python_awair.const import DEVICE_URL
- Kind: constant
- Signature:
DEVICE_URL: str
- Behavior: Module-level value required by the test import contract.