pybabytracker
Async Python client for the sync service of
Baby Tracker, the app by
Nighp, built for the
Baby Tracker (Nighp) for Home Assistant
integration. It is unofficial and identifies itself as pybabytracker/<version>.
Use
import aiohttp
from pybabytracker import DIAPER_WET, BabyTrackerClient, SyncEngine
async with aiohttp.ClientSession() as session:
client = BabyTrackerClient(
"parent@example.com", "password", "STABLE-DEVICE-UUID", "Home Assistant", session=session
)
engine = SyncEngine(device_uuid="STABLE-DEVICE-UUID") # or SyncEngine.from_dict(saved_state)
result = await engine.sync(client) # the first also reads the seed; then only what's new
diaper = await engine.add_diaper(client, baby_id, DIAPER_WET) # posts as this device
await engine.delete_record(client, diaper.object_id) # only records this device created
saved_state = engine.to_dict() # JSON-safe: save it after writes, and after a sync with
# result.transactions_applied or result.seed_read
- Pass your own
aiohttp.ClientSession(the client never closes it), and make it dedicated to this client: the service authenticates by cookie, so two accounts must not share a session (in Home Assistant, useasync_create_clientsession). Without one, the client makes its own and closes it inclose(). AuthenticationErrormeans the credentials were rejected.BabyTrackerConnectionErrormeans the service was unreachable or answered with a server error. A 401 mid-session triggers one sign-in and a retry before it becomes anAuthenticationError.AccountChangedErrormeans a sign-in opened a different sync group (AccountID) from the one the engine's state came from: the group was reset in the app. The engine saves the firstAccountIDit sees and refuses to sync or write after it changes, as the app does; the client also refuses a sign-in to a different group from its own earlier one. Join the new group with a newBabyTrackerClientand a new engine (the aiohttp session can be reused). State saved before this version adopts the firstAccountIDit sees, so a reset that happened before upgrading isn't detected.AccountResetError(anAccountChangedError) means the service refused this device at sign-in because the account was reset: after a reset it refuses every device that joined before it, whatever the password, so it isn't anAuthenticationError. Join again as the app does, with a new device UUID, a new client and a new engine.- Records are typed (
Diaper,Sleep,Nursing, and so on). A record type the library doesn't know stays raw as anUnknownRecord(a debug line is logged once per type).Medicationis a medicine dose with the medicine embedded, andNursingSession, the Android app's timed nursing, is aNursing. The Android app sends codes such as a diaper'sstatusas strings of digits andenglishMeasureas a JSON boolean;numeric_code()reads either form, and volumes read both. Decoding then encoding any payload returns the same JSON, including keys the library doesn't model.
Writes
The engine posts as its own device (device_uuid, which must match the client's):
- A write needs a completed sync first (
NotSyncedErrorotherwise), because the payload embeds the baby record as known from sync (UnknownBabyErrorfor a baby it hasn't seen). - Numbers are at-most-once. The next number is one more than the highest of this device's
LastSyncIDon the server, its own log already applied, and its last confirmed post. Before choosing, the engine applies any of its own log it hasn't seen (another process using the same device ID). - When a post fails, the engine reads its own log at that number. If the same transaction is
there, the write succeeded. Otherwise the error is raised and the post stays pending; the next
write settles it first. After a definite HTTP error, a number nothing holds is reused. After
no answer at all (
NoResponseError: a timeout or dropped connection), the post may still land, so the number is reused only onceunknown_outcome_graceseconds (default 90) have passed with nothing under it; until then a write raisesWriteOutcomeUnknownErrorwithout posting. A 401 signs in again and resends the same number. Nothing is resent blindly. - To retry an add safely, pass the same
object_idagain: if the earlier attempt landed after all, its record is returned instead of a second copy being posted. - If this device's own log is shorter than its
LastSyncID, a write is refused (ProtocolError) rather than skipping the missing entries. - A confirmed write is applied locally at once, so the next sync doesn't fetch it back.
- Writes and syncs share a lock, so concurrent writes get consecutive numbers.
delete_recordonly deletes records this device added (NotOwnRecordError), and raisesRecordNotFoundErrorif one is already deleted. Like the app, the delete sends the record as last saved with onlynewFlageset to"false"; its timestamp is not bumped.- Save
to_dict()after every write, including one that raised: a pending post lives only in that state. Use one device ID per running process; two processes writing as one device can collide on a number whileLastSyncIDlags.
Record types you can add
Every add shares the rules above (numbering, pending posts, object_id retries, local apply),
and bad input raises ValueError before any request. Payloads match the iPad capture key for
key.
| Method | Writes | Notes |
|---|---|---|
add_diaper(client, baby_id, status, ...) |
Diaper |
DIAPER_WET, DIAPER_DIRTY, DIAPER_MIXED |
add_formula(client, baby_id, volume=, ...) |
Formula |
volume more than zero |
add_pumped(client, baby_id, volume=, ...) |
Pumped |
a bottle of pumped milk |
add_nursing(client, baby_id, left_minutes=, right_minutes=, ...) |
Nursing |
a finished session |
add_sleep(client, baby_id, start=, end=, ...) |
Sleep |
a finished sleep |
add_pump(client, amount=, ...) or add_pump(client, left_volume=, right_volume=, ...) |
Pump |
a pumping session; belongs to the account, so no baby_id |
add_milestone(client, baby_id, milestone, ...) |
Milestone |
milestone is a name or ID from milestone_choices(baby_id) |
add_vaccine(client, baby_id, vaccine, ...) |
Vaccine |
vaccine is a name or ID from vaccine_choices() |
add_medication(client, baby_id, medicine, amount=None, ...) |
Medication |
a dose; medicine is a name or ID from medicine_choices(), amount defaults to its usual dose |
add_activity(client, baby_id, activity, duration=0, ...) |
OtherActivity |
tummy time, a bath, and so on; activity is a name or ID from activity_choices() |
- A milestone names one from the app's pick list: one of the 20 it ships with
(
BUILT_IN_MILESTONES, under the app's ownEasyLogSeedIDs, which never sync) or one added in the app and known from sync.milestone_choices(baby_id)lists them andfind_milestoneresolves a name (ignoring case) or ID. An unknown one raisesUnknownMilestoneError, an empty or non-text oneInvalidSelectionNameError(aValueError), and a name that matches two entriesAmbiguousSelectionErrornaming their IDs, so pass the ID; all before any request. The three unknown-entry errors share the baseUnknownSelectionError(with.what), and a dose with noamountfor a medicine that has no usual dose raisesNoUsualDoseError. A milestone added for one baby is left out for the others. Adding a new milestone to the pick list isn't supported yet. Vaccines work the same way: the app's 10 built-ins (BUILT_IN_VACCINES) plus synced ones,vaccine_choices(),find_vaccine, andUnknownVaccineError. A medicine has no built-ins:medicine_choices()lists the ones doses already carry, and aMedicationis logged against one by name or ID. Activity types work like vaccines: the app's 5 built-ins (BUILT_IN_ACTIVITIES: Crawling, Cruising, Tummy Time, TV Time, Story Time) plus ones added in the app,activity_choices(),find_activity, andUnknownActivityError. The app has no bath screen: a bath is an activity of a type added in the app, such as "Bath". An activity'sdurationis whole minutes, 0 when not timed. - Where several records carry a copy of one entry, a synced copy wins, then the copy in the
newest record (by its
timestamp, then itstime), so a dose's default amount is the usual dose of the newest dose. A medicine without a usual dose that is a number above zero needs anamount. Doses are rounded to 2 decimals, like volumes, in the medicine's own unit. - How well this is checked: a built-in milestone ("Back home") and vaccine ("HepB") and a
medicine dose were posted on iOS and read back unchanged, and the app showed each as the entry
it is. The other built-in IDs, Android, and a custom milestone or vaccine are unverified. A
pick-list entry syncing as its own transaction (
MilestoneSelection,VaccineSelection,MedicationSelection) is an expected shape, not yet seen in synced data. A medicine'sintervalis in minutes. - Volumes are
Volume(value, "oz")orVolume(value, "ml"), written as aVolumeMeasurewithenglishMeasure"true"(ounces) or"false"(milliliters), rounded to 2 decimals (an integer when whole). The number is written as given, with no conversion, as the app does. timeis when the activity started (or, for a bottle or diaper, when it happened), written in UTC.timezone_offset(seconds east of UTC) defaults to the offset of the time given. The app itself writes the zone's standard offset all year, ignoring daylight saving, so to match it passtimezone_offset=standard_offset_seconds(tz, time): New York is -18000 in July and January.- Nursing:
timeis the session's start, as in the capture. Givestart_time, orend_time(start is end minus the total minutes), or neither (the session just ended).finish_sideisSIDE_LEFT(1),SIDE_RIGHT(2), orSIDE_NONE(0), the app's numbering. The app shows the field as the side a session started on. It defaults to the only side used, orSIDE_NONEwhen both were, since the totals can't tell which came first (the app also saves most two-sided pumps withSIDE_NONE), so passfinish_sideyourself when you know it. ANursingTimerknows: itsstart_sideis the side it started on. - Sleep:
timeisstart.durationis whole minutes: the length rounded half up (the capture stored about 30 seconds as 1), and at least 1, because a duration of 0 means a sleep in progress.endmust be afterstart, and a sleep can't be longer than 24 hours. - Nursing and pump minutes are whole numbers, at most 240 per side (a guard against seconds passed as minutes).
- Pump: a pump belongs to the account, not a baby, so it takes no
baby_idand its payload has nobabykey, like the app's. Give the total asamount, or the side volumes (not both): with onlyamountthe payload has no per-side amounts, and with sidesamountis their sum, a side left out is written as 0 in the other's unit, and both sides must use one unit. With no volume at all, minutes are required and the payload carries the durations and anamountof 0 indefault_unit(defaultoz), as the app writes a timed pump with no volume.sidesis written as 0, as captured. Babies are never derived from pumps, and a pump that carries ababystill decodes (kept raw, not read).engine.latest_pump()is the newest pump on the account;latest_records(baby_id)never includes pumps.
Sleep timers
The app syncs a running sleep: an add with duration 0 at the start, then an update (opcode 1)
to the same record at the stop. Nursing timers stay on the phone until they stop, so a timed
nursing session is written once, finished, with add_nursing.
| Method | Writes | Notes |
|---|---|---|
start_sleep(client, baby_id, start=None, ...) |
Sleep (add) |
duration 0; start defaults to now, no more than a minute ahead or 24 hours back |
end_sleep(client, object_id, end=None) |
Sleep (update) |
ends a running sleep, whichever device started it |
end_sleepsends the record as last saved, changing onlyduration(rounded likeadd_sleep),newFlage("false"), andtimestamp(the write time, or one second past the stored one when that's ahead of this clock, so the end wins the merge). Key order and unknown keys are kept.- A sleep longer than 24 hours at the stop is clamped to 1,440 minutes with a warning, not
refused, so a forgotten timer can always be stopped. An
endmore than a minute in the future is clamped to now, and an end at or up to a minute before the start (a clock running a little fast) is written as 1 minute. - Refused before any request: a record never seen or deleted (
RecordNotFoundError), one that isn't a sleep (WrongRecordTypeError), or a sleep another device finished (TimerNotRunningError). A sleep this device already ended (its end is in this device's log, even if a phone edited it since) is returned as is, with nothing posted, so retries are safe. - The end carries the whole record as this device last saw it, so a phone edit that hasn't synced yet (a note, say) is overwritten by it, as the app's own edits overwrite each other.
- A phone delete racing an end: the app's delete keeps the record's old timestamp, so an end posted after it (with a newer timestamp) outlives it, and the sleep stays here as ended. How the app shows that case is still to be checked on a test device.
- An end is an update, not an add: it doesn't make another device's sleep this device's own, so
delete_recordstill refuses it. Undo of a sleep this device started works running or ended.
The service lists a device only after its first post; on the test account, the dev device
appeared with LastSyncID 1 right after its first add, with no confirmation step.
Nursing and pump timers
Because a nursing timer isn't synced while it runs, a client that offers one keeps its own.
NursingTimer is that state as an immutable value: NursingTimer.start(object_id, "left", now),
timer.switched("right", now), and timer.minutes(now) for the whole minutes per side to pass to
add_nursing. Each side rounds half up; a session under 30 seconds is 1 minute on the side it
ended on; a side past 240 minutes is written as 240 and logged. to_dict() and
NursingTimer.from_dict() give a form to save between runs, and PumpTimer does the same for a
pump (one length for both sides, never under 1 minute).
Day totals and write validation
day_totals(records, baby_id, start, end) counts a baby's diapers (by kind), feeds, and bottle
volume in milliliters from start up to end. The caller passes the bounds, so a local calendar
day, including a 23- or 25-hour day at a clock change, is local midnight to the next local
midnight. pybabytracker.validation has the checks behind a bad request (check_amount,
check_pump_amounts, check_minutes, check_sleep_range, check_end_after_start,
check_sleep_start). Each raises a ValidationError subclass (InvalidAmountError,
AmountTooSmallError, MinutesTooLongError, EndBeforeStartError, SleepTooLongError,
SleepStartOutOfRangeError) that carries what was wrong, so a caller can pick its own message.
Merge rules
Records are keyed by objectID. Each stored record carries a version made of the record's
timestamp, the device, and the sync number. Within one device's log, later numbers always win.
Across devices the result doesn't depend on which device is fetched first:
- An add or update replaces a stored record if its (timestamp, device, number) is newer.
- A delete removes the record unless the record's timestamp is newer than the delete's, and it leaves a tombstone, so a delete that arrives before the add it targets still wins.
- An add or update from another device brings a deleted record back only with a strictly newer timestamp than the tombstone. Within one device, a later add always wins.
Tombstones are saved by to_dict(). State saved by an older version (1) loads with none.
A payload that can't be decoded at all is skipped with a warning, and the sync moves past it. A
fresh SyncEngine replays every log, so it recovers skipped payloads once a fix ships, and it
reads the seed again.
The seed
The logs don't hold the whole history. The account also has a seed, a full copy of its database
as of some point (client.get_seed(), a zip that read_seed decodes), and records from devices
that have since left the account are only there. The first sync reads it before the logs, and
state saved before this version reads it on its next sync. Seed records are merged as adds from
no device: a log copy of a record wins unless its timestamp is older, and a delete in a log
removes it. Every log is still read from the start, as the app does after loading a seed.
SyncResult.seed_read is true for the sync that read the seed (or learned there is none), so save
the state after it even when no log entry was applied. SyncEngine.seeded turns true as soon as
the seed is read, even in a sync that then fails, so a caller can save when it changes. A download
that fails is warned about once and tried again on the next sync, while the logs keep syncing. A
seed that can't be read, or that the client refuses (DownloadRefusedError: a redirect, or over
the size cap), is warned about and skipped. Saved state records the seed format it was read at
(seeded: 1; true from earlier versions counts as 1), and a library with a newer
SEED_FORMAT reads the seed again. Text that isn't valid UTF-8 is read with replacement
characters. Pick-list entries in the seed aren't records of their own; the records that use them
carry them, as synced records do.
Command line
export BT_EMAIL=... BT_PASSWORD=... # or put them in .env
python -m pybabytracker # latest record of each type, per baby
python -m pybabytracker --probe-history
# Writes go to a throwaway test account only (BT_TEST_EMAIL, BT_TEST_PASSWORD):
python -m pybabytracker --write-test-diaper [--status wet|dirty|mixed]
python -m pybabytracker --delete-test-diaper OBJECT_ID
The tool signs in as a separate device named "Home Assistant (dev)". Its ID is made once and
kept in .pybabytracker-device.json (gitignored). --probe-history reads every device's log
from 0 and reports how many transactions come back versus its LastSyncID, the lowest and
highest numbers returned, and a verdict (full, paged, paged newest first, starts at K with older
numbers trimmed, duplicates, or gaps), then whether the probe device now appears in the device
list. It only reads. History older than the logs is in the account's seed (see
The seed), which the probe doesn't read; the default run reads it, so its latest
records include it.
--write-test-diaper adds one diaper for the test account's first baby and reports whether the
dev device is in the device list before and after, with its LastSyncID, and whether the next
sync fetched its own log back. --delete-test-diaper deletes one the dev device wrote. Both
read only the BT_TEST_* credentials, and keep their device ID and engine state in
.pybabytracker-test-device.json and .pybabytracker-test-state.json (both gitignored).
Develop
uv venv --python 3.12 && uv pip install -e ".[dev]"
pytest && mypy && ruff check .
Release
Releases publish to PyPI from a v<version> tag such as v0.2.0 through trusted publishing: there is no API token
anywhere. .github/workflows/release.yml runs on that tag and needs the tests to pass, then
builds the sdist and wheel, checks them with twine check --strict, installs the wheel in a clean
venv, and publishes from the GitHub environment named pypi.
To cut a release:
- Set
__version__insrc/pybabytracker/_version.py(for example0.2.0, or0.2.0rc1for a pre-release) and merge it tomain. - Tag that commit with the same version and push the tag:
git tag v0.2.0 && git push origin v0.2.0. The workflow fails before building if the tag and_version.pydisagree (python scripts/check_version.py v0.2.0runs the same check locally).
One-time setup, done on PyPI and in GitHub before the first tag:
- On PyPI, add a pending publisher at https://pypi.org/manage/account/publishing/ for
the project name
pybabytracker, with ownerwtadler, repositorypybabytracker, workflowrelease.yml, and environmentpypi. - In the repository settings, create an environment named
pypi, and under deployment branches and tags choose Selected branches and tags with the tag rulev*, so only a version tag can reach the publish step (a branch could otherwise run the workflow with the publish permission). Adding required reviewers there makes each publish wait for an approval.
The first successful publish turns the pending publisher into a normal one.
Metadata
Release files for pybabytracker 0.5.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pybabytracker-0.5.1.tar.gz | 217.0 kB | With provenance | Details for pybabytracker-0.5.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pybabytracker-0.5.1-py3-none-any.whl | Python 3 | none | any | Details for pybabytracker-0.5.1-py3-none-any.whl |
Total release size: 292.4 kB
Release files / pybabytracker-0.5.1.tar.gz
| Download URL | pybabytracker-0.5.1.tar.gz |
|---|---|
| Size | 217.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1b0ef0c88cf428752ad4178efe2686c88a6b90983b6f7440b6bb0a0ac0f1bb0e
|
|
BLAKE2b-256 checksum How to use checksums |
ea6183f5f89f1bddace916b3cbc73a2488ba38c69895cf4c05f054c87dadb236
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.
Transparency logRelease files / pybabytracker-0.5.1-py3-none-any.whl
| Download URL | pybabytracker-0.5.1-py3-none-any.whl |
|---|---|
| Size | 75.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d8abbcec47d21a95365ea1dec5958c0c4b653bb538e558ac8ee2b1ced9ca1199
|
|
BLAKE2b-256 checksum How to use checksums |
780f9858a57f81e0db2aeb4a15302887c25c72c3aa11cca842c3a51befbbaa13
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.
Transparency logSecurity for pybabytracker 0.5.1
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pybabytracker-0.5.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.
Transparency logA 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.