New
Apps 6,419Makers 6,403This week 7
Promote your app−30%
Pet Watch screenshot 1
4views in
the last 30 days

Pet Watch

Low-cost non-contact sensor that spots changes in your pet's habits

Built with Claude Code

by pratiksardar · Unclaimed · from INIndia · added Nov 3, 2026
no ratings0 comments

🐾 Pet Watch

Pets hide illness. Their habits don't.

A low-cost, non-contact sensor that logs every visit your pet makes to the litter box or food bowl, learns that individual's normal rhythm, and flags when it drifts.

Watch the demo

▶ Watch the full 81-second demo · real footage, real sensor, real dashboard


Contents

Demo · Raw footage · Installation · Usage · Design notes · Hardware · Firmware · Detector · Support · Roadmap · Contributing · Authors · License · Project status

The demo in one breath

A golden retriever drinks from a bowl. An ultrasonic sensor above it sees the echo shorten from ~1100 mm to ~160 mm, the live dashboard flips to "in interaction zone — timing", and the visit counter ticks 1 → 2 → 3. No camera, no collar, no cloud. Every visit becomes a row in SQLite, and over days those rows become your pet's normal, so a change stands out long before it's visible.

Sense Detect Learn
Ultrasonic echo, 20× a second, streamed raw from an ESP32-C6 over ESPHome. Self-correcting baseline, 1.5 s walk-past filter, fragments merged into one real visit. Per-pet rhythm by hour of day; an EWMA flags a 2σ drift. Deviation, never diagnosis.

Raw footage

The unedited reels behind the demo: one phone, one sensor, one golden retriever. Timestamps in What you see are the dashboard's own clock, so you can check each count against the frame.

Clip What you see
Dog drinking from the bowl in front of the sensor
Bowl visit 1: drinking · 7 s
A teammate holds a water bowl while another holds the ultrasonic sensor at the top of the laptop screen, aimed at the dog. As the head dips in and out, the live distance swings 712 → 163 → 779 → 205 mm and the badge reads "in interaction zone · timing". Visits today: 1, logged at 14:28:40.
Close-up of the dog licking right above the sensor
Bowl visit 2: close-up · 5 s
Tight shot on the dog licking the bowl right above the sensor. The reading hovers at 169–304 mm, drops to 36 mm as the snout nudges the transducer, then jumps to 642 mm as the dog pulls back. Visits: 2, at 14:30:26.
Dog sitting in front of the sensor before drinking
Bowl visit 3: sit, drink, leave · 8 s
The dog sits facing the sensor, is offered the bowl, drinks, and wanders off. The trace shows a dense burst of activity followed by a flat baseline once the dog is gone. Visits: 3, at 14:30:43.
Pet Watch dashboard on a laptop during the bench test
Bench test: full take · 1 min 53 s
The dashboard on its own. 0:00–0:25: the last-2-minutes chart shows earlier visit bursts while a trig/echo sensor board on jumper wires is held up to the screen. 0:52–1:18: a second, sealed round ultrasonic probe is waved in front of it. 1:16–1:28: close-up of the readout: baseline ~140 mm, subject at 163 mm, "in interaction zone · timing". 1:28–1:50: the counts panel holds at 7 (last interaction 14:32:44). ~1:50: a new visit is committed and the counter ticks to 8 at 14:35:03.

All four are also cut into the demo video: visits 1–3 at 0:10–0:30 and the bench test at 0:38–0:59.

Installation

Requirements

  • Node.js 24+. TypeScript runs natively, with no build step and zero runtime dependencies.
  • Optional, for the real device: an ESP32-C6 dev board, an ultrasonic sensor (RCWL-1601 for the bench, JSN-SR04T for deployment), and ESPHome. See Hardware.
git clone https://github.com/pratiksardar/petWatch && cd petWatch
npm install
npm run verify        # typecheck + 38 tests; no hardware needed

To flash the device, follow Firmware; for wiring, see docs/wiring.md.

Usage

Live dashboard

PET_WATCH_DEVICE=http://pet-watch.local npm run dashboard   # → http://localhost:8788
Variable Default What it does
PET_WATCH_DEVICE http://172.20.0.183 Base URL of the ESPHome device to stream from.
PORT 8788 Dashboard port.
PET_WATCH_INTERACTION_MM 100 Distance that counts as "in the interaction zone".
PET_WATCH_MIN_S 3 Minimum dwell, in seconds, before it counts as a visit.
PET_WATCH_NO_OPEN (unset) Set it to stop macOS from opening the browser automatically.

Interactions are appended to data/interactions.jsonl (gitignored) and exported at /api/interactions.csv.

As a library

The detector is pure: samples go in, visits come out, with no clock, network or hardware.

import { detectVisits, synthTrace } from "./src/index.ts";

// 10 minutes of 20 Hz readings with one 45 s visit and a 0.5 s tail swish.
const samples = synthTrace({
  durationMs: 10 * 60_000,
  emptyMm: 1100,
  visits: [{ atMs: 120_000, durationMs: 45_000, depthMm: 520 }],
  blips: [{ atMs: 400_000, durationMs: 500 }],
});

for (const v of detectVisits(samples)) {
  console.log(`${v.durationMs / 1000} s visit, closest ${Math.round(v.minMm)} mm`);
}
// → 45 s visit, closest 564 mm   (the tail swish is filtered out)

For live use, new VisitDetector() exposes the same logic one sample at a time via push() and flush().

Repository map

Path What's there
src/ Streaming visit detector, anomaly layer, rollups, zero-dependency dashboard server.
test/ node:test golden-file and property tests over synthetic traces.
firmware/ ESPHome configs for trig/echo and UART ultrasonic sensors.
docs/ Wiring diagrams, level shifting, assembly and pre-power checklist.
claude-kudos-demo/ The demo video as code: a Remotion project with a storyboard.
media/ Rendered demo video, poster, preview GIF, team photo, and the raw footage in media/footage/.

Design notes

The rest of this README is the engineering write-up: why the parts fit, how the detector thinks, and the caveats that will bite you.

Why this earns its place: cats in particular hide illness in litter-box habits. Frequency, duration, and posture changes are the earliest cheap signal that something is wrong — often days before anything is visible. The device's job is not to diagnose. It is to notice deviation from your pet's own baseline so you can decide whether to call the vet.

Why these three parts fit

Part Role
Ultrasonic sensor The only sense organ. Proximity, dwell time, motion.
Dot matrix The only face. Low-resolution, so use it for state, not text.
ESP32-C6 Data collection, plus the 802.15.4 radio for Thread/Matter/Home Assistant.

The dot matrix is 32×8 pixels. That is not enough for a useful numeric readout and it is enough for eyes, bars, and a 24-hour strip chart. Design around that instead of fighting it.

Hardware

Item Note
ESP32-C6 devkit DevKitC-1 is the default assumption in the firmware.
Ultrasonic sensor Two families, two firmwares. See docs/wiring.md §1.
JSN-SR04T Preferred for deployment. Waterproof, 1 mm resolution, 25–600 cm, sealed transducer on a lead so the board stays outside the box. It is a UART device though, so it needs pet-watch-uart.yaml, not the trig/echo firmware.
RCWL-1601 Least fussy for bench work. 3.3 V native and trig/echo, so no divider at all.
HC-SR04 Trig/echo. Needs a divider on echo, and has a marginal 3.3 V trigger. See caveats.
MAX7219 dot matrix Optional — the display is cosmetic. 4 × 8×8 modules chained = 32×8, which is what the firmware draws.
R1 1 kΩ + R2 2 kΩ The 5 V → 3.3 V divider every 5 V sensor line needs.
470 µF electrolytic Across the 5 V rail. Brownout headroom — see caveats.
Optional: BLE collar beacon The only real fix for multi-pet disambiguation.

Mounting

The two profiles differ enough to be a config switch, not a tweak:

  • LITTER — probe mounted on the outside of the entry, aimed down and across the opening. You are measuring "is something in the doorway/box". Empty reads the far wall; occupied reads the pet's back at ~40–60 cm.
  • BOWL — probe mounted above and slightly behind the bowl, aimed down. Empty reads the bowl rim; occupied reads the pet's head and shoulders, and a feeding session shows as rhythmic dips as the head raises and lowers.

Never put bare electronics inside the box.

Wiring

Connection diagram

Full diagrams, level shifting, an assembly order, a pre-power checklist, and a troubleshooting table live in docs/wiring.md. Read §1 and §8 there before buying a sensor or applying power.

Signal C6 GPIO DevKitC-1
Sensor TRIG (or UART TX) GPIO20 J3 pin 8
Sensor ECHO (or UART RX) GPIO21 J3 pin 7
MAX7219 CLK GPIO6 J1 pin 5
MAX7219 DIN GPIO7 J1 pin 6
MAX7219 CS GPIO10 J1 pin 10
Power 5 V / GND J1 pins 14 / 15

GPIO4, GPIO5, GPIO8, GPIO9 and GPIO15 are strapping pins on the ESP32-C6 and carry no signals here — their level at reset selects boot and JTAG behaviour. GPIO8 also drives the on-board RGB LED, GPIO12/13 are USB, and GPIO16/17 are the serial console.

Firmware

Two entry points, because the two sensor families are genuinely different devices:

File Sensors Interface
firmware/pet-watch.yaml HC-SR04, RCWL-1601, US-100 trigger/echo
firmware/pet-watch-uart.yaml JSN-SR04T, AJ-SR04M UART 9600

Everything they share — power, network, calibration, and debounce — lives in firmware/common/base.yaml, so the two cannot drift apart.

The display is an optional package, common/display-max7219.yaml, added with one line. Nothing in base.yaml depends on it, so a device with no display still reports distance, occupancy, and presence. That matters because ESPHome cannot drive I2C LED matrices — there is no HT16K33 component upstream — so an I2C dot matrix will not work regardless of wiring. See docs/wiring.md §13 for the options.

Either entry point:

  1. Streams raw distance at 20 Hz as distance (in mm).
  2. Computes occupancy as 0–100% between two calibrated distances.
  3. Derives a debounced occupied binary sensor — this is what makes it an occupancy device in Home Assistant immediately.
  4. Draws eyes and an activity bar on the matrix, graphics only — no font file dependency, nothing to break on a fresh flash.
  5. Exposes a runtime occupancy threshold number so you can tune it from Home Assistant without reflashing.
cd firmware
cp secrets.example.yaml secrets.yaml    # fill in WiFi, api key, ota password
esphome run pet-watch.yaml              # or pet-watch-uart.yaml

Generate the API key with openssl rand -base64 32.

Calibration

  1. Mount it, pet elsewhere. Watch distance in the logs for a minute. Set dist_empty_mm to that value.
  2. Put the pet in position (or hold a cardboard proxy where the pet goes). Read distance again. Set dist_full_mm.
  3. Tune the occupancy threshold in Home Assistant from the live chart.

On-device vs. host

The firmware deliberately does the least it can and streams raw distance. Everything interesting is derived on the host:

  • You cannot iterate on a detector that lives in flash without a reflash per attempt.
  • Raw traces replay through a test harness without the hardware present.
  • A threshold in YAML is a threshold you can't tune from the couch.

Move detection back onto the device only when you actually need it — offline operation, or real-time display reaction. Not before.

Detector

Input: a series of (timestamp, distance_mm) samples at ~20 Hz.

  1. Baseline — median of a rolling quiet window. This floats, because temperature and humidity drift the speed of sound, and litter level drops.
  2. Occupancy — deviation from baseline beyond a noise-adaptive threshold, sustained.
  3. Visit — a contiguous run of occupancy. Discard runs under ~1.5 s: that's a tail swishing past, not a visit.
  4. Features per visit — duration, min/mean depth, depth spread (how much the pet moved), and sample count. Time-of-day and inter-visit intervals belong to the rollup layer, not here.
  5. Post-process — merge fragments separated by a 2–3 s gap; a cat that repositions isn't making two visits.

durationMs and depthStdDevMm are the two features that carry most of the signal. The first separates a real visit from a walk-past; the second separates "settled in and using the box" from "circling restlessly", and the restless case is the one worth noticing.

src/detector.ts is a streaming state machine with no hardware, no network, and no clock reads — detectVisits() is a thin array adapter over the same class, so batch and live use cannot drift apart. That is what makes it testable; see below.

Two decisions in the detector worth not re-litigating

The baseline only learns from samples it is confident are empty. Not from "samples below the entry threshold". The gap between those two ideas is a feedback loop: a subject that interrupts the beam only weakly (say 120 mm under a 150 mm threshold) sits in an ambiguous band, and if those samples train the baseline then the baseline slides toward the subject, the measured deviation shrinks along with it, the subject never clears the threshold, and so the samples stay classified empty and keep dragging the baseline down. The subject becomes permanently undetectable — and the quieter it is, the more thoroughly it hides. The ambiguous band is therefore evidence of nothing. test/detector.test.ts pins this; with the loop present the baseline converges onto the subject's own distance (1030 mm instead of 1150 mm).

The seed baseline errs low, at the 25th percentile. The asymmetry matters. A baseline that is too high makes genuinely empty readings look "closer than empty" — permanently occupied — and nothing can correct it, because adaptation only ever runs on samples already classified empty. A baseline that is too low self-corrects within seconds, because empty readings are correctly identified and pull it upward.

Data model

CREATE TABLE visit (
  id            INTEGER PRIMARY KEY,
  device_id     TEXT    NOT NULL,
  pet_id        TEXT,                   -- null when ambiguous
  started_at    TEXT    NOT NULL,
  ended_at      TEXT    NOT NULL,
  duration_ms   INTEGER NOT NULL,
  min_dist_mm   INTEGER NOT NULL,
  mean_dist_mm  REAL    NOT NULL,
  depth_std_dev_mm REAL NOT NULL,
  confidence    REAL    NOT NULL
);

CREATE TABLE daily_rollup (
  device_id     TEXT    NOT NULL,
  pet_id        TEXT,
  day           TEXT    NOT NULL,
  visit_count   INTEGER NOT NULL,
  total_ms      INTEGER NOT NULL,
  overnight_count INTEGER NOT NULL,     -- 00:00-06:00, a real signal
  PRIMARY KEY (device_id, pet_id, day)
);

CREATE TABLE alert (
  id            INTEGER PRIMARY KEY,
  device_id     TEXT    NOT NULL,
  pet_id        TEXT,
  kind          TEXT    NOT NULL,       -- frequency | duration | restlessness | none
  severity      TEXT    NOT NULL,
  raised_at     TEXT    NOT NULL,
  window_start  TEXT    NOT NULL,
  window_end    TEXT    NOT NULL,
  detail_json   TEXT    NOT NULL
);

SQLite is enough. There is one sensor.

AI — three layers, cheapest first

L1: threshold + debounce. On-device, in the YAML. Proves the plumbing.

L2: per-individual anomaly detection. This is the layer that has value, and it needs no labelled data. For each pet, for each hour-of-day bucket, keep a rolling mean and standard deviation of visit count and duration. Flag a day when it deviates beyond ~2σ. Use an EWMA so a week-long illness doesn't get absorbed into the baseline as "normal".

Start here. This is most of the product.

L3: supervised classifier. Only worth it once you have weeks of labelled trace — you label by reviewing the same week of footage once. Features per visit as above; logistic regression or a small gradient-boosted tree gets you pet-vs- human and cat-vs-dog. Don't start here; the labels don't exist yet.

Absolute clinical numbers vary with species, size, age, and medication, so the system should never assert "normal" or "abnormal" in absolute terms. Frame every alert as deviation from this pet's baseline over N days and leave the judgment to the owner. Also: a single missed day is noise. Alerting on one-day deviation will train you to ignore it.

Running the host project

Node 24 only, and deliberately zero runtime dependencies: TypeScript runs directly via native type stripping (no build step, no tsx), tests use the built-in node:test, and storage uses built-in node:sqlite. The only devDependencies are typescript and @types/node, and only for tsc --noEmit.

npm install
npm run verify     # tsc --noEmit && node --test
npm test
Path Contents
src/detector.ts Streaming visit detector: baseline, occupancy, merging, features.
src/stats.ts Percentile / median / MAD. Robust by design — see the module note.
src/synthetic.ts Deterministic trace generator, so awkward cases are reproducible.
test/ Golden-file and property tests over generated traces.
firmware/ ESPHome entry points, plus common/ shared between both sensor variants.
docs/wiring.md Wiring diagrams, level shifting, assembly order, pre-power checklist.
docs/wiring-diagram.svg The connection diagram, as editable vector source.

Testing without a pet

The single highest-value engineering decision in this project:

Record real traces once, then replay them forever. Log raw distance samples to JSON while your pet uses the box — an hour of footage gives you dozens of labelled visits. Once you have traces/*.json plus expected visit lists, the entire

Description taken from the repository README.

Ratings

–
0 ratings
5 0
4 0
3 0
2 0
1 0

Rate this app

Sign in to rate

Comments 0

Sign in to comment

No comments yet.

Related apps

#pets · #health · #hardware