Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
73.4 kB

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:

  1. Do NOT create or modify any files under the test directories (e.g. tests/, test/, testing/, or files named test_*.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.

  2. Your package MUST be importable by the name the tests use. The hidden tests import your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid pyproject.toml / setup.py / setup.cfg and lay out your modules so that pip install -e . succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.

  3. 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/repo at 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 supplied authenticator always wins. Otherwise a truthy access_token is wrapped in AccessTokenAuth. If neither is supplied, construction raises AwairError("No authentication supplied!") immediately (the literal string is the extra message appended to the base message). Passing access_token="" counts as "not supplied" - empty strings are falsy.
  • AwairLocal(session, device_addrs): the address list must be non-empty or construction raises AwairError("No local Awair device addresses supplied!"). The client is built as AwairClient(AccessTokenAuth(""), session) - an intentionally empty bearer token - because local devices do not validate credentials, yet every request still carries an Authorization: Bearer header. Addresses must be bare hosts (192.168.1.42, device.local, optionally host:port); the library prepends http:// and appends /settings/config/data itself, so an address containing a scheme yields a malformed URL. The list is stored by reference (no copy) and re-read on every devices() 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; subclassing AwairAuth (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() GETs const.USER_URL and wraps the body as AwairUser(client=..., attributes=response); the user retains that client, so await user.devices() hits const.DEVICE_URL with 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 via asyncio.gather and returns AwairLocalDevice objects in the same order as the address list as it stands at devices() 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 (AwairError when no authenticator and no truthy token); credential rejection by the server still surfaces as AuthError (401/403) per awaited request, not at construction.
  • Authenticator beats token when both are given; the unchosen token is ignored entirely.
  • AwairLocal keeps device_addrs as a live reference and re-reads it inside each devices() 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 at devices() call time, not construction time.
  • The errors-array scan runs even on a 200; Too many requests is a case-sensitive substring check that reads each entry's message key directly, so an entry without that key raises KeyError before 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 raw json.JSONDecodeError, not an AwairError. Any other non-JSON, non-text/html content type goes through resp.json(), which raises aiohttp's ContentTypeError (not AwairError) 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 the Bearer scheme 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 of query() 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

  1. Headers first. Before any network I/O, query awaits the authenticator's bearer token and builds {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}. This means get_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 of query before a request is ever issued.
  2. Status gate before body parsing. The response status is checked inside the async with block before the body is read. Any non-200 status short-circuits: the body is never decoded, and __handle_non_200_error always raises (its NoReturn contract). There is no retry, no backoff, and no attempt to read error detail from the response body.
  3. Content-type-aware JSON decoding. On a 200, the client checks resp.content_type. Awair Omni devices with the Ethernet backpack answer with text/html bodies that are nonetheless valid JSON, so in that case the client reads await resp.text() and applies json.loads explicitly. For any other content type it uses await resp.json() directly — which means a 200 answered with any non-JSON content type (e.g. text/plain) raises aiohttp's own ContentTypeError, uncaught. This is a test-sensitive quirk: a mock response declaring text/html must still yield parseable JSON text, or json.JSONDecodeError escapes uncaught — the library makes no effort to translate malformed bodies or unusable content types into AwairError.
  4. 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 uncaught TypeError at the subsequent json["errors"] indexing. Non-iterable scalar payloads (int, float, bool, None) never reach a return at all: the membership test itself raises an uncaught TypeError. A string payload undergoes substring matching — one containing "errors" passes the check and then raises TypeError at the indexing; one that does not is returned as-is.
  5. 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.")
  • 401 or 403 → AuthError
  • 404 → NotFoundError
  • 429 → 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 bare RatelimitError() 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 uncaught KeyError at 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 uncaught KeyError at the rate-limit scan, so an entry reaching aggregation always contributes its actual message value. 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 errors list ([]) passes through: messages stays 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/html is matched on the exact content type; application/json takes the normal resp.json() path (aiohttp's own decoder, honoring its content-type check). Any other 200 content type — e.g. text/plain — makes resp.json() raise aiohttp.ContentTypeError uncaught, mirroring the existing uncaught json.JSONDecodeError escape for malformed bodies: neither is ever translated into AwairError.
  • The bearer token is interpolated into the Authorization header verbatim; no scheme rewriting or whitespace stripping occurs.
  • query accepts any URL string — cloud endpoints and local-device URLs (AwairLocal pointed 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_id comes from the required "id" key; a payload without it raises KeyError at construction. No type coercion is performed, so user_id stores the payload's "id" value verbatim: the API documents the field as a string (and the class annotates it as str), but a payload supplying digits without quotes yields a non-str user_id at runtime. The repr is unchanged either way, since the value is formatted through an f-string.
  • email, first_name (payload key "firstName"), last_name ("lastName"), sex, and tier default to None when absent. sex is conventionally one of 'MALE', 'FEMALE', or 'UNKNOWN'; tier nominally drives quotas, but the library performs no tier-based logic.
  • dob becomes a datetime.date only when all three of "dobDay", "dobMonth", "dobYear" are present and truthy; otherwise it is None. There is no partial-date support - one missing or zero-valued component discards the whole date. Absent/falsy is the only route to None: truthy components that do not form a valid calendar date (e.g. dobMonth=2 with dobDay=30, or a non-leap Feb 29) are not coerced to None - the constructor calls datetime.date(day=..., month=..., year=...), so out-of-range truthy values raise ValueError at construction, and non-numeric truthy values raise TypeError.
  • usages maps scope -> usage and permissions maps scope -> 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 raises KeyError rather 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

  1. "id" missing causes KeyError in the constructor; so does a usage/permission item lacking "scope" or its value key.
  2. Falsy DOB components (e.g. 0) are treated as absent, yielding dob = None; truthy-but-invalid or non-numeric DOB components instead propagate ValueError (or TypeError) from the constructor.
  3. Missing "usages" or "permissions" payload keys yield {}; missing "devices" in the device response yields []. Duplicate scopes are last-wins.
  4. The repr email clause appears iff the email is present.
  5. devices() is a coroutine - constructing a user never triggers network I/O.
  6. user_id stores the payload's "id" value verbatim with no type coercion: digits without quotes yield a non-str user_id (the repr output 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/devices and wraps each returned mapping in an AwairDevice, 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 concurrent GET http://{addr}/settings/config/data per supplied address (via asyncio.gather) and wraps each response in an AwairLocalDevice, 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:

  • model is a property, computed on access from device_type via const.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 raw device_type string, so model is never None. (The docstring table labels awair-mint as Awair Baby; the constant mapping is what actually runs.)
  • location_name is declared (annotation and docstring) on AwairBaseDevice, but __init__ never reads a locationName key and never assigns the attribute. On any discovered or hand-built device, device.location_name raises AttributeError — despite the "defaults to None" list above, this is not a populated optional field.
  • Local devices do not receive IDs from the wire. AwairLocalDevice.__init__ requires device_uuid in the config payload and derives all three identifiers by splitting on the first underscore: awair-element_123 becomes type awair-element and numeric id 123 (coerced with int, so a non-numeric suffix or a uuid without _ fails). wifi_mac maps to mac_address (optional); fw_version is stored as an extra attribute — firmware version is exposed only on local devices. device_addr is stored verbatim, IP or DNS.
  • repr() is identical for both subclasses: <AwairDevice: uuid=... model=...>.
  • room_type/space_type/preference/timezone are 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} under https://developer-apis.awair.is/v1/users/self/devices; local base is bare http://{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 except timestamp and score becomes {comp: key, value: value} under sensors — and yields exactly one datapoint per response. A local response missing timestamp/score raises KeyError.
  • 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 default extra=PREVENT_EXTRA, so an unexpected key raises vol.Invalid ("extra keys not allowed @ data[...]"). fahrenheit/desc are coerced to lowercase strings (true/false); limit is 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 a now attribute — e.g. a string or an int — raises the instances of datetime error (the check is duck-typed, not isinstance); (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 (every datetime exposes now via its class) and then fails at the future-date comparison — an offset-aware datetime compared against naive datetime.now() raises TypeError ("can't compare offset-naive and offset-aware datetimes"), not the instances of datetime message. Only supplied dates are stringified with str() and URL-encoded — the validation defaults are never sent, so omitting from_date/to_date defers the default window to the server. Empty kwargs produce no query string at all.
  • Ordering: desc is forwarded only when explicitly supplied (coerced to true/false); when omitted it is not sent, so the docstring's True/newest-first default is an API-level behavior not enforced or sent by this library — exactly parallel to the from_date/to_date defaults note above.
  • Local quirks: fahrenheit=True raises ValueError (fahrenheit is not supported for local sensors yet); a falsy fahrenheit is 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 raise vol.Invalid on 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 override
    • Expected 'from_date' and/or 'to_date' to be instances of datetime
    • Dates 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 with datetime.strptime using const.DATE_FORMAT ("%Y-%m-%dT%H:%M:%S.%fZ"). The result is a naive datetime: the trailing Z is 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 against datetime.strptime(payload["timestamp"], const.DATE_FORMAT) — an aware datetime or a hand-built datetime(...) with tzinfo will not compare equal. The %f component 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 as round(score, 2) — a rounded float displayed with Python's normal float repr, not f"{score:.2f}" fixed formatting (score 2.0 renders as 2.0, not 2.00).
  • sensors — a Sensors mapping built from attributes.get("sensors", []); each list entry contributes entry["comp"] -> entry["value"].
  • indices — an Indices mapping built identically from attributes.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/indices lists, or absent keys, yield empty mappings; air.sensors.temperature on an empty mapping raises the AttrDict's attribute-not-found error, and air.sensors["temp"] raises KeyError.
  • A sensors entry missing "comp" or "value" raises KeyError during construction; a non-dict entry raises a TypeError from the subscript.
  • repr(AirData) must produce <AirData@{timestamp}: score={rounded score} sensors={sensors}>, where the rounded score is round(score, 2) shown with Python's float repr (so 2.0 renders 2.0, not 2.00), and the mappings render as Sensors({...}) / 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) -> raise AwairError("No authentication supplied!"); stores the client as .client.
  • AwairLocal(session, device_addrs): non-empty list required at construction, else AwairError("No local Awair device addresses supplied!"); the list is retained by reference and re-read at each devices() 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 is AwairClient(AccessTokenAuth(""), session). devices() GETs http://<addr>/settings/config/data per address concurrently (asyncio.gather) and returns AwairLocalDevice objects in input order.
  • AwairClient(authenticator, session).query(url): headers Authorization: Bearer <await authenticator.get_bearer_token()> plus Content-Type: application/json; non-200 maps 400 -> QueryError, 401/403 -> AuthError, 404 -> NotFoundError, 429 -> RatelimitError, else AwairError; a 200 with text/html is parsed via json.loads(await resp.text()), else resp.json() - a 200 with any other non-JSON content type raises aiohttp's ContentTypeError before the errors-array scan; a body errors key raises RatelimitError if any entry's message contains Too many requests - that check reads error["message"] directly, so an entry lacking message raises KeyError, and the .get("message", "Unknown error") default is unreachable dead code - else AwairError(", ".join(messages)) (empty list -> no raise); returns the parsed JSON.
  • AccessTokenAuth(access_token): async get_bearer_token() returns the stored token unchanged; AwairAuth is an ABC with an abstract async get_bearer_token.
  • AttrDict(attrs): copies the mapping and renames any const.SENSOR_TO_ALIAS key at init only; dot access mirrors dict items; missing attributes raise AttributeError on reads, while deleting a missing key raises KeyError (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", plus SENSOR_TO_ALIAS and AWAIR_MODELS with 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

  • AwairAuth is an ABC with a single abstract coroutine get_bearer_token() -> str; instantiating it, or a subclass without the override, raises TypeError at construction.
  • The override must be a coroutine function; the client awaits its result, so a sync def returning str fails at request time, not at import.
  • AwairClient awaits get_bearer_token() on every request and builds Authorization: Bearer {token} plus Content-Type: application/json; the token is never cached and the Bearer prefix 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 attribute access_token and returns it unchanged, so reassigning the attribute changes later requests.
  • HTTP 401 and 403 both raise AuthError (subclass of AwairError) before response-body parsing; its literal message is The 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) awaits get_bearer_token() before each request; headers are exactly Authorization: Bearer <token> and Content-Type: application/json.
  • Status checked before body: 400→QueryError, 401/403→AuthError, 404→NotFoundError, 429→RatelimitError, all other non-200→base AwairError. Raised bare (no extra message), so str(exc) equals the class message exactly.
  • 200 bodies with content type text/html (Omni Ethernet backpack) are decoded via await resp.text() + json.loads; every other content type goes through await resp.json(), which raises uncaught aiohttp.ContentTypeError for any non-JSON content type (e.g. text/plain) — the same uncaught-escape behavior as json.JSONDecodeError for malformed JSON.
  • After decoding, if the payload contains key "errors": the scan indexes each entry directly (error["message"]), so any entry whose message contains the substring "Too many requests" raises RatelimitError() immediately (later entries ignored), and an entry lacking a "message" key raises an uncaught KeyError at the scan. Entries that do reach aggregation contribute error.get("message", "Unknown error") — the fallback literal is unreachable because the scan already raised on message-less entries — and a non-empty list raises AwairError(", ".join(messages)), yielding "Error querying the Awair API. <joined>".
  • Message composition for all exceptions: message + " " + extra_message when extra_message is truthy, else message alone. Every error type subclasses AwairError.
  • The errors-array gate is the bare expression "errors" in json with 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 uncaught TypeError at the membership test itself; a string payload is substring-matched, and one containing "errors" passes the test and then fails with uncaught TypeError at json["errors"] (a list containing the literal element "errors" fails the same way at the indexing).
  • Malformed JSON (including from a text/html body) raises json.JSONDecodeError uncaught; 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) where attributes mirrors the /users/self body; in production, obtain instances via Awair.user() instead. Construction performs no I/O.
  • attributes["id"] is mandatory and becomes user_id, stored verbatim with no type coercion - it is a str only because the API's payload shape documents it that way, so a payload supplying digits without quotes yields a non-str at runtime. All other profile fields are optional and default to None: email, first_name (firstName), last_name (lastName), sex, tier.
  • dob is a datetime.date only when dobDay, dobMonth, and dobYear are all present and truthy; otherwise None. Truthy-but-invalid components are not coerced to None: the constructor calls datetime.date(day=..., month=..., year=...), so out-of-range calendar values (e.g. dobMonth=2 with dobDay=30, or a non-leap Feb 29) raise ValueError at construction, and non-numeric truthy components raise TypeError; only absent/falsy components yield dob=None.
  • usages and permissions are scope-keyed dicts built from payload lists whose items must contain scope plus usage / quota. Missing payload keys yield empty dicts; missing item keys raise KeyError. Duplicate scope entries in the payload lists are resolved last-wins, with no error or accumulation.
  • Counts are per usage window (resets at midnight, timezone unspecified). permissions holds per-scope maxima, usages holds consumption; scopes with zero use may be absent from usages, so read them with .get(scope, 0). No client-side enforcement.
  • await user.devices() GETs DEVICE_URL (USER_URL + "/devices") with the stored client and maps the response's devices list to AwairDevice objects sharing that client; a missing devices key yields []. Ordering is the API's order.
  • HTTP failures (auth, rate-limit, query, not-found) propagate from the client unchanged; AwairUser adds no errors of its own around HTTP.
  • repr is <AwairUser: user_id=<id>>, appending email=<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

  • AwairBaseDevice is an ABC; instantiating it — or a subclass that does not override _get_airdata_base_url and _extract_airdata — fails. The abstract methods themselves raise TypeError (expected subclass to define override) if invoked on a hand-built instance.
  • Cloud construction requires the deviceId, deviceUUID, deviceType keys; every other metadata field defaults to None when the key is absent. Exception: location_name is declared on AwairBaseDevice but __init__ never reads a locationName key or assigns the attribute, so accessing it raises AttributeError on every device (cloud, local, or hand-built).
  • Local construction requires device_uuid of the form {device_type}_{int}; the type/id are split on the first underscore and the id is int-coerced. wifi_mac becomes mac_address; fw_version and device_addr exist only on AwairLocalDevice.
  • model resolves as AWAIR_MODELS.get(device_type, device_type) — never None, falls back to the API type string.
  • Air-data URLs: cloud /users/self/devices/{device_type}/{device_id}/air-data/{kind}; local http://{device_addr}/air-data/{kind}. Cloud responses read data (default []); local responses reshape all non-timestamp/score keys into a single sensors datapoint.
  • Shared kwargs fahrenheit, desc, limit, from_date, to_date: booleans lowercased to strings, limit bounded 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' default extra=PREVENT_EXTRA, so an extra key raises vol.Invalid ("extra keys not allowed @ data[...]"). Shared call path: AwairLocalDevice._format_args deletes a falsy fahrenheit (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 None check in __get_airdata is always true — **kwargs can never be None — so the only empty-kwargs behavior is the empty query string returned by _format_args; there is no None-handling path.
  • fahrenheit=True on a local device raises ValueError; falsy fahrenheit is silently removed before delegating to the base formatter.
  • AwairLocal.devices() queries all addresses concurrently and returns devices in device_addrs order; 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 in const.DATE_FORMAT, %Y-%m-%dT%H:%M:%S.%fZ) and "score" (number). Missing either → KeyError; unparseable timestamp → ValueError from strptime. The %f field is required, so timestamps without fractional seconds fail.
  • Parsed timestamp is a naive UTC datetime — no tzinfo is attached (the Z is a format literal). Compare against datetime.strptime, not aware datetimes.
  • score is stored unrounded; only __repr__ renders it as round(score, 2) — a rounded float in Python's normal float repr, not f"{score:.2f}" fixed formatting (score 2.0 renders as 2.0, not 2.00).
  • sensors and indices come from attributes.get(..., []): absent or empty lists yield empty mappings, never errors.
  • Each list entry contributes entry["comp"] -> entry["value"]; extra keys are ignored, duplicate comps resolve last-wins, and entries missing comp/value raise KeyError.
  • Sensors and Indices are 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 additionally illuminance/sound_pressure_level for 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 the AttrDict dict-key fallback; a name that is neither an alias nor a stored key raises the AttrDict'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.