648 lines
31 KiB
Markdown
648 lines
31 KiB
Markdown
# CLAUDE.md — pyFi Project Guide
|
||
|
||
This file is the authoritative context document for Claude Code sessions on the
|
||
pyFi project. Read this file completely before starting any non-trivial work.
|
||
|
||
---
|
||
|
||
## Before You Touch Any File
|
||
|
||
Follow this protocol on every edit to avoid the most common session errors:
|
||
|
||
1. **View before editing.** Always call `view` on a file immediately before
|
||
`str_replace`. A previous edit in the same session invalidates earlier view
|
||
output — stale context causes "string not found" failures.
|
||
2. **One logical change per str_replace.** Don't bundle unrelated edits.
|
||
3. **Syntax-check after every Python edit:**
|
||
```bash
|
||
python3 -c "import ast; ast.parse(open('filename.py').read()); print('OK')"
|
||
```
|
||
4. **Grep for stale references after renaming or removing anything:**
|
||
```bash
|
||
grep -n "old_name" main.py renderer.py data.py scanner.py interpolator.py
|
||
```
|
||
5. **Never assume file content from memory.** If in doubt, view the relevant
|
||
section before writing a replacement.
|
||
|
||
---
|
||
|
||
## Project Identity
|
||
|
||
**Name:** pyFi
|
||
**Type:** Cross-platform desktop WiFi heatmap generator
|
||
**Language:** Python 3.10+
|
||
**GUI:** tkinter + matplotlib (TkAgg backend)
|
||
**Entry point:** `main.py`
|
||
**Branding assets:** `extras/pyfi-logo.ico` (taskbar), `extras/pyfi-mini.png` (sidebar logo)
|
||
|
||
---
|
||
|
||
## Project Files
|
||
|
||
| File | Purpose |
|
||
|---|---|
|
||
| `main.py` | Tkinter GUI — two-tab layout, auto-scan engine, AP stats, AP placement drag-and-drop |
|
||
| `scanner.py` | Cross-platform WiFi scanning with platform-specific backends |
|
||
| `interpolator.py` | Spatial interpolation — auto-selects RBF, cubic, or linear |
|
||
| `renderer.py` | Ekahau-style RGBA heatmap rendering with signal-driven alpha |
|
||
| `data.py` | Session model — measurements, multi-BSSID ops, JSON persistence |
|
||
| `requirements.txt` | `numpy`, `scipy`, `matplotlib`, `Pillow` |
|
||
| `extras/` | Brand assets (logo, icon, screenshots for README) |
|
||
|
||
---
|
||
|
||
## Architecture Overview
|
||
|
||
pyFi is structured as a clean pipeline:
|
||
|
||
```
|
||
OS WiFi API → scanner.py → data.py (Session) → interpolator.py → renderer.py → tkinter Canvas
|
||
```
|
||
|
||
### `scanner.py` — scanning backends
|
||
|
||
Each OS uses the most accurate available API, with graceful fallback:
|
||
|
||
| OS | Primary | Fallback 1 | Fallback 2 |
|
||
|---|---|---|---|
|
||
| Windows | `wlanapi` via `ctypes` | `netsh wlan show networks` | — |
|
||
| Linux | `iw dev scan` | `nmcli dev wifi list` | `iwlist scan` |
|
||
| macOS | `airport -s` | — | — |
|
||
|
||
`scan_averaged(samples=10, delay=0.1)` takes the **median** (not mean) of 10
|
||
samples at 100 ms intervals. The median is more robust against RF burst spikes.
|
||
|
||
**Beacon IE parsing (Windows wlanapi).** The Windows scan list under-reports:
|
||
`dot11BssPhyType` caps at HE (10) even for Wi-Fi 7, channel width is never
|
||
exposed, and security is only available keyed by SSID (so hidden networks miss
|
||
it). To fix all three, the wlanapi backend snapshots each BSS entry's raw
|
||
802.11 Information Elements and parses them directly:
|
||
|
||
| Helper | Reads | Produces |
|
||
|---|---|---|
|
||
| `_mode_from_ies()` | EHT/HE/VHT/HT **Capabilities** elements | Wi-Fi 4/5/6/6E/7 mode |
|
||
| `_security_from_ies()` | RSN (48) + WPA1 vendor (221) elements | WPA2/WPA3/Enterprise/OWE |
|
||
| `_width_from_ies()` | EHT/HE/VHT/HT **Operation** elements | 20/40/80/160/320 MHz |
|
||
|
||
The IE bytes are read once per scan via `ctypes.string_at(base, dwTotalSize)`
|
||
(a bounded copy), and every field access is a length-guarded slice of that
|
||
`bytes` object — a malformed IE yields a blank result, never an out-of-bounds
|
||
read. See Decisions #16–#20.
|
||
|
||
### `data.py` — Session model
|
||
|
||
Key methods:
|
||
- `get_points_and_values(bssid)` — single BSSID signal data
|
||
- `get_points_and_values_multi(bssids)` — averaged across multiple BSSIDs;
|
||
only BSSIDs visible at each location contribute (absent ones are excluded,
|
||
not zeroed)
|
||
- `get_missing_points(bssids)` — positions where none of the selected BSSIDs
|
||
were visible; rendered as black `?` dots
|
||
- `get_anchor_points(bssids)` — synthetic peak points at known AP positions;
|
||
injected into interpolation to anchor the heatmap correctly at the transmitter
|
||
- `ap_positions: dict[str, tuple[float,float]]` — optional physical position
|
||
of each AP on the canvas; saved/loaded with the session JSON
|
||
|
||
### `interpolator.py` — method selection
|
||
|
||
| Points available | Method |
|
||
|---|---|
|
||
| < 4 | No heatmap (progress indicator shown) |
|
||
| 4–8 | Cubic (Delaunay triangulation via scipy `griddata`) |
|
||
| 9+ | RBF — Radial Basis Function, thin-plate spline kernel |
|
||
|
||
The 4-point minimum exists because `griddata(method='cubic')` and even
|
||
`method='linear'` use Qhull triangulation which raises `QH6214` with fewer
|
||
than 4 non-collinear points.
|
||
|
||
### `renderer.py` — Ekahau-style RGBA rendering
|
||
|
||
The heatmap is a `uint8` RGBA numpy array, not a matplotlib `ScalarMappable`.
|
||
|
||
**Colormap** (`SIGNAL_CMAP`): violet (-90 dBm) → blue → teal → green →
|
||
yellow-green → yellow → orange → red (-30 dBm). Warm = strong, cool = weak.
|
||
|
||
**Alpha channel**: per-pixel cosine ease-in-out ramp between `FADE_FLOOR`
|
||
(-85 dBm, fully transparent) and VMAX (-30 dBm, fully opaque). A Gaussian
|
||
blur (`sigma=8`) is applied to alpha to soften zone edges and blend overlapping
|
||
AP coverage bubbles.
|
||
|
||
**Colorbar**: drawn by `_draw_colorbar()` using a direct `imshow` of a 256×1
|
||
gradient on a dedicated `cax` axes. Does NOT use `fig.colorbar()` with a
|
||
`ScalarMappable` — see Decision #11.
|
||
|
||
**AP markers**: `_draw_ap_markers()` draws a diamond icon (pulse ring + outer
|
||
white diamond + signal-colored inner diamond + WiFi arcs + SSID label) at each
|
||
pinned AP position. Visually distinct from measurement dots (circles).
|
||
|
||
---
|
||
|
||
## Key Design Decisions
|
||
|
||
### Decision #1 — BSSID as the primary AP identifier, not SSID
|
||
|
||
SSIDs are not unique. Multiple physical radios (e.g. all nodes in a mesh
|
||
network) can broadcast the same SSID. The BSSID (hardware MAC address) is
|
||
the only reliable per-radio identifier. All session data, selection state,
|
||
and heatmap rendering is keyed on BSSID.
|
||
|
||
### Decision #2 — Floorplan is optional, not required
|
||
|
||
The app works without a floorplan using a coordinate grid as the canvas
|
||
background. Every surface that touches this state (sidebar label, heatmap
|
||
subtitle, export PNG footer) shows a `⚠ Adding a floorplan increases accuracy`
|
||
warning to guide users toward the better workflow without blocking them.
|
||
|
||
### Decision #3 — Minimum 4 points before rendering
|
||
|
||
The original code used `>= 2` which triggered `QH6214 qhull input error`
|
||
from scipy because Delaunay triangulation needs at least 4 non-collinear
|
||
points. Raised to 4 as the universal safe floor. A progress bar indicator
|
||
`[██░░] 2/4` is shown until the threshold is met.
|
||
|
||
### Decision #4 — Multi-BSSID averaging excludes absent BSSIDs per point
|
||
|
||
When multiple BSSIDs are selected, each measurement point averages only the
|
||
BSSIDs that were actually visible there. A BSSID that was out of range at a
|
||
location is excluded rather than contributing a -90 floor value. This is
|
||
critical for mesh networks where different nodes cover different areas.
|
||
|
||
### Decision #5 — Median instead of mean for scan averaging
|
||
|
||
WiFi RSSI has burst spikes that can be 10–15 dBm away from the true value.
|
||
The median discards these outliers. 10 samples at 100 ms intervals
|
||
(~1.1 seconds total) catches multiple beacon intervals.
|
||
|
||
### Decision #6 — wlanapi via ctypes instead of netsh on Windows
|
||
|
||
`netsh wlan show networks` converts raw RSSI to a 0–100% quality score,
|
||
which most drivers clamp at -55 dBm → 100% → -50 dBm. This means all
|
||
strong signals appear identical. Confirmed empirically by comparing our
|
||
readings (-50 dBm everywhere near the router) against NetSpot readings
|
||
(-37 to -45 dBm at the same locations). The `wlanapi` `WlanGetNetworkBssList()`
|
||
call returns the raw `dot11_RSSI` field with no clamping.
|
||
|
||
Critical struct detail: `DOT11_SSID` is `{ ULONG uSSIDLength; UCHAR ucSSID[32]; }`
|
||
(36 bytes total). The original code had it as `c_ubyte * 33`, treating byte `[0]`
|
||
as the length and reading from offset 1. This is wrong — `uSSIDLength` is a
|
||
4-byte ULONG, so `ucSSID` starts at offset 4. The misread caused SSIDs to be
|
||
truncated (e.g. "NETGEAR22" → "NETGEA").
|
||
|
||
Mode/security/width are NOT taken from the scan list's struct fields (which
|
||
under-report — see Decisions #16–#20); they are parsed from each entry's raw
|
||
beacon IEs instead.
|
||
|
||
### Decision #7 — iw instead of nmcli on Linux
|
||
|
||
`nmcli` reads from NetworkManager's scan cache with its own smoothing.
|
||
`iw dev <iface> scan` calls `nl80211` directly, returns signal in mBm
|
||
(0.1 dBm precision), and provides raw IE (Information Element) data for
|
||
accurate HE/VHT/HT mode detection.
|
||
|
||
### Decision #8 — Networks never disappear from the AP tab list
|
||
|
||
Once a BSSID is seen it stays in the table permanently, shown dimmed when
|
||
out of range. `_known_bssids_ordered()` merges the current scan with
|
||
`_ap_stats` (which accumulates all seen BSSIDs). Stale rows show "out of
|
||
range" in the Level column and keep their historical Max/Min/Avg stats.
|
||
|
||
### Decision #9 — AP tab column alignment via fixed-pixel container frames
|
||
|
||
tkinter `Label(width=N)` uses character units which vary by font, causing
|
||
headers to misalign with data. The fix wraps every cell (both header and
|
||
data rows) in a `tk.Frame(width=px, height=ROW_HEIGHT)` with
|
||
`pack_propagate(False)`, then uses `place(relwidth=1, relheight=1)` for the
|
||
label inside. Pixel widths are defined once in `AP_COLUMNS` and used
|
||
identically for both header and data rows.
|
||
|
||
### Decision #10 — Colorbar stacking fix via dedicated cax axes
|
||
|
||
`fig.colorbar(ax=ax)` steals a fraction of `ax`'s position on each call.
|
||
`ax.clear()` resets content but not position, so the axes shrank ~3% per
|
||
redraw. Fixed by: (1) calling `fig.subplots_adjust(right=0.88)` once at
|
||
figure creation to permanently reserve colorbar space, and (2) using
|
||
`fig.add_axes([0.91, 0.15, 0.02, 0.70])` with a dedicated `cax` so
|
||
matplotlib never touches the main axes position.
|
||
|
||
### Decision #11 — Colorbar rendered as direct imshow, not fig.colorbar()
|
||
|
||
`fig.colorbar()` with a `ScalarMappable(set_array([]))` renders as a white
|
||
rectangle on some matplotlib/backend combinations because the mappable has
|
||
no associated axes and no data range that all backends interpret consistently.
|
||
The fix: `_draw_colorbar()` calls `cax.imshow()` directly with a 256×1 gradient
|
||
array mapped through `SIGNAL_CMAP`. This is unconditional and backend-agnostic.
|
||
|
||
### Decision #12 — Ekahau-style signal-driven alpha (bubble effect)
|
||
|
||
The original renderer used a flat `alpha=0.65` scalar, producing a solid
|
||
rectangular overlay with no zone definition. The new approach builds a `uint8`
|
||
RGBA array where the alpha channel is a per-pixel cosine ramp based on signal
|
||
strength. Weak zones fade to transparent (showing the floorplan through),
|
||
strong zones stay opaque. A Gaussian blur on the alpha channel blends
|
||
overlapping coverage bubbles. This matches the visual output of professional
|
||
tools like Ekahau and NetSpot.
|
||
|
||
### Decision #13 — AP position anchoring for interpolation accuracy
|
||
|
||
Without knowing where APs physically are, the interpolator estimates signal
|
||
peaks from surrounding measurement points — which can place the peak in the
|
||
wrong location, especially in mesh systems with uneven measurement density.
|
||
`get_anchor_points(bssids)` injects a synthetic point at each pinned AP
|
||
position with value `min(-25, max_real_reading + 5)`. This anchors the
|
||
heatmap peak at the transmitter location without appearing as a measurement dot.
|
||
|
||
### Decision #14 — PyInstaller asset path resolution
|
||
|
||
`os.path.dirname(__file__)` does not work in PyInstaller bundles because
|
||
`__file__` points to the temp extraction directory, not the source tree.
|
||
`_resource_path(relative)` uses `getattr(sys, "_MEIPASS", os.path.dirname
|
||
(os.path.abspath(__file__)))` to resolve correctly in both source and compiled
|
||
modes. All asset paths go through this helper.
|
||
|
||
### Decision #15 — Mesh network uniformity problem
|
||
|
||
When a mesh system (e.g. Netgear RS500 + Orbi RBK750 with two satellites) all
|
||
broadcast the same SSID, the device silently roams between nodes. Measurements
|
||
always land on whichever node is currently serving the device, which is always
|
||
the strongest one nearby. This produces uniform readings across the entire floor
|
||
because the device is never far from a strong signal. The solution is to select
|
||
individual BSSIDs (one per radio) on the Access Points tab and map each node
|
||
separately, or temporarily disable other nodes during a single-radio session.
|
||
|
||
### Decision #16 — Wi-Fi 6E / 7 and the 6 GHz band
|
||
|
||
Mode detection covers `n/ac/ax/ax(6E)/be` (Wi-Fi 4 → 7). The band is derived
|
||
from **frequency**, not channel number, because 6 GHz channel numbers overlap
|
||
with 2.4/5 GHz ones — `_band_from_freq()` maps 5925–7125 MHz → "6 GHz" and is
|
||
preferred over `_band_from_channel()` whenever a frequency is known. Channel
|
||
width adds **320 MHz** (Wi-Fi 7 only).
|
||
|
||
### Decision #17 — Mode comes from beacon IEs, not `dot11BssPhyType`
|
||
|
||
The Windows `WlanGetNetworkBssList` `dot11BssPhyType` field **caps at HE (10)
|
||
and never reports EHT (11)**, even for 802.11be APs — only the connected-
|
||
association path (`netsh wlan show interfaces`) surfaces `802.11be`. So Wi-Fi 7
|
||
is detectable from a scan *only* by parsing the **EHT Capabilities** element
|
||
(Element ID 255, Ext ID 108). `_mode_from_ies()` checks EHT(108) → Wi-Fi 7,
|
||
HE(35) [+ 6 GHz freq or HE-6GHz-band-cap (59)] → Wi-Fi 6E/6, VHT(191) → 5,
|
||
HT(45) → 4. The `dot11BssPhyType` map remains only as a fallback — and its
|
||
enum was corrected (7=HT/n, 8=VHT/ac, 9=DMG, 10=HE/ax, 11=EHT/be; the old map
|
||
was off by one for 7/8/9).
|
||
|
||
### Decision #18 — `WLAN_BSS_ENTRY` struct must be byte-exact for IE access
|
||
|
||
The original ctypes `WLAN_BSS_ENTRY` had `bInRegDomain` as `BOOL` (4 bytes; it
|
||
is `BOOLEAN` = 1 byte) and `wlanRateSet` as `c_ubyte * 16` (it is
|
||
`WLAN_RATE_SET` = **256 bytes**). Those fields precede `ulIeOffset`/`ulIeSize`,
|
||
so both were read 240+ bytes off — pointing at garbage. This is why an early
|
||
attempt to read IEs via `from_address()` **crashed the app**. Fixed layout:
|
||
`sizeof = 360`, `ulIeOffset` at offset 352. (RSSI/freq/phy sit *before* the
|
||
broken fields, which is why scanning itself always worked.) Verify any struct
|
||
change with `ctypes.sizeof` + field `.offset` against these numbers.
|
||
|
||
### Decision #19 — Security from RSN IE; hidden networks via Privacy bit
|
||
|
||
Security resolves in three tiers: (1) SSID-keyed `dot11DefaultAuthAlgorithm`
|
||
from `WlanGetAvailableNetworkList`; (2) for hidden networks (no SSID to key
|
||
on), `_security_from_ies()` parses the **RSN element (48)** AKM suite types —
|
||
PSK(2/4/6)→WPA2, SAE(8/9)→WPA3, 802.1X(1/3/5/11–13)→Enterprise, OWE(18) — plus
|
||
the WPA1 vendor IE (221, OUI 00:50:F2:01); (3) the **Privacy bit** (0x10) of
|
||
`usCapabilityInformation` → "Secured"/"Open". RSN field offsets are exact:
|
||
within the element body, pairwise-cipher count is at offset **6** (after
|
||
version[2] + group-cipher[4]), AKM list follows the pairwise list.
|
||
|
||
### Decision #20 — Channel width from Operation elements; "Local" vendor
|
||
|
||
`_width_from_ies()` parses width from the **Operation** elements (the scan
|
||
list never exposes it), newest generation winning: EHT Operation (Ext 106,
|
||
3-bit width 0–4 = 20/40/80/160/320) → HE Operation (Ext 36; 6 GHz Op Info or
|
||
embedded VHT Op Info) → VHT Operation (El 192, width+seg0/seg1) → HT Operation
|
||
(El 61, secondary-offset + width-any → 20/40). All reads are length-guarded.
|
||
The **HT, VHT, and HE** (incl. 6 GHz Op Info) offsets are validated byte-for-byte
|
||
against the Linux kernel headers — HE matches `ieee80211_he_6ghz_oper()` exactly
|
||
(`optional[]` at struct offset 6 → `body[7]`; `VHT_OPER_INFO=0x4000`,
|
||
`CO_HOSTED_BSS=0x8000`, `6GHZ_OP_INFO=0x20000`; 6 GHz `control & 0x3` →
|
||
20/40/80/160). The **EHT** path (Ext 106 → `params`[1] bit0 = info-present,
|
||
`basic_mcs_nss`[4], `control` at `body[6]`, 3-bit width 0–4 = 20/40/80/160/320)
|
||
is confirmed only against the spec encoding — no `ieee80211-eht.h` was available
|
||
to cross-check; re-verify against the kernel `ieee80211_eht_operation` /
|
||
`ieee80211_eht_operation_info` structs if touched. Separately, `lookup_vendor()`
|
||
returns **"Local"** for locally-administered BSSIDs (U/L bit 0x02 set in the
|
||
first octet) — these are the randomized virtual/guest/mesh BSSIDs a single radio
|
||
spawns, whose OUI is not a real IEEE assignment.
|
||
|
||
---
|
||
|
||
## Known Issues & Gotchas
|
||
|
||
**Windows 11 24H2+**: Microsoft requires Location Services to be enabled for
|
||
WiFi scanning APIs to return BSSID data. This is an OS restriction, not a
|
||
pyFi bug. Users must enable Location Services in Settings.
|
||
|
||
**tkinter PhotoImage garbage collection**: If a `PhotoImage` object goes out of
|
||
scope, Python's GC destroys it and the label shows blank. Always store a
|
||
reference on the parent widget (e.g. `f._logo_img_ref = img`).
|
||
|
||
**`RegularPolygon` orientation**: matplotlib's `RegularPolygon` with
|
||
`numVertices=4` defaults to a square (flat-bottom). `orientation=np.pi/4`
|
||
rotates it 45° to produce a diamond shape.
|
||
|
||
**Duplicate `_draw_ap_markers`**: At one point the renderer had two definitions
|
||
of this function (the second silently overwriting the first) AND neither was
|
||
being called from `render_heatmap`. Both issues were resolved in the same fix.
|
||
|
||
**Auto-scan vs placement scan conflict**: If a placement scan (`_scan_for_placement`)
|
||
is in progress when the auto-scan timer fires, `_fire_auto_scan` detects
|
||
`self.scanning == True` and reschedules without firing, preventing a race condition.
|
||
|
||
**BSSID SSID truncation (Windows)**: The `DOT11_SSID` struct was originally
|
||
defined as `c_ubyte * 33` which misread the 4-byte `uSSIDLength` field.
|
||
This truncated SSIDs to their first 6 bytes. Fixed by defining a proper
|
||
`DOT11_SSID` ctypes Structure.
|
||
|
||
**Wi-Fi 7 not seen in scans**: If an 802.11be AP shows as Wi-Fi 6/6E, the cause
|
||
is almost always the `dot11BssPhyType` HE cap (Decision #17) — confirm the EHT
|
||
Capabilities IE (Ext 108) is actually being parsed, not the phy-type field.
|
||
`netsh wlan show interfaces` showing `802.11be` does NOT mean the scan list
|
||
does; it uses a different (connected-association) code path.
|
||
|
||
**OUI vendor database**: `lookup_vendor()` is backed by the full IEEE OUI CSV
|
||
(~37k entries), downloaded once to `~/.pyfi/oui.csv` and refreshed every 30
|
||
days. The download runs in a daemon thread started at module import, so the
|
||
*first ever* scan (cold cache, before the download finishes) may briefly show
|
||
`-`/built-in-table vendors; subsequent scans have the full DB. A small
|
||
built-in table (`_OUI_BUILTIN`) is the offline fallback. Locally-administered
|
||
BSSIDs short-circuit to "Local" before any lookup.
|
||
|
||
**Show Hidden toggle**: The AP tab has a "Show Hidden" checkbox (default off)
|
||
that filters rows whose SSID is `<hidden>`/empty. `_populate_ap_table` skips
|
||
them using a separate `visible_idx` counter for row numbering/striping —
|
||
`_ap_row_widgets` stays keyed by BSSID, so Select All / toggles remain correct.
|
||
|
||
---
|
||
|
||
## AP_COLUMNS — Canonical Column Definition
|
||
|
||
This list in `main.py` drives pixel widths for both the header row and every
|
||
data row in the Access Points table. Header and data cells use identical
|
||
fixed-pixel container frames — any mismatch causes misalignment. Always update
|
||
both if adding a column.
|
||
|
||
```python
|
||
AP_COLUMNS = [
|
||
("sel", "✓", 38),
|
||
("ssid", "SSID", 160),
|
||
("bssid", "BSSID", 145),
|
||
("channel", "Ch", 38),
|
||
("freq", "Frequency", 90),
|
||
("width", "Ch Width", 75),
|
||
("band", "Band", 60),
|
||
("security", "Security", 160),
|
||
("vendor", "Vendor", 90),
|
||
("mode", "Mode", 90),
|
||
("level", "Level", 110), # canvas-drawn signal bar, not a Label
|
||
("last_seen", "Last Seen", 75),
|
||
("max_dbm", "Max", 50),
|
||
("min_dbm", "Min", 50),
|
||
("avg_dbm", "Avg", 50),
|
||
]
|
||
```
|
||
|
||
The `level` column is special — it's a `tk.Canvas` widget drawn by
|
||
`_draw_signal_bar()`, not a `_cell()` label. It must be handled separately
|
||
in `_populate_ap_table`.
|
||
|
||
---
|
||
|
||
## Heatmap Tab State Variables
|
||
|
||
These variables on `WiFiHeatmapApp` interact during scanning and AP placement.
|
||
Understand their invariants before modifying either workflow.
|
||
|
||
| Variable | Type | Invariant |
|
||
|---|---|---|
|
||
| `_placement_mode` | `bool` | True only between `_ready_to_place()` and the canvas click that records the measurement |
|
||
| `_pending_scan` | `list[AccessPoint] \| None` | Holds scan results while `_placement_mode` is True; cleared on canvas click |
|
||
| `_ap_drag_mode` | `bool` | True while the "Place APs" button is active; toggled by `_toggle_ap_drag_mode()` |
|
||
| `_dragging_bssid` | `str \| None` | The BSSID armed for placement; set by `_select_ap_for_pin()`, cleared after a drop |
|
||
| `_ap_drag_preview` | `list \| None` | Temporary crosshair artists on the canvas; removed on next motion event |
|
||
| `scanning` | `bool` | True during any background scan thread; guards against concurrent scans |
|
||
| `selected_bssids` | `set[str]` | BSSIDs checked on the AP tab; source of truth for selection |
|
||
| `selected_bssids_for_heatmap` | `list[str]` | Ordered list derived from `selected_bssids` by `_sync_heatmap_bssids()`; passed to renderer |
|
||
|
||
**Critical invariant**: `scanning` must be set to `True` before spawning a
|
||
background thread and back to `False` (on the main thread via `root.after`)
|
||
when done. Never set it from the background thread directly.
|
||
|
||
**Critical invariant**: `_placement_mode` and `_ap_drag_mode` are mutually
|
||
exclusive in practice — `_on_canvas_click` checks `_ap_drag_mode` first and
|
||
returns early, so a placement click is only processed when drag mode is off.
|
||
|
||
---
|
||
|
||
## Matplotlib Figure Structure
|
||
|
||
The figure is created once in `_build_heatmap_tab` and reused across all
|
||
redraws. Its structure must be respected:
|
||
|
||
- `fig.axes[0]` — always the main plot (`ax`). Never remove this.
|
||
- `fig.axes[1:]` — colorbar axes from previous renders. These are removed at
|
||
the top of every `render_heatmap` call with `for ax_obj in fig.axes[1:]: ax_obj.remove()`.
|
||
- `fig.subplots_adjust(right=0.88)` — called once at figure creation. Reserves
|
||
the right 12% for the colorbar permanently. Do not call this on every render
|
||
or it will compound.
|
||
- Colorbar `cax` position: `[0.91, 0.15, 0.025, 0.70]` in figure-fraction
|
||
units (left, bottom, width, height). Created fresh each render by
|
||
`_draw_colorbar()`.
|
||
|
||
**Do not pass `ax=ax` to `fig.colorbar()`**. This steals space from `ax` on
|
||
every call and the axes shrinks permanently. Always use `cax=` with a
|
||
pre-made axes, or use `_draw_colorbar()` which renders the gradient directly.
|
||
|
||
---
|
||
|
||
## Session JSON Schema
|
||
|
||
```json
|
||
{
|
||
"name": "string",
|
||
"floorplan_path": "string | null",
|
||
"canvas_width": 800,
|
||
"canvas_height": 600,
|
||
"created_at": "ISO datetime string",
|
||
"updated_at": "ISO datetime string",
|
||
"ap_positions": {
|
||
"AA:BB:CC:DD:EE:FF": [123.4, 456.7]
|
||
},
|
||
"measurements": [
|
||
{
|
||
"x": 123.4,
|
||
"y": 456.7,
|
||
"signals": { "AA:BB:CC:DD:EE:FF": -52 },
|
||
"ssid_map": { "AA:BB:CC:DD:EE:FF": "MyNetwork" },
|
||
"timestamp": "ISO datetime string"
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
**Backward compatibility rule**: every field read in `Session.load()` must use
|
||
`data.get("field", default)` or have an explicit `if "field" in data` guard.
|
||
Sessions saved before a new field was added must still load without error.
|
||
`ap_positions` is an example — it was added after initial sessions existed,
|
||
so `load()` uses `data.get("ap_positions", {})`.
|
||
|
||
---
|
||
|
||
## What Could Reasonably Be Unit-Tested
|
||
|
||
There is currently no automated test suite. These areas are well-suited for
|
||
testing without requiring OS WiFi hardware or a display:
|
||
|
||
| Area | What to test |
|
||
|---|---|
|
||
| `interpolator.py` | Minimum point threshold (3 points raises ValueError, 4 succeeds), method selection (< 9 → cubic, ≥ 9 → rbf), NaN fill at edges |
|
||
| `data.py — get_points_and_values_multi` | Single BSSID equals `get_points_and_values`, absent BSSID excluded not zeroed, empty selection returns empty lists |
|
||
| `data.py — get_missing_points` | Returns positions where no selected BSSID was seen, returns empty when all BSSIDs visible |
|
||
| `data.py — get_anchor_points` | Returns empty when no AP positions set, synthetic value is `min(-25, max_reading + 5)` |
|
||
| `data.py — Session save/load` | Round-trip preserves all fields, missing `ap_positions` key loads as empty dict |
|
||
| `scanner.py — scan_averaged median` | Given known readings, median is returned not mean; single-sample case returns that value |
|
||
| `scanner.py — _channel_from_freq` | 2437 → channel 6, 5180 → channel 36, 2484 → channel 14 |
|
||
| `scanner.py — _band_from_freq` | 2422 → 2.4 GHz, 5180 → 5 GHz, 6295 → 6 GHz |
|
||
| `scanner.py — _mode_from_ies` | EHT cap → Wi-Fi 7, HE cap + 6 GHz → 6E, VHT → 5, HT → 4, empty → "" |
|
||
| `scanner.py — _security_from_ies` | RSN AKM PSK → WPA2, SAE → WPA3, both → WPA2/WPA3, 802.1X → Enterprise, WPA1 vendor IE → WPA-Personal |
|
||
| `scanner.py — _width_from_ies` | EHT width 4 → 320, 3 → 160; VHT seg gap 8 → 160; HT sec+wide → 40; EHT wins over VHT/HT |
|
||
| `scanner.py — lookup_vendor` | U/L bit set (e.g. D6:…) → "Local"; globally-unique OUI → vendor name |
|
||
| `main.py — _resource_path` | When `sys._MEIPASS` is not set, returns path relative to `__file__`; when set, returns path relative to `_MEIPASS` |
|
||
| `renderer.py — _build_ekahau_rgba` | Output shape is `(H, W, 4)` uint8, NaN cells have alpha=0, strong signal cells have high alpha |
|
||
|
||
**What cannot reasonably be unit-tested without significant mocking:**
|
||
- Actual WiFi scanning (requires OS API and a WiFi adapter)
|
||
- tkinter GUI behavior (requires a display; `tkinter.Tcl()` can test some logic but is fragile)
|
||
- Matplotlib rendering output (visual; would need image comparison with tolerances)
|
||
- PyInstaller bundle behavior
|
||
|
||
---
|
||
|
||
## Known Fragile Areas
|
||
|
||
These are not bugs but structural fragilities where a well-intentioned change
|
||
is likely to break something non-obvious.
|
||
|
||
**`_build_heatmap_right` row numbers are manual.**
|
||
Grid rows are numbered 0–12 explicitly. Inserting a new panel requires
|
||
renumbering all subsequent `grid(row=N)` calls. Miss one and widgets overlap
|
||
silently or disappear. Always audit all row numbers in the method after any
|
||
insertion.
|
||
|
||
**`_ap_row_widgets` must stay in sync with visual rows.**
|
||
`_ap_select_all` and `_ap_deselect_all` iterate `_ap_row_widgets`. If
|
||
`_populate_ap_table` ever returns early or skips a row without appending to
|
||
`_ap_row_widgets`, the checkbox state will be wrong for all subsequent rows.
|
||
|
||
**`_known_bssids_ordered()` determines AP table row order.**
|
||
This method defines which BSSIDs appear and in what order. `_ap_row_widgets[i]`
|
||
corresponds to `_known_bssids_ordered()[i]`. If the ordering changes between
|
||
the time rows are built and the time a checkbox callback fires, the wrong BSSID
|
||
gets toggled. The ordering is stable (current scan order → stale by last-seen
|
||
descending) but must remain deterministic.
|
||
|
||
**`scan_averaged` delay × samples = wall-clock time.**
|
||
Default is 10 × 0.1s ≈ 1.1s. The AP tab auto-scan also uses this. If the
|
||
interval is set to 3 seconds (the minimum) and scanning takes 1.1 seconds,
|
||
the app is scanning 37% of the time. Increasing samples or delay without
|
||
considering the auto-scan interval can make the UI feel unresponsive.
|
||
|
||
**`fig.subplots_adjust(right=0.88)` is called only at figure creation.**
|
||
The figure is created in `_build_heatmap_tab`. If the figure is ever recreated
|
||
(e.g. to change figure size), `subplots_adjust` must be called again or the
|
||
colorbar will overlap the main plot.
|
||
|
||
**The `DOT11_SSID` ctypes struct layout is exact.**
|
||
`uSSIDLength` is a 4-byte `ULONG`. `ucSSID` is 32 bytes. Total 36 bytes. If
|
||
this struct is ever modified or the field types changed, SSIDs will silently
|
||
truncate or corrupt. The original bug (treating the struct as `c_ubyte * 33`)
|
||
produced SSIDs truncated to 6 characters. Test any struct change against a
|
||
network with a known SSID length > 6 characters.
|
||
|
||
**The `WLAN_BSS_ENTRY` ctypes struct layout is exact (and IE-critical).**
|
||
`bInRegDomain` is `BOOLEAN` (1 byte) and `wlanRateSet` is `WLAN_RATE_SET`
|
||
(256 bytes). Getting either wrong shifts `ulIeOffset`/`ulIeSize` and makes all
|
||
beacon-IE parsing (mode, security, width) read garbage — and a raw read at a
|
||
bad offset crashes the app. Invariants: `ctypes.sizeof(WLAN_BSS_ENTRY) == 360`,
|
||
`ulIeOffset` at offset 352, `ulIeSize` at 356, `lRssi` at 56,
|
||
`ulChCenterFrequency` at 92. Verify with `.offset` after any change (see
|
||
Decision #18). Note RSSI/freq/phy precede the IE fields, so a broken layout
|
||
still scans fine — only IE-derived columns break, which masks the bug.
|
||
|
||
**Beacon-IE parsers assume byte-exact element offsets.**
|
||
`_mode_from_ies`, `_security_from_ies`, `_width_from_ies` index into raw IE
|
||
bytes at fixed offsets derived from the 802.11 / Linux `ieee80211.h` layouts
|
||
(e.g. RSN pairwise count at body offset 6; EHT Operation control at body[6];
|
||
HE `he_oper_params` is a 4-byte LE field with VHT=0x4000 / 6GHz=0x20000 flags).
|
||
All accesses are length-guarded so bad data yields "" not a crash, but a wrong
|
||
offset silently mislabels. The HT/VHT/HE width offsets have been validated
|
||
byte-for-byte against the Linux kernel `ieee80211-ht.h` / `-vht.h` / `-he.h`
|
||
definitions (HE matches `ieee80211_he_6ghz_oper()` exactly); the **EHT** path
|
||
is the one still unverified against source. When touching these, diff against
|
||
the kernel `ieee80211_*_operation` structs and test on a live network of the
|
||
relevant generation.
|
||
|
||
---
|
||
|
||
|
||
|
||
There is no automated test suite. Testing is done by:
|
||
1. Running the app and manually scanning
|
||
2. Exporting PNG and comparing measurement dots against known AP locations
|
||
3. Comparing readings against NetSpot (reference tool) at the same locations
|
||
4. Checking session JSON files for correct data structure after save/load cycles
|
||
|
||
---
|
||
|
||
## Build & Distribution
|
||
|
||
**Development:**
|
||
```bash
|
||
pip install -r requirements.txt
|
||
python main.py
|
||
```
|
||
|
||
**Windows binary:**
|
||
```bash
|
||
pyinstaller --onefile --windowed \
|
||
--icon "extras/pyfi-logo.ico" \
|
||
--add-data "extras/pyfi-mini.png;extras" \
|
||
--add-data "extras/pyfi-logo.ico;extras" \
|
||
main.py
|
||
```
|
||
|
||
All asset paths inside the binary use `_resource_path()` which resolves
|
||
`sys._MEIPASS` at runtime.
|
||
|
||
---
|
||
|
||
## Session Workflow (for context in future sessions)
|
||
|
||
1. User scans on **Access Points** tab — discovers BSSIDs, sees SSID/channel/
|
||
security/vendor/mode/level/last-seen/max/min/avg per network. Checkboxes
|
||
select which BSSIDs to include in the heatmap. Auto-scan runs on a
|
||
user-configurable interval (default 10s, min 3s).
|
||
|
||
2. User switches to **Heatmap** tab — active BSSIDs shown in the right panel.
|
||
Single BSSID = individual radio map. Multiple BSSIDs = averaged coverage map.
|
||
|
||
3. User optionally pins AP physical locations with **◆ Place APs** — click a
|
||
network row to arm it, click its location on the canvas to drop the pin.
|
||
Pins are saved with the session and inject anchor points into interpolation.
|
||
|
||
4. User walks the space clicking **▶ Scan & Place** at each location. After 4+
|
||
valid measurements the heatmap renders automatically with Ekahau-style
|
||
signal bubbles.
|
||
|
||
5. Black `?` dots mark locations where the selected BSSID(s) were completely
|
||
out of range. These are important dead-zone indicators.
|
||
|
||
6. Sessions save as `.json` and restore all measurements, AP positions, and
|
||
floorplan path.
|