/

Ambitwin · source-available, not open source · © 2026 Nicolò Ghignatti

Wireless People Flow

Where people are in a building, live, from the Wi-Fi signals their phones already emit: a dot per phone on the twin, and room counts stored as metrics.

Status: phase 1 built on simulated routers; not yet tried on a real OpenWrt site. Tracks issue #314.

Applies to: devices/ap-collector, telemetry (/telemetry/observations, three router metrics), digital-twin (the estimator), socket (the devices event). No new service.

Two phases, in order

Phase 1 — routers only. Poll the access points the building already has, and listen to the probe requests they hear. Zero new hardware.

Phase 2 — dedicated sniffers. Raspberry Pi rigs in monitor mode, for devices the routers miss. Only after phase 1 is proven in a real building.


What Crosses Into Ambitwin

The Dutch DPA is explicit: “Storing multiple location points per device means that the data is not anonymous.” So the design keeps a phone’s identity on site and never stores a position.

DataWhere it existsHow long
MAC addresscollector memory onlywhile the phone is heard
Token (random, secrets.token_hex(8), never derived from the MAC)signed tick, Kafka wifi-observations, twin memory10 min on Kafka; in twin, until unseen for 3 ticks
Positiontwin memory (one per track, no history), Redis pub/sub twin:devices:{id}the current tick only
Room countsTimescale readingsthe platform’s retention (below)

Invariants:

This is pseudonymous personal data while it is live

A token follows one phone for as long as it stays, and Kafka holds ten minutes of them. A dot has no id, but a viewer watching a near-empty building can follow one dot from tick to tick. So a site needs a legal basis and a notice before enabling it (Wi-Fi terms, employment agreement), exactly as for any Wi-Fi analytics. Turning off probes (subscribeProbes: false) limits it to people who joined the Wi-Fi.


What Is Stored, And Why That Is Safe

A count carries no identifier and no per-device row, so there is nothing to single out. That is the whole argument for the stored data, and it is only as strong as the two conditions below.

Why Routers-Only Works

The obvious objection: MAC addresses are randomized, so won’t one phone look like a different person to every access point it passes?

No — randomization is per-SSID, not per-AP. Every AP in the building broadcasts the same SSID, so a device roaming across them keeps one address.

PlatformBehaviour on the building SSID
Android 10–15Persistent randomized MAC derived from the network profile (SSID + security type). Stable across APs, stable across forget-and-rejoin, until factory reset.
Apple (iOS 18 / macOS Sequoia)On WPA2-AES or WPA3, the private address is fixed per SSID. Only open and pre-WPA2 networks rotate — every 2 weeks.

Wi-Fi roaming requires this. The DHCP lease, L2 forwarding tables and 802.11r fast transition are all keyed on the station MAC. If it changed on roam, open TCP connections would drop and roaming would not function.

The objection is correct for the other regime

Probe-request MACs are random per scan burst and uncorrelated between listeners. So a probe address is never counted: the collector groups one address’s frames into a burst (one scan), gives the burst a fresh token, and the twin only places it.

Two regimes

RegimeWhat the AP seesRouters-only?
Associated — device joined the Wi-FiEvery frame, continuously, stable per-SSID MAC, RSSI per APYes. This is phase 1.
Unassociated — visitor never joinsSporadic probe requests, streamed by hostapd (subscribeProbes, off by default)Partly. Bursts place passing dots; counting them is phase 2.

Phase 1 covers everyone on the Wi-Fi and misses the walk-through visitor. For facility management the associated population is generally the population that matters.

It is also the only regime with a workable legal basis: a captive portal, Wi-Fi terms of service or an employment agreement supports consent or legitimate interest. Ambient sniffing of passers-by supports neither — that is what the AP fined a Dutch municipality for in 2021. That is why subscribeProbes is off by default: a site turns it on only with a basis for it.


Positions, Estimated in the Twin

Digital-twin owns the floor plan and the router placements, so it places the phones. Telemetry never sees a coordinate, and no copy of the geometry can go stale when a router moves.

How a phone is placed (service/estimator.rs, service/tracks.rs):

Why a grid fit, not circles. Fitting circles (trilateration) needs every distance right, but walls and weak antennas only ever lower a signal, so every circle comes out too big. Measured on 470 simulated bursts: right room 95% for the grid fit, 69% for circles.

Measured on a recorded run (tests/data/wifi-recording.jsonl, 15 min, 48 phones, simulated):

DotsEach phone in its router’s room
Right room79.4%75.0%
Room counts, total off1 4621 988
Position errormedian 4.0 m, p90 8.1 m—

Fine Timing Measurement (802.11mc/az/bk) stays rejected: it is client-initiated, so the infrastructure never learns the position unless an app reports it back.


Phase 1 — Routers-Only

graph LR
    subgraph Building
        AP1[AP - lobby]
        AP2[AP - floor 2]
        AP3[AP - canteen]
    end
    C[ap-collector]
    AP1 -->|RSSI per station| C
    AP2 --> C
    AP3 --> C
    T2[GET /telemetry/collector] -->|routers: sensor id, room, ubus address| C
    C -->|Wi-Fi tick, tokens only, HMAC-signed| T[POST /telemetry/observations]
    T -->|router-room counts| PG[(Timescale)]
    T -->|tick as received| K1[[Kafka wifi-observations]]
    K1 --> TW[digital-twin estimator]
    TW -->|dots, no id| R{{Redis twin:devices:id}}
    R --> S[socket] -->|devices event| B[browser]
    TW -->|room counts| K2[[Kafka estimated-occupancy]]
    K2 --> T

The collector

A small daemon on the building network. Polls each AP every pollIntervalS (10 s), holds one in-memory token table, posts one signed Wi-Fi tick per building per poll to /telemetry/observations (schemas/fixtures/wifi-observations.json). It counts nothing: telemetry counts the tick per router room.

On OpenWrt the readings come from hostapd over ubus — hostapd.<iface> get_clients returns every associated station with its signal in dBm. iw dev <iface> station dump is the equivalent without ubus.

Per tick:

  1. Collect (mac, rssi, idle) from every AP. iwinfo’s inactive is the idle time. hostapd has none: idle is how long that station’s packets.rx has not changed, so it is one poll coarse, and a station first seen counts as fresh.
  2. Drop roam leftovers. A MAC listed by several APs keeps only its least-idle rows (within 1 s: each AP is polled on its own clock read). A station associates with one AP; the old one still lists it, signal frozen, until ap_max_inactivity (300 s).
  3. Tokenise: swap every MAC for its token; group probes into bursts.
  4. Post the tick. Telemetry then counts it: one token is one phone, counted once, in its loudest router’s room.

Union by phone, never sum per-AP client counts

Summing the client lists of overlapping APs is a straight multiplication of the count, and it produces exactly the symptom people expect from MAC randomization. One token on two rows is one phone; telemetry counts it once (kernel/observations.rs).

Smoothing lives in the twin, transitions are not built

Telemetry keeps no state between ticks, so its router-room count can flip a phone between rooms each tick. Digital-twin’s tracks carry each phone across ticks, which is what smooths the dots and estimatedOccupancy. Transition counts (zoneTransition, below) are still not built.


The Platform Side

Occupancy is three metrics, not one

Telemetry stores these for every room, every tick (the factor rides on the tick as devicesPerPerson):

MetricWhat it isFrom
totalDeviceCountDevices connected, each in its loudest router’s room. A measurement.telemetry, from the tick
ratioDeviceCountDevices ÷ the site’s devices-per-person factor. An estimate.telemetry, from the tick
estimatedOccupancyConnected devices placed in the room by position. An estimate.digital-twin, Kafka estimated-occupancy

estimatedOccupancy is never mixed into totalDeviceCount: the two place a phone differently, and a dashboard can show both. It counts only rooms on a floor with a placed router, and only ticks where a router answered.

Publishing only the estimate would be the smaller change and the wrong one. The factor is a per-building guess that gets re-measured, and an estimate is only as good as the factor it was derived with. Store the raw count and a corrected factor re-derives the whole history; store the estimate alone and every past bucket is permanently wrong by whatever the old factor was off by. The measurement is also the only one of the two that means the same thing in every building, which is what makes cross-site comparison possible at all.

ratioDeviceCount is emitted only where the site actually configured a factor (useDevicesPerPerson). No factor, no estimate — an estimate silently equal to the device count is a claim about people that nobody made.

Both follow the shape of the existing peopleCount plugin (backend/telemetry/src/plugins/people_count.rs): per building and room, non-negative integer, dashboard catalog, twin overlay, agent tool.

A room’s count is its router’s, not the room’s. A router hears devices wherever they stand, across walls and floors, so the reading keyed to its room says “near this router”. The figure that means what it says is the building’s: telemetry sums the rooms at the building’s newest report and serves it at GET /telemetry/connected-devices/buildings/{id}.

One device, three metrics. The access point is what gets registered as a sensor — device kind router in telemetry’s plugins::devices(), which reports all three. Registering it once per metric would count one device three times.

None carries a threshold. A device count is an access-point capacity question, not a facility one — it breaches on a room full of laptops. And the estimates beside it are guesses, so a bound on them fires on the guess as much as on the building. Occupancy alerting stays with peopleCount, which measures people instead of inferring them.

Optional — per-AP client counts

Separate from occupancy, and useful for Wi-Fi capacity planning rather than for the twin: how many stations each AP is carrying. It needs no deduplication, unlike the zone path — a station is associated to exactly one AP at a time, so the per-AP lists cannot double-count the way overlapping RSSI coverage can.

readings is keyed (building_id, room_id, metric, ts) with no AP dimension, and ingest does not validate room_id against building_rooms. So the cheap shape is a distinct metric with the AP name in roomId:

metric = "apClients", roomId = "ap-lobby-1", value = 14

Zero migration, existing index, existing hourly rollup. The alternative — the AP name as an extra field in payload — stores fine but is not in the rollup’s group by, so it never aggregates, which is the entire point of collecting it. The cost of the cheap shape is that these rows are only distinguishable from real rooms by their metric key; every query is already metric-scoped, so it works, but it is a convention and not a constraint.

Transitions (not built)

Counts of people moving from one room to another. Digital-twin’s tracks now hold the data to derive them; nothing emits them yet. One new plugin, following the same shape:

static DESCRIPTOR: MetricDescriptor = MetricDescriptor {
    value_field: "zoneTransition",
    key: "zoneTransition",
    label: "Zone Transition",
    interface_name: "IZoneTransition",
    unit: Some("people"),
    fields: &[
        FieldSpec { name: "buildingId",     kind: NonEmptyString,  required: true },
        FieldSpec { name: "roomId",         kind: NonEmptyString,  required: true },
        FieldSpec { name: "fromRoomId",     kind: NonEmptyString,  required: true },
        FieldSpec { name: "timestamp",      kind: Finite,          required: true },
        FieldSpec { name: "zoneTransition", kind: NonNegativeInt,  required: true },
    ],
};

static BOUNDS: &[BoundSpec] = &[BoundSpec { key: "maxTransitions", field: "zoneTransition", label: "Zone transitions", unit: None, direction: Above }];

roomId is the destination; fromRoomId is the extra field, so it lands in the stored payload while the columns stay as they are — consistent with Telemetry Storage. One registration line in backend/telemetry/src/main.rs and the metric is live everywhere.

maxTransitions is not decoration: a sudden flow spike across an edge is the signal for an evacuation or an incident, and the alert path is already built.

Registration

devices/, not simulators/. A simulator is a fake you throw away; the collector is the sensor, shipped to every building and running unattended. edge/ would collide with the ingress proxy, which is what “the edge” means everywhere else in this repository.


What Is Built, What Is Open

Built on branch feat/collector-bursts, against ap-simulator only:

PartWhere
Burst grouping, MAC → token, one signed tick per poll (10 s)devices/ap-collector
Tick contracttwin_schema::WifiObservations, fixtures/wifi-observations.json
Check, count per router room, republish to Kafkatelemetry POST /telemetry/observations
Estimator, tracks, accuracy testdigital-twin estimator.rs, tracks.rs
Dots to the browsertwin → Redis twin:devices:{id} → socket devices event → twin view, devices mode
Room counts by positiontwin → Kafka estimated-occupancy → telemetry estimatedOccupancy

Open, and only real hardware answers them:

The risky unknowns are physical, not code: whether signals separate two rooms depends on where the routers are mounted. Measure before tuning.


Phase 2 — Dedicated Sniffers

Only once phase 1 runs in a real building. Adds coverage of devices that never associate.

Raspberry Pi with a dual-band monitor-mode NIC (mt7612u, ath9k), roughly €60 per unit. An ESP32 is €5 but 2.4 GHz only, and modern phones probe heavily on 5 GHz — systematic undercount. Acceptable for a bench prototype, not for a building.

Do not de-randomize. The literature is good — Bleach reports ~99%, vMac and Espresso combine information elements, sequence numbers and RSSI, one IE-attribute method reports 99% precision across 70+ device types — and every one of them is re-identification engineering. It buys accuracy this feature does not need, at the one cost it cannot pay.

Count without identity instead. RateCount (2025) estimates the device count from a provably unbiased closed form over the rate at which probe frames arrive, with an error model. Learning-free: no training set, no per-site model tuning, no MAC ever inspected. The Keio scheme is the same idea — a phone emits a roughly constant probe rate, so the rate scales with the population.

This is simultaneously the lazier engineering and the defensible privacy story.

Practical corrections the estimator needs: channel hopping means only a fraction of frames are heard, so a duty-cycle term; probe rate varies by phone model and screen state.


Deployment Prerequisites

Phase 1 is only correct if the Wi-Fi is configured for it. These are requirements, not recommendations.

RequirementWhy
One SSID across all APsPer-SSID randomization means a second SSID is a second identity for the same phone.
One SSID across 2.4 and 5 GHzSplit-band SSIDs are two networks; use band steering. Standard practice regardless.
WPA2-AES or WPA3On open networks Apple rotates the private address every 2 weeks. Encryption pins it.
Every router placed in the twinA router sensor in its room, at its position in the twin editor, is the AP → room mapping and the estimator’s geometry; the collector reads the list from GET /telemetry/collector. A router with no placement counts in totalDeviceCount but adds nothing to positions; the editor mounts a router given only a room 0.5 m below that room’s ceiling centre.
One read-only ubus login on the routersThe collector’s own file holds it (per-router overrides where one differs). Logins never reach the platform.

Known Error Sources

SourceEffectHandling
Multiple devices per personPhone + laptop + watch = 3 counts, 1 human. Largest error term by far.A stated conversion factor per building. Cannot be inferred.
People with no deviceUndercount.Inherent. Document the caveat.
Visitors not on the Wi-FiUndercount.Phase 2.
Boundary flappingA router-room count flips rooms each tick.Twin’s tracks smooth the dots and estimatedOccupancy; totalDeviceCount stays unsmoothed.
Walls, antennas, shadowingSignals read weaker than the radio model expects; positions land a room off.Grid fit with walls; measured 79.4% right room on simulated data.
Ambiguous burstsA burst fitting two phones joins neither.Dropped on purpose: no phone gets someone else’s path.
Roam leftoversOld AP lists a roamed device up to 300 s, signal frozen; holds it in its old room.Least-idle row per MAC wins. Rows still tied, e.g. both unchanged since the collector started, fall back to strongest signal.
Android re-randomize on reconnectSplit identity.Non-default per-network option. Rare; ignored.

What is measured is devices; what a facility manager wants is people. That gap is the conversion factor above, and it is why both numbers are published separately rather than one being quietly substituted for the other. The caveat belongs in the user-facing docs too, not only here: ratioDeviceCount and estimatedOccupancy are estimates and read like facts.

The conversion rounds up. One device at a factor of 2.5 is 0.4 of a person, and rounding that to zero reports an occupied room as empty — the one fact the collector otherwise takes care to keep distinct from a genuinely empty zone. An empty zone still converts to 0.

A rejected or unreachable tick POST is logged and dropped, not raised: the run loop calls the post path directly, so an escaping error ends the collector on a single telemetry restart. One lost batch costs one poll interval of resolution; the next tick supersedes it.

Calibration

Every number that depends on the physical world is configuration, per building:

None of these are constants. A building full of engineers and a building full of visitors have different device ratios, and no model can see that from the code.

Two numbers are not on that list, because they are ceilings rather than tuning:


Alternative — Consume the Vendor Controller

If the building runs Cisco, Aruba or Mist, the controller already computes client positions. Cisco Spaces Location Cloud API returns cartesian (x, y) per floor; Mist is equivalent.

Zero hardware, zero algorithm — but vendor lock-in, and the vendor holds the MAC addresses. That moves the privacy problem rather than removing it, and the platform then depends on a commercial contract. Worth taking where the hardware already exists; not worth designing for.


Prior Art & References

Ordered by how directly it feeds the build. The first group is code to read before writing any; the research groups are there to justify — or overturn — a decision, not to be reimplemented.

Phase 1 — closest existing implementations

Read these first. Every one solves a piece of the collector.

Phase 1 — the ubus / hostapd surface

Trilateration — reference implementations

Circles lost to the grid fit on simulated data (69% vs 95% right room); listed so the comparison is checkable.

Phase 2 — sniffers and probe capture

Phase 3 — device-free CSI sensing

Not planned. Tracked because it removes the identifier problem entirely.

Standards and platform behaviour

Counting and localization research

Datasets and simulation

For validating an estimator before any hardware exists.

Videos

Listed by their published title; orientation, not specification.

Privacy and law

Vendor controller APIs

If the building already runs managed Wi-Fi, the position is computed for you.