diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..557c046 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,517 @@ +# 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. + +### `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"). + +### Decision #7 — iw instead of nmcli on Linux + +`nmcli` reads from NetworkManager's scan cache with its own smoothing. +`iw dev 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. + +--- + +## 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. + +--- + +## 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 | +| `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. + +--- + + + +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.