Skip to main content

neakasa-litterbox-sdk

CI PyPI

Sponsor

Async Python SDK for the Neakasa M1 self-cleaning cat litter box.

⚠️ Unofficial. This project is not affiliated with, endorsed by, or supported by Neakasa or its parent company. It targets the publicly-reachable Neakasa cloud API and the Aliyun IoT gateway their mobile app uses. The vendor can change either side at any time and break this SDK without notice.

Status

Alpha — usable but not yet stable.

Area State
Email/password login + persisted sessions ✅
Device list, history (cats, toilet records, daily statistics) ✅
Live device status (sand level, cat presence, mode flags) ✅
Device commands (clean, level, calibrate, toggles) ✅
Real-time MQTT push (watch_status) ✅
Automatic reconnect with backoff after a dropped push session ✅
Async-native API (aiohttp + aiomqtt) ✅
Public API stability ❌ breaking changes still happen across 0.x releases
Multi-device user accounts ⚠️ untested — designed for it, but only validated against single-device setups
Regions other than US ⚠️ EU/AP endpoints declared, only US is exercised live

See CHANGELOG.md for breaking changes between releases.

Install

pip install neakasa-litterbox-sdk

Or, with uv:

uv add neakasa-litterbox-sdk

Requires Python 3.14+.

Quick start

import asyncio
from neakasa_litterbox_sdk import NeakasaClient, Region


async def main() -> None:
    async with NeakasaClient(email="you@example.com", password="…", region=Region.US) as client:
        await client.login()
        for device in await client.list_devices():
            print(device.product_name, device.device_name, device.role.name.lower())
            for cat in await client.list_cats(device.device_name):
                print(" ", cat.name, cat.weight, cat.unit)


asyncio.run(main())

API

The package re-exports everything below from neakasa_litterbox_sdk; deeper import paths are internal and may change. The whole SDK is asyncio-native — every I/O method is a coroutine and the client doubles as an async context manager that closes its underlying HTTP sessions on exit.

NeakasaClient

The single entry point. Holds session state in memory. Use as an async context manager so the underlying aiohttp sessions tear down cleanly.

NeakasaClient(
    email: str,
    password: str,
    region: Region = Region.US,
    timeout: float = 10.0,
    language: str = "en",
)

All I/O methods are coroutines (prefix every call with await).

Method Signature Purpose
login async (*, cached: LoginResult | None = None) -> LoginResult Establish a session. With cached= resumes the stored one idempotently; without it forces a fresh login.
list_devices async () -> list[Device] Devices on the account (mobile-app "device picker").
get_status async (device_name: str) -> DeviceStatus Live property snapshot — sand level, cat presence, mode switches.
list_cats async (device_name: str) -> list[Cat] Cat profiles registered against a device.
set_cat_weight async (device_name: str, cat_id: int, weight: float, *, unit: Literal["kg", "lb"], zone_seconds: int = 0) -> None Update an existing cat's profile weight without changing other profile fields.
get_toilet_records async (device_name: str, start_time: int, end_time: int) -> list[ToiletRecord] Visit history (unix-second bounds).
get_toilet_statistics async (device_name: str, start_time: int, end_time: int, *, zone_seconds: int = 0) -> list[DailyStatistics] Per-day aggregates. zone_seconds is the UTC offset for bucket alignment (e.g. -10800 for America/Sao_Paulo).
start_clean / stop_clean async (device_name: str) -> None Run / cancel a cleaning cycle — mobile app's "Clean Now".
start_level / stop_level async (device_name: str) -> None Run / cancel the leveling motor — redistributes litter evenly.
calibrate_sand async (device_name: str, percent: int) -> None Tell the device the current physical load is percent (1–100) of "full".
set_auto_clean async (device_name: str, enabled: bool) -> None Toggle scheduled auto-cleaning. Preserves the device's existing mode/interval.
set_auto_level async (device_name: str, enabled: bool) -> None Toggle automatic litter-leveling after each clean cycle.
set_silent_mode async (device_name: str, enabled: bool) -> None Suppress motor / status sounds while on.
set_child_lock async (device_name: str, enabled: bool) -> None Ignore manual button presses while on.
watch_status (*, ca_certs=None, tls_context=None, reconnect=DEFAULT_RECONNECT_POLICY) -> StatusStream Build a live MQTT push stream — use as an async with context manager and register per-event handlers on the returned stream. See Reconnecting and Broker TLS.
close async () -> None Close the underlying HTTP sessions. Idempotent; async with client also does this on exit.
Property Type
region Region The cloud region this client targets.
is_authenticated bool True once login() has succeeded.
login_result LoginResult | None The active session, or None.

To update a cat's profile weight, use its id from list_cats() and supply the weight's unit explicitly:

cats = await client.list_cats(device_name)
cat = next(cat for cat in cats if cat.name == "Mini")
await client.set_cat_weight(device_name, cat.id, 4.8, unit="kg", zone_seconds=-14400)
updated = next(item for item in await client.list_cats(device_name) if item.id == cat.id)

weight must be finite and positive, and cat_id must be positive. The method sends only the weight, unit, and request context; name, birthday, avatar, and other profile fields are preserved. A successful call means the cloud accepted the update; read back with list_cats() to confirm it. It does not assign past visits to the cat. As with statistics, zone_seconds is the UTC offset in seconds (default UTC). The request format follows Android 2.3.4's CatVm.addOrUpdateCat.

Models

All dataclasses are frozen=True, slots=True.

Device — one entry of list_devices().

Field Type Notes
iot_id str Stable per pairing.
product_key str
product_name str e.g. Neakasa_M1.
device_name str Identifier the history endpoints accept.
category_key / category_name str
net_type str
role DeviceRole OWNER or SHARED.
status int
bind_time int Unix seconds.

Cat — one entry of list_cats().

Field Type Notes
id int Matches ToiletRecord.cat_id.
name str
weight / unit float, str
avatar / birthday / path str
variety int Breed code; -1 if not set.
gender CatGender UNKNOWN / MALE / FEMALE.
sterilization / enabled int Raw flags.

Properties: is_sterilized: bool, is_enabled: bool.

ToiletRecord — one entry of get_toilet_records().

Field Type Notes
record_id int
record_type RecordType CAT_VISIT / CLEAN_CYCLE / OTHER.
cat_id int 0 when no cat was matched.
start_time / end_time int Unix seconds.
weight / unit float, str For CAT_VISIT, the cat's measured weight.
way int Preserved from the wire; semantics not yet pinned down.

Property: duration_seconds: int.

StatusUpdate — one push delivered by watch_status().

Field Type Notes
device_name str Same identifier the history endpoints accept.
changes dict[str, JsonValue] Only the fields that changed. Known keys are snake_case (matching DeviceStatus); unknown ones pass through under the original camelCase name with the raw value.
received_at float Client-side time.time() when the push arrived.

StatusStream — returned by watch_status(). Register one handler per event type; each is fire-and-forget (no return):

Handler Signature Fires on
on_silent_mode / on_child_lock / on_auto_level / on_young_cat_mode / on_cleaning_enabled / on_cat_present / on_needs_cleaning / on_bucket_full (device_name: str, value: bool) -> None The corresponding DeviceStatus bool flipping.
on_sand_percent / on_cat_stay_seconds (device_name: str, value: int) -> None The corresponding int changing.
on_last_sand_added / on_last_action (device_name: str, value: str) -> None The string-typed property updating.
on_operating_state (device_name: str, value: OperatingState) -> None The box changes activity (idle / cleaning / restoring / leveling / cat_appears).
on_unknown (device_name: str, raw_key: str, raw_value: JsonValue) -> None A property the SDK doesn't yet model (raw passthrough).
on_change (update: StatusUpdate) -> None Every push, after the per-event handlers — catchall.

Handlers run on the same asyncio loop as the rest of the SDK; keep them non-blocking and offload heavy work via asyncio.create_task. Use the stream as async with client.watch_status() as stream: and await stream.run_forever() to block until the stream stops — see Reconnecting for what happens when the broker drops the session.

ReconnectPolicy — the retry schedule watch_status() follows.

Field Type Default Notes
max_attempts int 5 Attempts before the stream gives up.
initial_delay float 1.0 Seconds before the first attempt.
max_delay float 60.0 Ceiling for the growing delay.
multiplier float 2.0 Growth factor applied per attempt.

Method: delay_for(attempt: int) -> float — the wait before a 1-based attempt. DEFAULT_RECONNECT_POLICY is an instance carrying the defaults above.

DeviceStatus — return value of get_status().

Field Type Notes
sand_percent int Litter level, 0–100.
cat_present bool A cat is currently in the box.
cat_stay_seconds int How long the cat has been there.
needs_cleaning bool Device flagged a pending clean.
bucket_full bool Waste bin needs emptying.
operating_state OperatingState Activity: idle / cleaning / restoring / leveling / cat_appears (cat inside).
last_sand_added str Server-formatted "YYYY-MM-DD HH:MM:SS".
last_action str Device-reported description of its last action.
cleaning_enabled / auto_level / silent_mode / child_lock / young_cat_mode bool Mode switches.
wifi_name / ip_address / mac_address str Network diagnostics.
wifi_rssi int Signal strength in dBm (negative).
firmware_version / hardware_version str Reported by the device.
updated_at int Snapshot timestamp (epoch ms).

get_status() does not cache — every call hits the device gateway. "Last cleaned at" is not on this readback; query get_toilet_records() and filter by record_type == RecordType.CLEAN_CYCLE.

DailyStatistics — one entry of get_toilet_statistics().

Field Type
date str YYYY-MM-DD.
num int Visits in the bucket.
weight / unit float, str
toilet_total_second int Total occupied seconds.
weight_avg float Average cat weight.

LoginResult — the session blob.

Treat it as opaque; persist via to_dict()/from_dict() and pass to client.login(cached=...) on the next run.

Method Signature
to_dict () -> dict[str, JsonValue] JSON-safe snapshot.
from_dict (data: dict) -> LoginResult Classmethod; restore.
age_seconds (now: float | None = None) -> float Seconds since issued_at.

Exposes user_info: UserInfo for diagnostics (user_id, user_name, ali_user_id). Other fields are session-internal.

Region — enum with US (default), EU, AP. Mainland China is out of scope.

DeviceRole — IntEnum: OWNER = 1, SHARED = 2. The numeric values match the server's per-call role filter so the SDK can pass them through without conversion.

CatGender — IntEnum: UNKNOWN = 0, MALE = 1, FEMALE = 2.

RecordType — IntEnum: CAT_VISIT = 1, CLEAN_CYCLE = 2, OTHER = 3.

Exceptions

NeakasaError
├── ApiError                    (non-zero envelope code)
│   └── AuthenticationError
│       ├── SessionExpiredError      (codes 1007 / 3026 / 3027)
│       └── InvalidCredentialsError  (codes 10060 / 10061 / 10192)
└── TransportError              (HTTP / network failure)

Catch the narrowest class that fits; AuthenticationError is the catch-all for "auth went wrong".

Caching the session

The server does not advertise an expiry; the official app uses the token until an auth-failure code comes back, then re-logs in. The SDK exposes the issue timestamp so consumers can persist LoginResult and reuse it across runs:

import asyncio, json
from pathlib import Path
from neakasa_litterbox_sdk import LoginResult, NeakasaClient


async def run() -> None:
    cache = Path(".neakasa-session.json")
    stored = LoginResult.from_dict(json.loads(cache.read_text())) if cache.exists() else None

    async with NeakasaClient(email="…", password="…") as client:
        result = await client.login(cached=stored)
        if result is not stored:
            cache.write_text(json.dumps(result.to_dict()))


asyncio.run(run())

result is not cached cleanly distinguishes "minted something" from "nothing changed". The SDK does not recheck staleness — the caller decides their TTL policy and skips cached= whenever they want a refresh.

Handling token expiry

The SDK does not refresh the session automatically. On SessionExpiredError the caller should:

  1. Call client.login() (no cached=) for a fresh LoginResult.
  2. Persist that result.
  3. Retry the original call.
from neakasa_litterbox_sdk import SessionExpiredError


async def call_and_persist(client, cache):
    try:
        return await client.list_devices()
    except SessionExpiredError:
        result = await client.login()
        cache.write_text(json.dumps(result.to_dict()))
        return await client.list_devices()

InvalidCredentialsError and bare AuthenticationError propagate without retry — they signal a hard failure (wrong password, account locked, …) that re-login cannot fix.

Reconnecting

When the broker drops the MQTT session, the stream rebuilds it in the background: it waits initial_delay seconds, opens a fresh connection, re-subscribes and re-binds the account, and multiplies the delay by multiplier (capped at max_delay) before each further attempt. A successful attempt is transparent — run_forever() never returns and the registered handlers keep firing on the new session.

Only when max_attempts attempts have failed does the stream give up. It then releases run_forever() with a TransportError naming the attempt count and the last failure, which is the same signal a caller already had to handle before.

from neakasa_litterbox_sdk import ReconnectPolicy

async with client.watch_status(
    reconnect=ReconnectPolicy(max_attempts=10, initial_delay=2.0, max_delay=300.0),
) as stream:
    stream.on_sand_percent(handler_sand)
    await stream.run_forever()

Pass reconnect=None to switch the retries off entirely: the first drop then reaches run_forever() immediately, exactly as it did before this policy existed. That is the right setting for callers that already supervise the stream themselves (a Home Assistant coordinator, a process manager, ...), so two retry loops don't fight over the same session.

Broker TLS

watch_status() always verifies the broker's certificate chain and hostname. The MQTT endpoint (<productKey>.iot-as-mqtt.<region>.aliyuncs.com) is served by the GlobalSign GCC R1 OV TLS CA 2025 intermediate, which chains to the 1998 GlobalSign Root CA — a root current trust stores no longer carry, so the system store alone fails the handshake with unable to get local issuer certificate. The SDK ships that root and trusts it in addition to the system store, scoped to this MQTT context.

Two optional overrides:

  • ca_certs="/path/to/bundle.pem" — replaces the system store with your own bundle. The shipped broker root is still trusted on top of it.
  • tls_context=<ssl.SSLContext> — takes over entirely. Useful for callers that build a context off the event loop and reuse it (Home Assistant does this); you own verification from that point on.

The pinned root and the intermediate both expire on 2028-01-28. The broker has to move to a currently-trusted root before then, after which the system store covers it and the bundled file can be dropped.

Contributing

Read CODE_STYLE.md before adding or restructuring code — it's the single source of truth for layout, naming, typing, logging, error messages, and commit conventions. The high-level pointer for agents lives in CLAUDE.md.

Architecture

The SDK speaks to two backends under the hood (the Neakasa REST cloud and an Aliyun IoT API Gateway used for device-list and command paths), but consumers only see the high-level surface above — login() handles the multi-step bootstrap and LoginResult carries whatever credentials need to round-trip.

Support

This SDK is built and maintained on personal time, on hardware bought for the purpose. If it is useful to you, consider sponsoring the work — it keeps the devices, the testing and the releases coming.

License

MIT.

Metadata

Release files for neakasa-litterbox-sdk 0.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for neakasa-litterbox-sdk 0.2.3
File Size Uploaded Provenance Actions
neakasa_litterbox_sdk-0.2.3.tar.gz 143.3 kB Without provenance Details for neakasa_litterbox_sdk-0.2.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for neakasa-litterbox-sdk 0.2.3
File Interpreter ABI Platform Actions
neakasa_litterbox_sdk-0.2.3-py3-none-any.whl Python 3 none any Details for neakasa_litterbox_sdk-0.2.3-py3-none-any.whl

Total release size: 210.2 kB

Release files / neakasa_litterbox_sdk-0.2.3.tar.gz

Download URL neakasa_litterbox_sdk-0.2.3.tar.gz
Size 143.3 kB
Tags Source
SHA-256 checksum
How to use checksums
da7c2e5c285244ef7c45df82e63f03bfaf48dc4aaab9f79b4e881f04e64d9571
BLAKE2b-256 checksum
How to use checksums
ed84b040eeca1b2903f9136e41b9e8aef2555c6d5849e057592b743765684574
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / neakasa_litterbox_sdk-0.2.3-py3-none-any.whl

Download URL neakasa_litterbox_sdk-0.2.3-py3-none-any.whl
Size 66.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d404c36c13881265b7a0437822ba1016a1fd3781030bbc8a9e447f63cc1c56f9
BLAKE2b-256 checksum
How to use checksums
2b2103428375f35195e168fc831f661d423ec3f37199ba1a9f90d2e5ce9eba2c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for neakasa-litterbox-sdk 0.2.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page