Metadata-Version: 2.4
Name: combustion_cloud
Version: 0.1.0
Summary: Asynchronous Python client for Combustion MeatNet Cloud
Author-email: Larry Gregory <lgregorydev@gmail.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/legrego/combustion_cloud
Project-URL: Repository, https://github.com/legrego/combustion_cloud
Project-URL: Issues, https://github.com/legrego/combustion_cloud/issues
Project-URL: Changelog, https://github.com/legrego/combustion_cloud/blob/main/CHANGELOG.md
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp<4,>=3.14
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: mypy>=1.15; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: pytest-cov>=5; extra == "dev"
Requires-Dist: pytest-timeout>=2.3; extra == "dev"
Requires-Dist: ruff>=0.9; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"
Dynamic: license-file

# combustion_cloud

An asynchronous, read-only Python client for **Combustion MeatNet Cloud**. It uses
HTTP snapshots and WebSocket updates to read account-linked devices from outside
Bluetooth range. It is independent of Home Assistant and of
[`combustion_ble`](https://github.com/legrego/combustion_ble).

Home Assistant is the primary integration target: you can inject its shared
`aiohttp.ClientSession`, persist a refresh token rather than a password, cancel the
live stream on unload, and distinguish authentication failures from network errors.
The package has no Home Assistant dependency.

## Status

This is an initial, experimental client for an **undocumented service**. Protocol
research used Android app v3.3.17 and a successful read-only capture on November 23,
2026. Email/password sign-in, token exchange, three probe snapshots/preferences,
cook metadata, live probe messages and an intentional reconnect were verified.

Gauge and Engine payloads are represented but have not been verified live. Natural
token expiration, recovery from network failures, and long-running operation have
automated tests but still need real-device soak testing. Historical sample downloads,
Google sign-in UI, account linking and device control are outside this first release.

You need a **Combustion account**, linked devices, and a WiFi accessory or another
device running the Combustion app to upload readings. A store account is separate.
Target temperatures, SafeCook configuration and other physical commands continue
to require Bluetooth. See [Combustion's MeatNet Cloud overview](https://combustion.inc/pages/features/meat-net-cloud-watch-your-cook-from-anywhere).

## Install

Requires Python 3.11 or newer:

```sh
python -m pip install combustion_cloud
```

The runtime dependency is `aiohttp>=3.14,<4`; earlier versions drop the
live connection while a consumer is busy.

## Read linked devices

```python
import asyncio
import getpass

from combustion_cloud import CombustionCloudClient


async def main():
    email = input("Combustion email: ")
    password = getpass.getpass("Password: ")
    async with CombustionCloudClient() as client:
        await client.login(email, password)
        account = await client.get_account()
        for device in account.devices:
            status = await client.get_status(device)
            print(device.serial_number, status.is_fresh(), status.temperatures)
            print("Core:", status.virtual_temperature("core"))


asyncio.run(main())
```

For a runnable read-only example, see
[`examples/watch.py`](https://github.com/legrego/combustion_cloud/blob/main/examples/watch.py). It prompts locally
and prints temperatures without logging passwords or tokens. Ctrl-C stops it.

## Listen for live updates

```python
from contextlib import aclosing

from combustion_cloud import (
    ApiError,
    CloudConnectionError,
    CloudEvent,
    Connected,
    DeviceStore,
    Disconnected,
    ProtocolError,
)

store = DeviceStore()
async with aclosing(client.events()) as events:
    async for event in events:
        match event:
            case Connected():
                # No initial WebSocket snapshot is assumed. Reconcile on every connection.
                try:
                    snapshot = await client.get_snapshot()
                except (ApiError, CloudConnectionError, ProtocolError) as error:
                    print("Snapshot failed, live updates continue:", error)
                    continue
                for status in snapshot.statuses.values():
                    store.update(status)
                for identity, error in snapshot.errors.items():
                    print(identity.serial_number, "could not be read:", error)
            case Disconnected(retry_after=seconds):
                print("Reconnecting in", seconds, "seconds")
            case CloudEvent(status=status) if status is not None:
                if store.update(status):
                    print(status.identity, status.virtual_temperature("core"))
```

Server messages are always `CloudEvent`, whatever their type. `Connected` and
`Disconnected` come only from the client. REST failures in your loop are yours to
handle, as above: the stream's retries cover only its own connection. After a failed
snapshot, schedule another rather than waiting for the next connection.

`get_snapshot()` reads every linked device and reports the ones that fail in
`snapshot.errors`. It raises only when the account itself can't be read, when sign-in
is required, or when the client closes.

Use one `events()` iterator per client. It starts no hidden tasks. Network, server and
rate-limit failures use exponential backoff with jitter, starting afresh once a
connection has lasted a minute; HTTP 429 respects `Retry-After`. A handshake rejected
with HTTP 401 or 403 is retried once after refreshing credentials. Authentication,
permission and other HTTP errors propagate to the caller. Unreadable messages are
logged and skipped. Active sockets are rotated before the ID token expires.
`reconnect=False` raises on the first interruption, and ends the iterator at rotation.

Wrap the iterator in `aclosing` when breaking early. Cancellation or `client.close()`
also closes the active socket. Closing the client ends the iterator, waking a pending
reconnect wait or interrupting a handshake.

## Freshness and state

**HTTP 200 does not mean a device is online.** The verified capture returned one
snapshot about four weeks old. `DeviceStatus.sampled_at` comes from
`collected_timestamp`; `published_at` is the later cloud timestamp. Neither is
replaced by local receipt time. Missing sample times are treated as not fresh.

`status.is_fresh()` defaults to 30 seconds. Sample times come from whichever device
uploaded the reading, so up to one minute of future clock skew is tolerated; pass
`max_age` and `clock_skew` to suit your uploaders. An unusable sample time is treated
as missing, without losing the reading. `DeviceStore` rejects older samples, preventing
a late REST response from overwriting a newer live message. A sample from too far in
the future neither blocks nor replaces believable ones. Use `DeviceStore.remove` for
unlinked devices, but only when `account.skipped_associations` is 0. Consumers own
availability timers so a silent device can become unavailable even when no event
arrives. A connected socket does not make every linked device online.

Temperatures are Celsius. `sample_period_ms` is milliseconds. Virtual selectors
such as `T1` refer to positions in the eight-temperature tuple. Prediction state,
mode, type, battery state and SafeCook values are strings, with unfamiliar values
preserved. The low battery value observed is `LOW_BATTERY`.

`prediction.remaining_seconds` follows `combustion_ble`: it is set only while
`PREDICTING`, 0 for `REMOVAL_PREDICTION_DONE`, and otherwise `None`. The client does
not decrement countdowns.

`food_safe_data` is the SafeCook program and `food_safe_status` its progress. Either is
`None` when absent, null or unusable, as is `food_safe_data.completion_criteria`. The
client never substitutes zeros, calculates food safety or infers a safety state.

A probe with SafeCook turned off still reports a program, and progress as `NOT_SAFE`. Check
`food_safe_data.program_set` before using either.

Models are immutable and hashable, and keep unknown fields in `raw`. `as_dict()` returns
plain JSON-compatible data. It includes account and device identifiers, so redact it
before sharing.

## Device identity

`DeviceIdentity` is the product type plus serial number. Probe serials are 8 uppercase
hex digits, the same as `combustion_ble`'s `Probe.serial_number_string`. Convert with
`DeviceIdentity.probe(probe.serial_number)` and `identity.probe_serial`.

## Home Assistant integration

See [the integration notes](https://github.com/legrego/combustion_cloud/blob/main/docs/home-assistant.md). A minimal session setup is:

```python
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from combustion_cloud import CombustionCloudClient

client = CombustionCloudClient(
    session=async_get_clientsession(hass),
    on_token_update=persist_session,
)
await client.resume(saved_refresh_token)
```

`persist_session(tokens)` is a synchronous callback called whenever credentials are
issued or rotated. Persist `tokens.refresh_token` using the consumer's credential
storage. Exceptions it raises are logged by type and traceback, without their text, and
don't end the session. An `async` function is refused with `TypeError`; start a task from
a synchronous one instead. Never log the
`tokens` object or put credentials in diagnostic reports. The token dataclass hides all fields
from `repr`, and exceptions exclude URLs and server bodies. The library logs under
`combustion_cloud` without identifiers, URLs or payloads. Do not enable HTTP wire
tracing on authenticated requests.

The client never changes default headers or closes an injected session. It closes
a session it created itself. Explicit `close()` is idempotent; a closed client cannot
be reused. A client instance represents one account.

## Public API

- `login(email, password)` / `resume(refresh_token)` / `refresh()` return `AuthTokens`.
- `get_account()` returns current linked `DeviceIdentity` values and preferences.
- `get_snapshot()` returns a `Snapshot` of the account and every linked device's status.
- `get_status(device)` returns an immutable `DeviceStatus` for an identity or serial.
- `get_preferences(device)` returns immutable device metadata/preferences.
- `get_sessions(page=1, page_size=20)` returns one `SessionPage` of cook metadata.
- `events(reconnect=True)` yields `CloudEvent`, `Connected` and `Disconnected` values.
- `close()` releases resources owned by the client.

Exceptions derive from `CombustionCloudError`: `AuthenticationError`,
`CloudConnectionError`, `ProtocolError`, `ApiError`, `PermissionDeniedError`,
`RateLimitError` and `ClientClosedError`. `ApiError.status` exposes the HTTP status and
`ApiError.code` an authentication service code such as `API_KEY_INVALID`;
`RateLimitError.retry_after` exposes seconds when supplied by the server. Only
`AuthenticationError` means the user has to sign in again. A revoked session is
remembered, so later calls fail without contacting the service until then.

## Development

```sh
python -m venv .venv
.venv/bin/python -m pip install -e '.[dev]'
.venv/bin/pytest
.venv/bin/ruff check .
.venv/bin/ruff format --check .
.venv/bin/mypy
.venv/bin/python -m build
```

Tests use synthetic account/device data and a local fake service, never user
credentials or live accounts. See [protocol evidence](https://github.com/legrego/combustion_cloud/blob/main/docs/protocol.md) for the
verified contract and remaining uncertainty. This project is unofficial and is not
affiliated with Combustion Inc. Licensed under Apache-2.0.
