Ambitwin · source-available, not open source · © 2026 Nicolò Ghignatti
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.
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.
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.
| Data | Where it exists | How long |
|---|---|---|
| MAC address | collector memory only | while the phone is heard |
Token (random, secrets.token_hex(8), never derived from the MAC) | signed tick, Kafka wifi-observations, twin memory | 10 min on Kafka; in twin, until unseen for 3 ticks |
| Position | twin memory (one per track, no history), Redis pub/sub twin:devices:{id} | the current tick only |
| Room counts | Timescale readings | the platform’s retention (below) |
Invariants:
twin_schema::Device refuses unknown fields, so socket drops a dot carrying a token.totalDeviceCount, ratioDeviceCount, estimatedOccupancy.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.
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.
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.
| Platform | Behaviour on the building SSID |
|---|---|
| Android 10–15 | Persistent 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.
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.
| Regime | What the AP sees | Routers-only? |
|---|---|---|
| Associated — device joined the Wi-Fi | Every frame, continuously, stable per-SSID MAC, RSSI per AP | Yes. This is phase 1. |
| Unassociated — visitor never joins | Sporadic 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.
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):
connected: false); one fitting two is dropped.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):
| Dots | Each phone in its router’s room | |
|---|---|---|
| Right room | 79.4% | 75.0% |
| Room counts, total off | 1 462 | 1 988 |
| Position error | median 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.
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 --> TA 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.
GET /telemetry/collector at start and every syncIntervalS (300 s). A router that stays keeps its session; telemetry unreachable keeps the previous list.endpoint is the ubus URL (endpointTemplate fills a missing one); driver openwrt-iwinfo selects the iwinfo reader, anything else hostapd.answered tells telemetry nothing was measured, so no room gets a fresh 0. Trimmed to the contract’s limits (2000 rows, keeping the loudest; 2000 bursts, keeping the newest; 6 loudest routers per burst), since telemetry refuses an oversized tick whole. A refused or failed post is dropped, never retried: the next poll supersedes it.ubus login and ifaces, per-router overrides. Never sent to the platform.keys: { "<buildingId>": "<device key>" } in the same file, issued by an editor (POST /telemetry/device-keys/buildings/{id}). Each key reads that building’s routers and signs its ticks; it cannot sign for another building.subscribeProbes: true): one hostapd probe stream per router interface, grouped each tick into bursts (app/bursts.py) — one address within 2 s of its first frame is one scan, keeping each router’s loudest frame. A burst the tick cuts in half waits for the next tick. --dry-run prints counts, never an address or a token.app/tokens.py): every address is swapped for a random token (secrets.token_hex(8)), minted, never derived, so nothing can turn one back. A connected phone keeps its token until it is missing for 3 ticks; a burst gets a fresh one, unless it was sent from a connected phone’s own address. The mac → token table lives only in the collector’s memory.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:
(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.ap_max_inactivity (300 s).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).
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.
Telemetry stores these for every room, every tick (the factor rides on the tick as devicesPerPerson):
| Metric | What it is | From |
|---|---|---|
totalDeviceCount | Devices connected, each in its loudest router’s room. A measurement. | telemetry, from the tick |
ratioDeviceCount | Devices ÷ the site’s devices-per-person factor. An estimate. | telemetry, from the tick |
estimatedOccupancy | Connected 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.
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 = 14Zero 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.
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.
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.
ap-collector: "devices/ap-collector" in .moon/workspace.yml..github/services.json with no image key. ci-gate.yml gates the docker matrix on select(.image and (.ci != false)), so omitting the image skips the build while the tests still run. Do not copy the simulators’ "ci": false — that also drops the package from coverage and from check-workflow-registry.py, and union-by-MAC is the likeliest bug in the design.ci-gate.yml using tpl-python-ci.yml, listed in both docker.needs and ci-passed.needs — check-workflow-registry.py fails otherwise.moon.yml overrides the inherited test / lint, which shell out to npm. Agent wraps uv in a package.json; this package cannot, because the root .gitignore ignores every package.json. Both overrides use script:, not command: — command: merges with the inherited task’s args and silently runs uv test./telemetry/observations are both JSON over HTTP, and signing is hmac.new(key, body, sha256). urllib.request covers it.Built on branch feat/collector-bursts, against ap-simulator only:
| Part | Where |
|---|---|
| Burst grouping, MAC → token, one signed tick per poll (10 s) | devices/ap-collector |
| Tick contract | twin_schema::WifiObservations, fixtures/wifi-observations.json |
| Check, count per router room, republish to Kafka | telemetry POST /telemetry/observations |
| Estimator, tracks, accuracy test | digital-twin estimator.rs, tracks.rs |
| Dots to the browser | twin → Redis twin:devices:{id} → socket devices event → twin view, devices mode |
| Room counts by position | twin → Kafka estimated-occupancy → telemetry estimatedOccupancy |
Open, and only real hardware answers them:
ap_max_inactivity (300 s). A time limit would fix it, but would also drop phones that are present but asleep.estimatedOccupancy.The risky unknowns are physical, not code: whether signals separate two rooms depends on where the routers are mounted. Measure before tuning.
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.
Phase 1 is only correct if the Wi-Fi is configured for it. These are requirements, not recommendations.
| Requirement | Why |
|---|---|
| One SSID across all APs | Per-SSID randomization means a second SSID is a second identity for the same phone. |
| One SSID across 2.4 and 5 GHz | Split-band SSIDs are two networks; use band steering. Standard practice regardless. |
| WPA2-AES or WPA3 | On open networks Apple rotates the private address every 2 weeks. Encryption pins it. |
| Every router placed in the twin | A 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 routers | The collector’s own file holds it (per-router overrides where one differs). Logins never reach the platform. |
| Source | Effect | Handling |
|---|---|---|
| Multiple devices per person | Phone + laptop + watch = 3 counts, 1 human. Largest error term by far. | A stated conversion factor per building. Cannot be inferred. |
| People with no device | Undercount. | Inherent. Document the caveat. |
| Visitors not on the Wi-Fi | Undercount. | Phase 2. |
| Boundary flapping | A router-room count flips rooms each tick. | Twin’s tracks smooth the dots and estimatedOccupancy; totalDeviceCount stays unsmoothed. |
| Walls, antennas, shadowing | Signals 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 bursts | A burst fitting two phones joins neither. | Dropped on purpose: no phone gets someone else’s path. |
| Roam leftovers | Old 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 reconnect | Split 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.
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:
requestTimeoutS <= pollIntervalS (defaults 5 s and 10 s). Holds only because the collector polls every AP of a building concurrently. Polled in sequence a tick would cost the sum of its APs’ timeouts, so enough dark APs would silently slow the real poll rate. One AP’s own interfaces are still read in series, so an AP with many radios and a long timeout is the one case still worth checking by hand.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.
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.
Read these first. Every one solves a piece of the collector.
wifi_stations collector in prometheus-node-exporter-lua, then polls /metrics on each AP every 5 s for wifi_station_signal_dbm. The simplest transport for the collector: no ubus auth, no custom ACLs.ubus client pulling per-station RSSI, connection quality and which AP interface each device is on.ubus interface (source) — authoritative definition of get_clients and the rest. The docs lag; the source does not.session.login for a token, then call with the object and method.get_hostapd_clients./usr/share/rpcd/acl.d/ needed to grant hostapd methods to a non-root RPC user. Easy to miss; nothing works without it.rpcd, uhttpd-mod-ubus, ACL) in user-facing terms.Circles lost to the grid fit on simulated data (69% vs 95% right room); listed so the comparison is checkable.
d = 10 ^ ((Ptx - RSSI) / (10n)) whose exponent n is the per-site calibration that makes this expensive.tshark on a monitor-mode adapter. Small, readable, and the direct ancestor of the rate-based approach.Not planned. Tracked because it removes the identifier problem entirely.
wifi_sensing_demo for motion and human presence with on-site training.For validating an estimator before any hardware exists.
sapienza/probe-requests (IEEE DataPort) — the classic set: four one-shot events of 40 min to 6 h, plus six weeks of fixed capture on a campus.simulators/.Listed by their published title; orientation, not specification.
If the building already runs managed Wi-Fi, the position is computed for you.
(x, y) per floor.