31 Commits
Author SHA1 Message Date
iamdoubz 009ea8c816 Bump latest release version 2026-05-04 12:02:03 -05:00
iamdoubz 79f864c4aa Add additional screenshot 2026-05-04 12:01:45 -05:00
iamdoubz b25cc5f29d Add single bssid w/ap image 2026-05-04 12:01:12 -05:00
iamdoubz 0001a8a702 Merge pull request 'Remove dup ap marker and actually render the legend' (#17) from legend_fix2 into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/17
2026-05-04 11:31:22 -05:00
iamdoubz 621978d1d6 Remove dup ap marker and actually render the legend 2026-05-04 11:27:32 -05:00
iamdoubz bfdf025c37 Add a few more images 2026-05-04 11:21:06 -05:00
iamdoubz 329e81bf86 Bump latest release version 2026-05-04 09:14:06 -05:00
iamdoubz 19b6447eaf Fix legend alpha display issue 2026-05-04 09:13:30 -05:00
iamdoubz 7befa142a6 Change display text and relative logos in GUI 2026-05-04 08:38:43 -05:00
iamdoubz 97c2c4d3bb Merge pull request 'Use repo logos instead of generic ones' (#16) from bundle_logo_exe into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/16
2026-05-04 08:27:31 -05:00
iamdoubz 1086a98e7b Use repo logos instead of generic ones 2026-05-04 08:23:43 -05:00
iamdoubz a76a7f221d Merge pull request 'Change program render title and logos' (#15) from program_logo_change into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/15
2026-05-04 04:32:03 -05:00
iamdoubz 3291fa0867 Change program render title and logos 2026-05-04 04:31:05 -05:00
iamdoubz 62c1b48093 Add verbage for new features 2026-05-04 03:45:47 -05:00
iamdoubz 95f8d1e2d2 Bump latest release version 2026-05-04 03:44:10 -05:00
iamdoubz 1833e412c7 Merge pull request '[Feature] Add ability to add AP to heatmap' (#14) from add_ap_positions into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/14
2026-05-04 03:40:50 -05:00
iamdoubz eccdbdcd78 Show AP positions on heatmap 2026-05-04 03:39:45 -05:00
iamdoubz 5c98e8e4a6 Add saving positions of AP to session file 2026-05-04 03:39:13 -05:00
iamdoubz 80c5781daa Add AP positioning to heatmap page 2026-05-04 03:38:18 -05:00
iamdoubz e48aa38b70 Bump latest release version 2026-05-04 03:24:28 -05:00
iamdoubz 10fde8278e Merge pull request 'Change logos' (#13) from change_logos into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/13
2026-05-04 03:22:05 -05:00
iamdoubz 060aa781b3 Change logos 2026-05-04 03:21:02 -05:00
iamdoubz f1e0a1838e Merge pull request 'Make heatmap more like ekahau' (#12) from visual_heatmap_filter into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/12
2026-05-04 02:42:51 -05:00
iamdoubz 24efe2802c Make heatmap more like ekahau 2026-05-04 02:41:34 -05:00
iamdoubz 34213ba4ee Merge pull request 'Fix SSID truncated' (#11) from fix_ssid_truncate into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/11
2026-05-04 02:33:58 -05:00
iamdoubz 988c40025e Display correct ssid 2026-05-04 02:30:48 -05:00
iamdoubz d4bdb340c8 Fix wrong windows sdk struct layout 2026-05-04 02:30:26 -05:00
iamdoubz f15ecc36e4 Change example export image 2026-05-01 16:55:22 -05:00
iamdoubz c9f72b566c Bump latest release version 2026-05-01 16:47:44 -05:00
iamdoubz cf0180b3b7 Merge pull request '[BUG] After multiple scans and plots, heatmap becomes 3% smaller each scan (fixed)' (#10) from heatmap_shrink_fix into main
Reviewed-on: http://git.dou.bet/iamdoubz/pyfi-hmg/pulls/10
2026-05-01 16:44:58 -05:00
iamdoubz afbc6f77e9 After multiple scans and plots, heatmap becomes 3% smaller each scan (fixed) 2026-05-01 16:43:30 -05:00
12 changed files with 717 additions and 177 deletions

No files matched your search

+102 -35
View File
@@ -59,17 +59,18 @@ The application has two tabs and a persistent left sidebar.
<img src="extras/page-accesspoints.png" alt="An image of the wifi heatmap generator page 1 titled Access Points that shows discovered SSID and BSSID network information">
</p>
The first tab you see on launch. Shows a scrollable table of every access point
ever discovered during the session — including those that have gone out of range,
which remain in the list permanently and are shown dimmed with an "out of range"
indicator in the Level column.
The first tab you see on launch. Shows a scrollable table (horizontal and
vertical) of every access point ever discovered during the session — including
those that have gone out of range, which remain in the list permanently and are
shown dimmed with an "out of range" indicator in the Level column. Column
headers are pixel-exact aligned to their data columns.
**Table columns:**
| Column | Description |
|---|---|
| ✓ | Checkbox to include this BSSID in heatmap rendering |
| SSID | Network name |
| SSID | Network name (full name, never truncated) |
| BSSID | Hardware MAC address — unique per physical radio |
| Ch | 802.11 channel number |
| Frequency | Centre frequency in MHz |
@@ -84,18 +85,19 @@ indicator in the Level column.
| Min | Weakest signal ever recorded |
| Avg | Running average of all valid readings |
The Max, Min, and Avg columns accumulate across the entire session lifetime and
are cleared only when starting a new session. Max is tinted green, Min red, and
Avg is color-coded dynamically by signal quality.
**Toolbar controls:**
- **🔄 Refresh Scan** — Trigger a manual scan immediately.
- **☑ Select All / ☐ Deselect All** — Check or uncheck all rows for heatmap use.
- **Auto-scan** — Enable automatic periodic scanning. The interval is
user-configurable via a spinbox (minimum 3 seconds, default 10 seconds,
maximum 300 seconds). A live countdown shows time until the next scan.
maximum 300 seconds). A live countdown label shows time until the next scan.
While auto-scan is active the manual Refresh button is disabled to prevent
scan conflicts.
The table scrolls both horizontally and vertically. Column headers are
pixel-exact aligned to their data columns.
scan conflicts. Changing the interval mid-countdown restarts the timer.
### Tab 2 — Heatmap
@@ -103,7 +105,14 @@ pixel-exact aligned to their data columns.
<img src="extras/page-heatmap.png" alt="An image of the wifi heatmap generator page 2 titled Heatmap showing a datagrid of measurements and active networks">
</p>
The heatmap canvas with measurement tools.
The heatmap canvas with measurement and AP placement tools.
**Toolbar controls:**
- **▶ Scan & Place** — Scan WiFi and enter placement mode; click your location on the canvas.
- **↩ Undo** — Remove the most recently recorded measurement point.
- **◆ Place APs** — Toggle AP placement mode (see AP Positions below).
- **✕ Clear AP Pins** — Remove all AP position pins from the session.
**Active Networks panel (right side):**
@@ -119,27 +128,51 @@ AP tab checkboxes are the sole selector.
A mode label shows either "Mode: single BSSID" or "Mode: averaging N BSSIDs".
**AP Positions panel (right side):**
Shows one row per active BSSID. Each row displays:
- A status indicator: ○ (not pinned), ◆ (pinned), or ▶ (armed for placement)
- The SSID and current pin coordinates (if placed)
- An ✕ remove button when pinned
To place an AP:
1. Click **◆ Place APs** in the toolbar to enter placement mode.
2. Click a network row in the AP Positions panel to arm it (▶ indicator appears).
3. Click the AP's physical location on the canvas — a ◆ diamond marker appears.
4. Repeat for each AP. Right-click an existing ◆ marker to remove it.
Placing APs is optional but improves heatmap accuracy — see *AP Positioning* below.
**Measurements panel (right side, full height):**
A scrollable list of every recorded measurement point showing its canvas
coordinates and how many APs were visible at that location. Individual
measurements can be deleted by selecting them and clicking 🗑 Delete Selected.
The Undo button removes the most recent point.
**Heatmap rendering:**
**Heatmap rendering (Ekahau-style):**
- The colormap runs **red** (strongest, ≥ -30 dBm) → orange → yellow → green →
teal → blue → **violet** (weakest, ≤ -90 dBm), matching professional site
survey tools. Strong signal zones are warm colors; weak zones are cool.
- The alpha channel is derived per-pixel from signal strength — strong zones are
opaque and weak/absent zones fade to transparent, revealing the floorplan
beneath. This produces the characteristic "bubble" zone appearance.
- A Gaussian blur is applied to zone edges so overlapping coverage areas blend
smoothly rather than showing hard triangulation boundaries.
- The heatmap is not drawn until at least **4 measurement points** are collected
for the selected BSSID(s). Until then a progress indicator shows how many
points have been collected and how many more are needed.
- Colored dots mark each valid measurement point, labeled with the dBm value.
for the selected BSSID(s). Until then a progress indicator shows how many more
are needed.
- **Colored dots** (circles) mark each valid measurement point, labeled with the dBm value.
- **Black dots with a `?`** mark measurement points where none of the selected
BSSIDs were visible — the user was there and scanned, but that radio had no
coverage at that location.
- The colorbar runs from black (no signal / not found) at the bottom through
navy → blue → cyan → green → yellow → orange → red (excellent) at the top.
A "No signal" label appears below the scale.
- **◆ Diamond markers** with WiFi arc icons mark AP physical positions when
pinned. These are visually distinct from measurement dots and show the SSID
label beneath the icon.
- The colorbar runs from black (no signal) at the bottom to red (excellent) at
the top. A "No signal" label appears below the scale.
- When no floorplan is loaded, a subtle coordinate grid is drawn instead, and
a warning note appears in the heatmap subtitle.
a warning note appears in the heatmap subtitle and export.
---
@@ -153,17 +186,34 @@ The Undo button removes the most recent point.
real spatial context and produces a significantly more accurate heatmap.
4. Switch to the **Heatmap** tab. The Active Networks panel shows your selected
BSSIDs and the current mode (single or averaged).
5. Walk to a location in your space and click **▶ Scan & Place**. The app
5. *(Optional)* Pin your AP locations using **◆ Place APs** — see *AP Positioning*.
6. Walk to a location in your space and click **▶ Scan & Place**. The app
scans WiFi (10 samples, 100 ms apart, median reported) and enters placement
mode. Click your current position on the canvas.
6. Repeat from step 5. Aim for **at least 15–20 measurement points** for a
7. Repeat from step 6. Aim for **at least 15–20 measurement points** for a
good interpolation. Prioritize:
- Locations very close to each router (expect -30 to -45 dBm)
- Far corners and edges of the space (expect -65 to -80 dBm)
- Both sides of walls and doorways
- Any spot you suspect has poor coverage
7. The heatmap auto-updates after each new point once the 4-point minimum is met.
8. Use **Export PNG** to save the result, or **Save Session** to continue later.
8. The heatmap auto-updates after each new point once the 4-point minimum is met.
9. Use **Export PNG** to save the result, or **Save Session** to continue later.
### AP Positioning
When you pin an AP's physical location on the canvas, the renderer injects a
synthetic anchor point at that position into the interpolation. The anchor value
is the strongest real measurement seen for that BSSID plus 5 dBm (capped at
-25 dBm), representing the expected near-field signal directly at the
transmitter.
Without an anchor, the interpolator estimates the signal peak from surrounding
measurement points, which can place it in the wrong location — especially in a
mesh system where measurement density may not be uniform. With an anchor, the
heatmap peak is correctly located at the physical AP, and coverage zones radiate
outward from the right origin.
AP positions are saved in the session file and restored on load.
### Mapping a mesh network accurately
@@ -178,6 +228,9 @@ multiple radios broadcast the same SSID:
checked, the multi-BSSID averaging mode will produce a combined coverage map.
- For the most accurate single-radio map, consider temporarily disabling the
other nodes in your mesh system's admin panel during the session.
- Pinning each node's physical location with **◆ Place APs** is especially
useful for mesh systems — it anchors each radio's peak independently so the
averaged multi-BSSID map correctly reflects all three coverage zones.
---
@@ -206,6 +259,10 @@ This can reveal 8–15 dBm of real variation that `netsh` completely hides.
`WlanScan()` is also called first to request a fresh radio sweep rather than
reading the OS scan cache (which can be 30–60 seconds stale).
The `DOT11_SSID` struct is read using the correct SDK layout (`uSSIDLength` as
a 4-byte ULONG + `ucSSID[32]`), ensuring SSIDs are never truncated regardless
of length.
**Linux — `iw` vs `nmcli`:**
`nmcli` reads from NetworkManager's internal scan cache and applies its own
@@ -260,7 +317,9 @@ per BSSID across the entire session.
## Interpolation
Signal values between measurement points are interpolated using scipy:
Signal values between measurement points are interpolated using scipy. When AP
positions are pinned, synthetic anchor points are injected at the transmitter
locations before interpolation runs.
| Points collected | Method used |
|---|---|
@@ -281,8 +340,8 @@ entire canvas is always covered.
|---|---|---|
| -30 to -50 | Excellent | Red → Orange → Yellow |
| -50 to -65 | Good | Yellow → Green |
| -65 to -75 | Fair | Green → Cyan |
| -75 to -90 | Poor | Cyan → Blue → Navy |
| -65 to -75 | Fair | Green → Teal |
| -75 to -90 | Poor | Teal → Blue → Violet |
| Not found | No signal | Black dot (●) on map |
---
@@ -290,15 +349,17 @@ entire canvas is always covered.
## Session Files
Sessions are saved as `.json` files containing all measurement points, signal
readings for every visible BSSID at each point, SSID mappings, the floorplan
path, and canvas dimensions. Sessions can be loaded at startup:
readings for every visible BSSID at each point, SSID mappings, AP position
pins, the floorplan path, and canvas dimensions. Sessions can be loaded at startup:
```bash
python main.py --session my_office.json
```
Measurements can be deleted individually from the Heatmap tab. The session is
not auto-saved — use **💾 Save Session** or **💾 Save As…** from the sidebar.
Measurements can be deleted individually from the Heatmap tab. AP pins can be
removed individually from the AP Positions panel or all at once via
**✕ Clear AP Pins**. The session is not auto-saved — use **💾 Save Session**
or **💾 Save As…** from the sidebar.
---
@@ -318,17 +379,23 @@ not auto-saved — use **💾 Save Session** or **💾 Save As…** from the sid
| File | Purpose |
|---|---|
| `main.py` | Tkinter GUI — two-tab layout (Access Points + Heatmap), sidebar, auto-scan engine, AP stats tracking |
| `scanner.py` | Cross-platform WiFi scanning with `wlanapi` / `iw` / `nmcli` / `airport` backends, median averaging |
| `main.py` | Tkinter GUI — two-tab layout (Access Points + Heatmap), sidebar, auto-scan engine, AP stats tracking, AP placement drag-and-drop |
| `scanner.py` | Cross-platform WiFi scanning with `wlanapi` / `iw` / `nmcli` / `airport` backends, median averaging, correct DOT11_SSID struct |
| `interpolator.py` | Spatial interpolation — auto-selects RBF, cubic, or linear based on point count |
| `renderer.py` | Matplotlib heatmap rendering — colorbar, measurement dots, missing-signal black dots |
| `data.py` | Session model — measurements, multi-BSSID averaging, missing-point detection, JSON persistence |
| `renderer.py` | Ekahau-style RGBA heatmap rendering — signal-driven alpha, Gaussian zone blending, AP diamond markers, colorbar |
| `data.py` | Session model — measurements, multi-BSSID averaging, missing-point detection, AP position anchoring, JSON persistence |
| `requirements.txt` | Python dependencies (`numpy`, `scipy`, `matplotlib`, `Pillow`) |
---
## 🖼️ Screenshots 🖼️
### Single BSSID
<p align="center">
<img src="extras/example_export.png" alt="An image of the wifi heatmap generator heatmap export">
</p>
### Single BSSID w/AP
<p align="center">
<img src="extras/example_export_with_ap.png" alt="An image of the wifi heatmap generator heatmap export with access point">
</p>
+35
View File
@@ -30,6 +30,10 @@ class Session:
canvas_width: int = 800
canvas_height: int = 600
measurements: list[Measurement] = field(default_factory=list)
# Physical positions of access points on the canvas, keyed by BSSID.
# Optional — when set, the renderer uses these as anchor points to pin the
# interpolation peak to the real transmitter location.
ap_positions: dict[str, tuple[float, float]] = field(default_factory=dict)
created_at: str = ""
updated_at: str = ""
@@ -106,6 +110,32 @@ class Session:
missing.append((m.x, m.y))
return missing
def get_anchor_points(self, bssids: list[str]) -> tuple[list, list]:
"""
Return synthetic (x, y) anchor points and estimated dBm values for any
BSSID in `bssids` that has a known physical position in ap_positions.
The anchor value is the strongest real measurement seen for that BSSID
plus 5 dBm (capped at -25 dBm), representing the expected near-field
signal directly at the transmitter. These points are injected into the
interpolation so the heatmap peak is correctly anchored to the AP's
physical location rather than estimated from surrounding measurements.
"""
points, values = [], []
for bssid in bssids:
if bssid not in self.ap_positions:
continue
pos = self.ap_positions[bssid]
# Find the strongest real reading for this BSSID
real_pts, real_vals = self.get_points_and_values(bssid)
if real_vals:
anchor_dbm = min(-25, max(real_vals) + 5)
else:
anchor_dbm = -35 # reasonable default when no measurements exist yet
points.append(pos)
values.append(float(anchor_dbm))
return points, values
def save(self, path: str):
"""Save session to JSON file."""
data = {
@@ -115,6 +145,8 @@ class Session:
"canvas_height": self.canvas_height,
"created_at": self.created_at,
"updated_at": datetime.now().isoformat(),
# Serialize ap_positions as {bssid: [x, y]} for JSON compatibility
"ap_positions": {b: list(pos) for b, pos in self.ap_positions.items()},
"measurements": [
{
"x": m.x,
@@ -143,6 +175,9 @@ class Session:
created_at=data.get("created_at", ""),
updated_at=data.get("updated_at", "")
)
# Restore AP positions — stored as {bssid: [x, y]}, convert to tuples
for bssid, pos in data.get("ap_positions", {}).items():
session.ap_positions[bssid] = (float(pos[0]), float(pos[1]))
for m in data.get("measurements", []):
session.measurements.append(Measurement(
x=m["x"],
Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 KiB

After

Width:  |  Height:  |  Size: 334 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 458 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 455 KiB

After

Width:  |  Height:  |  Size: 929 KiB

+4 -4
View File
@@ -7,8 +7,8 @@ VSVersionInfo(
ffi=FixedFileInfo(
# filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4)
# Set not needed items to zero 0. Must always contain 4 elements.
filevers=(2026,5,0,0),
prodvers=(2026,5,0,0),
filevers=(2026,5,5,0),
prodvers=(2026,5,5,0),
# Contains a bitmask that specifies the valid bits 'flags'r
mask=0x3f,
# Contains a bitmask that specifies the Boolean attributes of the file.
@@ -32,12 +32,12 @@ VSVersionInfo(
u'040904B0',
[StringStruct(u'CompanyName', u''),
StringStruct(u'FileDescription', u'pyFi: WiFi Heatmap Generator'),
StringStruct(u'FileVersion', u'2026.5.0.0'),
StringStruct(u'FileVersion', u'2026.5.5.0'),
StringStruct(u'InternalName', u'pyFi'),
StringStruct(u'LegalCopyright', u'© iamdoubz'),
StringStruct(u'OriginalFilename', u'pyFi.exe'),
StringStruct(u'ProductName', u'pyFi'),
StringStruct(u'ProductVersion', u'2026.5.0.0')])
StringStruct(u'ProductVersion', u'2026.5.5.0')])
]),
VarFileInfo([VarStruct(u'Translation', [1033, 1200])])
]
+307 -29
View File
@@ -1,5 +1,5 @@
"""
main.py — WiFi Heatmap Generator GUI
main.py — pyFi WiFi Heatmap Generator GUI
Cross-platform tkinter application for collecting and visualizing WiFi signal data.
Usage:
@@ -14,6 +14,7 @@ import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import os
import sys
import argparse
import time
from dataclasses import dataclass, field
@@ -30,6 +31,19 @@ from data import Session, Measurement
from renderer import render_heatmap, SIGNAL_CMAP
def _resource_path(relative_path: str) -> str:
"""
Resolve a path to a bundled resource at runtime.
PyInstaller extracts bundled files to a temporary folder at runtime and
sets sys._MEIPASS to that folder's path. When running from source,
the directory containing main.py is used instead — so both the compiled
binary and plain `python main.py` resolve assets correctly.
"""
base = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base, relative_path)
# ── Palette ───────────────────────────────────────────────────────────────────
BG = "#0d0d1a"
BG2 = "#131325"
@@ -109,7 +123,7 @@ AP_COLUMNS = [
class WiFiHeatmapApp:
def __init__(self, root: tk.Tk, initial_session: Optional[str] = None):
self.root = root
self.root.title("WiFi Heatmap Generator")
self.root.title("pyFi")
self.root.configure(bg=BG)
self.root.minsize(1200, 720)
@@ -127,6 +141,11 @@ class WiFiHeatmapApp:
self._auto_scan_job: Optional[str] = None # root.after() handle
self._auto_scan_enabled: bool = False
# AP position drag state
self._ap_drag_mode: bool = False # True when "Place APs" is active
self._dragging_bssid: Optional[str] = None
self._drag_ghost = None # matplotlib artist for drag preview
self._build_ui()
self._apply_styles()
@@ -178,9 +197,21 @@ class WiFiHeatmapApp:
def _build_sidebar(self):
f = self.sidebar
# Logo image — load pyfi-mini.png, fall back to emoji if file is missing
try:
_logo_img = tk.PhotoImage(file=_resource_path(
os.path.join("extras", "pyfi-mini.png")))
# Use a single divisor for both axes to preserve aspect ratio.
# Target ~64px on the longest side.
_divisor = max(1, max(_logo_img.width(), _logo_img.height()) // 92)
_logo_img = _logo_img.subsample(_divisor, _divisor)
tk.Label(f, image=_logo_img, bg=BG2).pack(pady=(20, 4))
f._logo_img_ref = _logo_img # prevent garbage collection
except Exception:
tk.Label(f, text="📡", font=("Segoe UI Emoji", 28), bg=BG2, fg=ACCENT).pack(pady=(20, 4))
tk.Label(f, text="WiFi Heatmap", font=("Georgia", 13, "bold"), bg=BG2, fg=TEXT).pack()
tk.Label(f, text="Generator", font=("Georgia", 11), bg=BG2, fg=TEXT_DIM).pack(pady=(0, 16))
tk.Label(f, text="WiFi", font=("Georgia", 13, "bold"), bg=BG2, fg=TEXT).pack()
tk.Label(f, text="Heatmap Generator", font=("Georgia", 10), bg=BG2, fg=TEXT_DIM).pack(pady=(0, 16))
ttk.Separator(f, orient="horizontal").pack(fill="x", padx=12, pady=4)
@@ -460,7 +491,7 @@ class WiFiHeatmapApp:
text_fg = TEXT if is_live else dim_fg
dim2 = TEXT_DIM if is_live else dim_fg
_cell(ssid[:20], 160, fg=text_fg, bold=True)
_cell(ssid, 160, fg=text_fg, bold=True)
_cell(bssid, 145, fg=dim2)
_cell(channel, 38, fg=text_fg)
_cell(freq, 90, fg=text_fg)
@@ -597,6 +628,20 @@ class WiFiHeatmapApp:
command=self._undo_last)
self.undo_btn.grid(row=0, column=2, padx=4, pady=8)
# Place APs toggle — activates drag-and-drop mode for positioning APs
self.place_ap_btn = tk.Button(toolbar, text="◆ Place APs",
font=("Courier", 9), bg=BG2, fg=ACCENT2,
relief="flat", padx=10, pady=6, cursor="hand2",
activebackground=BG3,
command=self._toggle_ap_drag_mode)
self.place_ap_btn.grid(row=0, column=3, padx=4, pady=8)
self.clear_ap_pos_btn = tk.Button(toolbar, text="✕ Clear AP Pins",
font=("Courier", 9), bg=BG2, fg=TEXT_DIM,
relief="flat", padx=10, pady=6, cursor="hand2",
command=self._clear_ap_positions)
self.clear_ap_pos_btn.grid(row=0, column=4, padx=4, pady=8)
self.status_label = tk.Label(toolbar, text="Ready",
font=("Courier", 9), bg=BG3, fg=TEXT_DIM)
self.status_label.grid(row=0, column=99, padx=12, sticky="e")
@@ -610,6 +655,8 @@ class WiFiHeatmapApp:
self.canvas_widget = FigureCanvasTkAgg(self.fig, master=f)
self.canvas_widget.get_tk_widget().grid(row=1, column=0, sticky="nsew")
self.canvas_widget.mpl_connect("button_press_event", self._on_canvas_click)
self.canvas_widget.mpl_connect("motion_notify_event", self._on_canvas_motion)
self.canvas_widget.mpl_connect("button_release_event", self._on_canvas_release)
f.columnconfigure(0, weight=1)
# Right panel — AP selector + measurements (full window height)
@@ -631,7 +678,8 @@ class WiFiHeatmapApp:
tk.Label(f,
text="Check networks on the Access\nPoints tab to include them here.\n"
"1 selected = single BSSID mode.\n"
"2+ selected = averaged mode.",
"2+ selected = averaged mode.\n"
"Enable ◆ Place APs then drag\na network here onto the map.",
font=("Courier", 7), bg=BG2, fg=TEXT_DIM, justify="left", wraplength=230
).grid(row=1, column=0, sticky="w", padx=14, pady=(0, 6))
@@ -663,19 +711,36 @@ class WiFiHeatmapApp:
ttk.Separator(f, orient="horizontal").grid(row=4, column=0, sticky="ew", padx=8, pady=6)
# ── AP Positions panel ─────────────────────────────────────────────────
tk.Label(f, text="AP POSITIONS ◆", font=("Courier", 8, "bold"),
bg=BG2, fg=TEXT_DIM).grid(row=5, column=0, sticky="w", padx=14, pady=(4, 2))
tk.Label(f,
text="Click ◆ Place APs, then click a\nnetwork below to arm it, then\n"
"click its location on the map.\nRight-click a ◆ marker to remove.",
font=("Courier", 7), bg=BG2, fg=TEXT_DIM, justify="left", wraplength=230
).grid(row=6, column=0, sticky="w", padx=14, pady=(0, 4))
# Frame that holds one row per active BSSID
self.ap_pos_frame = tk.Frame(f, bg=BG2)
self.ap_pos_frame.grid(row=7, column=0, sticky="ew", padx=8, pady=(0, 4))
self.ap_pos_frame.columnconfigure(0, weight=1)
ttk.Separator(f, orient="horizontal").grid(row=8, column=0, sticky="ew", padx=8, pady=6)
# ── Measurements list (full remaining height) ──────────────────────
tk.Label(f, text="MEASUREMENTS", font=("Courier", 8, "bold"),
bg=BG2, fg=TEXT_DIM).grid(row=5, column=0, sticky="w", padx=14, pady=(4, 2))
bg=BG2, fg=TEXT_DIM).grid(row=9, column=0, sticky="w", padx=14, pady=(4, 2))
self.meas_count_label = tk.Label(f, text="0 points collected",
font=("Courier", 8), bg=BG2, fg=ACCENT2)
self.meas_count_label.grid(row=6, column=0, sticky="w", padx=14, pady=(0, 4))
self.meas_count_label.grid(row=10, column=0, sticky="w", padx=14, pady=(0, 4))
meas_frame = tk.Frame(f, bg=BG2)
meas_frame.grid(row=7, column=0, sticky="nsew", padx=8, pady=(0, 4))
meas_frame.grid(row=11, column=0, sticky="nsew", padx=8, pady=(0, 4))
meas_frame.columnconfigure(0, weight=1)
meas_frame.rowconfigure(0, weight=1)
f.rowconfigure(7, weight=1)
f.rowconfigure(11, weight=1)
meas_scroll = ttk.Scrollbar(meas_frame, orient="vertical")
meas_scroll.grid(row=0, column=1, sticky="ns")
@@ -694,7 +759,7 @@ class WiFiHeatmapApp:
font=("Courier", 8), bg=BG3, fg=DANGER,
relief="flat", padx=8, pady=4, cursor="hand2",
command=self._delete_measurement)
self.del_meas_btn.grid(row=8, column=0, sticky="w", padx=12, pady=(0, 10))
self.del_meas_btn.grid(row=12, column=0, sticky="w", padx=12, pady=(0, 10))
# ── Active BSSID display on Heatmap tab ───────────────────────────────────
@@ -723,7 +788,89 @@ class WiFiHeatmapApp:
self._redraw()
# ── Scanning (AP Tab) ─────────────────────────────────────────────────────
def _update_ap_positions_panel(self, highlight: Optional[str] = None):
"""
Rebuild the AP Positions panel rows — one row per active BSSID.
Each row shows: armed indicator | SSID | pinned coords | remove button.
Clicking the row arms that BSSID for placement.
"""
for w in self.ap_pos_frame.winfo_children():
w.destroy()
bssids = self.selected_bssids_for_heatmap
if not bssids:
tk.Label(self.ap_pos_frame, text=" No networks selected",
font=("Courier", 7), bg=BG2, fg=TEXT_DIM
).grid(row=0, column=0, sticky="w", padx=8, pady=2)
return
for i, bssid in enumerate(bssids):
ssid = self.session.get_ssid(bssid)
pos = self.session.ap_positions.get(bssid)
is_armed = (bssid == self._dragging_bssid and self._ap_drag_mode)
is_pinned = pos is not None
row_bg = "#1a2a1a" if is_armed else (BG3 if is_pinned else BG2)
row = tk.Frame(self.ap_pos_frame, bg=row_bg,
highlightthickness=1,
highlightbackground=ACCENT2 if is_armed else BORDER)
row.grid(row=i, column=0, sticky="ew", pady=1)
row.columnconfigure(1, weight=1)
# Armed indicator
armed_lbl = tk.Label(row,
text="▶" if is_armed else ("◆" if is_pinned else "○"),
font=("Courier", 8, "bold"), bg=row_bg,
fg=ACCENT2 if is_armed else (SUCCESS if is_pinned else TEXT_DIM),
padx=4)
armed_lbl.grid(row=0, column=0, sticky="w")
# SSID + coords
coord_str = f" ({int(pos[0])}, {int(pos[1])})" if pos else " not pinned"
name_lbl = tk.Label(row,
text=f"{ssid[:14]}{coord_str}",
font=("Courier", 7), bg=row_bg,
fg=TEXT if is_pinned else TEXT_DIM,
anchor="w", padx=2)
name_lbl.grid(row=0, column=1, sticky="ew")
# Remove button (only shown when pinned)
if is_pinned:
rm_btn = tk.Button(row, text="✕",
font=("Courier", 7), bg=row_bg, fg=DANGER,
relief="flat", padx=2, cursor="hand2",
command=lambda b=bssid: self._remove_ap_pin(b))
rm_btn.grid(row=0, column=2, sticky="e", padx=2)
# Click anywhere on the row to arm this BSSID
for widget in (row, armed_lbl, name_lbl):
widget.bind("<Button-1>",
lambda e, b=bssid: self._select_ap_for_pin(b))
def _select_ap_for_pin(self, bssid: str):
"""Arm a BSSID for placement — next canvas click drops its pin there."""
self._dragging_bssid = bssid
if not self._ap_drag_mode:
self._ap_drag_mode = True
self.place_ap_btn.config(bg=ACCENT2, fg='black',
text="◆ Placing APs (click to cancel)")
ssid = self.session.get_ssid(bssid)
self._set_status(
f"Click the location of {ssid} on the map. "
"Right-click an existing ◆ to remove it.")
self.canvas_widget.get_tk_widget().config(cursor="crosshair")
self._update_ap_positions_panel(highlight=bssid)
def _remove_ap_pin(self, bssid: str):
"""Remove a single AP pin."""
if bssid in self.session.ap_positions:
self.session.ap_positions.pop(bssid)
if self._dragging_bssid == bssid:
self._dragging_bssid = None
ssid = self.session.get_ssid(bssid)
self._set_status(f"◆ Removed pin for {ssid}")
self._update_ap_positions_panel()
self._redraw()
def _refresh_scan(self):
if self.scanning: return
@@ -866,12 +1013,90 @@ class WiFiHeatmapApp:
self._set_status("✓ Scan done — click your position on the map")
self.canvas_widget.get_tk_widget().config(cursor="crosshair")
def _undo_last(self):
if not self.session.measurements: return
self.session.remove_measurement(len(self.session.measurements) - 1)
self._set_status("Last measurement removed")
self._refresh_everything()
def _delete_measurement(self):
sel = self.meas_listbox.curselection()
if not sel: return
idx = sel[0]
self.session.remove_measurement(idx)
self._refresh_everything()
self._set_status(f"Measurement {idx + 1} deleted")
# ── AP position drag-and-drop ──────────────────────────────────────────────
def _toggle_ap_drag_mode(self):
"""Toggle AP placement mode on/off."""
self._ap_drag_mode = not self._ap_drag_mode
if self._ap_drag_mode:
self.place_ap_btn.config(bg=ACCENT2, fg='black')
self._set_status(
"◆ Place APs mode — click an AP in the list, then click its location on the map. "
"Right-click an existing pin to remove it.")
self.canvas_widget.get_tk_widget().config(cursor="crosshair")
# Highlight the active_bssid_listbox so user knows to click there first
self.active_bssid_listbox.config(highlightthickness=2,
highlightcolor=ACCENT2,
highlightbackground=ACCENT2)
else:
self._ap_drag_mode = False
self._dragging_bssid = None
self.place_ap_btn.config(bg=BG2, fg=ACCENT2)
self._set_status("Ready")
self.canvas_widget.get_tk_widget().config(cursor="")
self.active_bssid_listbox.config(highlightthickness=0)
def _get_selected_listbox_bssid(self) -> Optional[str]:
"""Return the BSSID currently selected in the active networks listbox."""
sel = self.active_bssid_listbox.curselection()
if not sel:
return None
idx = sel[0]
bssids = self.selected_bssids_for_heatmap
if idx < len(bssids):
return bssids[idx]
return None
def _on_canvas_click(self, event):
"""Handles both placement-mode measurement recording and AP pin dropping."""
if event.inaxes != self.ax: return
if not self._placement_mode or not self._pending_scan: return
x, y = event.xdata, event.ydata
if x is None or y is None: return
# ── Right-click: remove AP pin under cursor ────────────────────────────
if event.button == 3 and self._ap_drag_mode:
hit_radius = max(self.session.canvas_width,
self.session.canvas_height) * 0.025
for bssid, (px, py) in list(self.session.ap_positions.items()):
if abs(px - x) < hit_radius and abs(py - y) < hit_radius:
del self.session.ap_positions[bssid]
ssid = self.session.get_ssid(bssid)
self._set_status(f"Removed pin for {ssid}")
self._redraw()
return
return
# ── AP drag mode: left-click drops the selected AP ─────────────────────
if self._ap_drag_mode and event.button == 1:
bssid = self._dragging_bssid
if not bssid:
self._set_status("⚠ Click a network in the AP Positions panel first, then click its location.")
return
self.session.ap_positions[bssid] = (x, y)
ssid = self.session.get_ssid(bssid)
self._dragging_bssid = None
self._set_status(f"◆ Pinned {ssid} at ({int(x)}, {int(y)}) — right-click pin to remove")
self._update_ap_positions_panel()
self._redraw()
return
# ── Normal measurement placement ───────────────────────────────────────
if not self._placement_mode or not self._pending_scan: return
signals = {ap.bssid: ap.signal_dbm for ap in self._pending_scan}
ssid_map = {ap.bssid: ap.ssid for ap in self._pending_scan}
@@ -886,19 +1111,61 @@ class WiFiHeatmapApp:
self._set_status(f"✓ Point #{n} recorded at ({int(x)}, {int(y)})")
self._refresh_everything()
def _undo_last(self):
if not self.session.measurements: return
self.session.remove_measurement(len(self.session.measurements) - 1)
self._set_status("Last measurement removed")
self._refresh_everything()
def _on_canvas_motion(self, event):
"""Show a ghost diamond following the cursor in AP drag mode."""
if not self._ap_drag_mode: return
if event.inaxes != self.ax: return
if event.xdata is None or event.ydata is None: return
def _delete_measurement(self):
sel = self.meas_listbox.curselection()
if not sel: return
idx = sel[0]
self.session.remove_measurement(idx)
self._refresh_everything()
self._set_status(f"Measurement {idx + 1} deleted")
bssid = self._dragging_bssid
if not bssid: return
# Draw a ghost diamond at cursor position — redraw is expensive so we
# use blit-safe artists: remove the old ghost and add a new one.
if self._drag_ghost:
try:
self._drag_ghost.remove()
except Exception:
pass
self._drag_ghost = None
import matplotlib.patches as mpatches
import matplotlib.path as mpath
w = self.session.canvas_width
h = self.session.canvas_height
r = max(w, h) * 0.012 * 1.6
px, py = event.xdata, event.ydata
verts = [(px, py-r), (px+r, py), (px, py+r), (px-r, py), (px, py-r)]
codes = [mpath.Path.MOVETO, mpath.Path.LINETO, mpath.Path.LINETO,
mpath.Path.LINETO, mpath.Path.CLOSEPOLY]
self._drag_ghost = mpatches.PathPatch(
mpath.Path(verts, codes),
facecolor=ACCENT2, edgecolor='white',
linewidth=1.5, zorder=10, alpha=0.6
)
self.ax.add_patch(self._drag_ghost)
self.canvas_widget.draw_idle()
def _on_canvas_release(self, event):
"""Clean up ghost on mouse release (no action needed — drop is on click)."""
if self._drag_ghost:
try:
self._drag_ghost.remove()
except Exception:
pass
self._drag_ghost = None
if self._ap_drag_mode:
self.canvas_widget.draw_idle()
def _clear_ap_positions(self):
"""Remove all AP position pins from the session."""
if not self.session.ap_positions: return
if messagebox.askyesno("Clear AP Pins", "Remove all AP position pins?"):
self.session.ap_positions.clear()
self._set_status("All AP pins cleared")
self._redraw()
# ── Rendering ─────────────────────────────────────────────────────────────
@@ -962,6 +1229,9 @@ class WiFiHeatmapApp:
self.session_path = None
self.selected_bssids_for_heatmap = []
self._ap_stats.clear()
self._ap_drag_mode = False
self._dragging_bssid = None
self.place_ap_btn.config(bg=BG2, fg=ACCENT2)
self._refresh_everything()
self._set_status("New session started")
@@ -1038,6 +1308,7 @@ class WiFiHeatmapApp:
self._update_session_info()
self._update_floorplan_label()
self._update_heatmap_ap_selector()
self._update_ap_positions_panel()
self._redraw()
def _update_measurements_list(self):
@@ -1085,16 +1356,23 @@ class WiFiHeatmapApp:
# ── Entry point ───────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="WiFi Heatmap Generator")
parser = argparse.ArgumentParser(description="pyFi — WiFi Heatmap Generator")
parser.add_argument("--session", help="Path to a .json session file to load on startup")
args = parser.parse_args()
root = tk.Tk()
root.title("WiFi Heatmap Generator")
root.title("pyFi")
# Set taskbar / window icon
_icon_path = _resource_path(os.path.join("extras", "pyfi-logo.ico"))
try:
root.iconbitmap(default="")
root.iconbitmap(default=_icon_path)
except Exception:
pass
try:
_icon_img = tk.PhotoImage(file=_icon_path)
root.iconphoto(True, _icon_img)
except Exception:
pass # icon is cosmetic — silently skip if unavailable
WiFiHeatmapApp(root, initial_session=args.session)
root.protocol("WM_DELETE_WINDOW", lambda: (root.destroy()))
+257 -105
View File
@@ -1,34 +1,48 @@
"""
renderer.py — Renders WiFi heatmaps using matplotlib.
Supports both floorplan overlay and grid-only mode.
Ekahau-style rendering:
- Colormap runs red (strongest) → orange → yellow → green → teal → blue →
violet (weakest), matching professional site survey tools.
- Alpha channel is derived per-pixel from signal strength so strong-signal
zones are opaque and weak/absent zones fade to transparent, revealing the
floorplan or grid beneath. This produces the "bubble" zone appearance.
- A Gaussian smoothing pass is applied to the RGBA image to soften the
zone edges and blend overlapping coverage areas naturally.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.patches as mpatches
import matplotlib.path as mpath
from matplotlib.figure import Figure
from matplotlib.axes import Axes
from matplotlib.patches import Circle
from scipy.ndimage import gaussian_filter
from typing import Optional
from PIL import Image
from data import Session, Measurement
from interpolator import interpolate, HeatmapData, get_signal_at
from data import Session
from interpolator import interpolate, HeatmapData
# Custom colormap: black (no signal) → dark navy → blue → cyan → green → yellow → red (strong)
# Black occupies the very bottom so "not found" markers read naturally against the scale.
SIGNAL_COLORS = [
(0.00, 0.00, 0.00), # no signal: black ← new
(0.05, 0.05, 0.35), # very weak: dark navy
(0.10, 0.40, 0.80), # weak: blue
(0.10, 0.80, 0.80), # moderate: cyan
(0.20, 0.90, 0.20), # good: green
(1.00, 0.90, 0.10), # strong: yellow
(1.00, 0.40, 0.00), # very strong: orange
(0.90, 0.05, 0.05), # excellent: red
# ── Colormaps ─────────────────────────────────────────────────────────────────
_EKAHAU_COLORS = [
(0.45, 0.00, 0.55), # -90 dBm violet / purple
(0.10, 0.10, 0.80), # -80 dBm blue
(0.00, 0.60, 0.80), # -70 dBm teal
(0.10, 0.80, 0.30), # -65 dBm green
(0.70, 0.95, 0.10), # -58 dBm yellow-green
(1.00, 0.85, 0.00), # -52 dBm yellow
(1.00, 0.50, 0.00), # -46 dBm orange
(0.95, 0.10, 0.10), # -30 dBm red
]
SIGNAL_CMAP = mcolors.LinearSegmentedColormap.from_list("wifi_signal", SIGNAL_COLORS)
SIGNAL_CMAP = mcolors.LinearSegmentedColormap.from_list("ekahau", _EKAHAU_COLORS)
VMIN, VMAX = -90, -30
def render_heatmap(
@@ -36,158 +50,143 @@ def render_heatmap(
bssids: list[str],
fig: Optional[Figure] = None,
ax: Optional[Axes] = None,
alpha: float = 0.65,
alpha: float = 0.85,
show_points: bool = True,
show_colorbar: bool = True,
export_path: Optional[str] = None,
) -> tuple[Figure, Axes, Optional[HeatmapData]]:
"""
Render a heatmap for one or more BSSIDs onto a matplotlib figure.
Render an Ekahau-style heatmap for one or more BSSIDs.
Args:
session: The data session with measurements.
bssids: List of BSSIDs to visualize. If more than one, signal
values are averaged per measurement point (only BSSIDs
actually visible at each point contribute to the average).
fig/ax: Existing figure/axes to draw onto (creates new if None).
alpha: Transparency of the heatmap overlay.
show_points: Whether to draw measurement dot markers.
show_colorbar: Whether to draw the dBm color scale.
export_path: If set, saves figure to this path.
The heatmap is composited as an RGBA image where:
- RGB = signal strength mapped through the Ekahau colormap
- Alpha = derived from signal strength so strong zones are opaque and
weak/absent zones fade to transparent, revealing the background.
Returns:
(figure, axes, heatmap_data)
If any selected BSSIDs have physical positions set in session.ap_positions,
synthetic anchor points are injected into the interpolation so the heatmap
peak is correctly located at the real transmitter position.
"""
if not bssids:
raise ValueError("At least one BSSID must be provided.")
if fig is None or ax is None:
fig, ax = plt.subplots(figsize=(10, 7))
fig.subplots_adjust(right=0.88)
# Remove any colorbars left over from previous renders.
# Colorbars attach to the figure, not the axes, so ax.clear() doesn't touch them.
for ax_obj in fig.axes[1:]: # axes[0] is the main plot; everything else is a colorbar
# Remove stale colorbar axes from previous renders
for ax_obj in fig.axes[1:]:
ax_obj.remove()
ax.clear()
points, values = session.get_points_and_values_multi(bssids)
missing_points = session.get_missing_points(bssids) # positions with no signal
missing_points = session.get_missing_points(bssids)
anchor_pts, anchor_vals = session.get_anchor_points(bssids)
w, h = session.canvas_width, session.canvas_height
# Build a human-readable label for the title
interp_points = points + anchor_pts
interp_values = values + anchor_vals
# ── Title label ───────────────────────────────────────────────────────────
if len(bssids) == 1:
ssid = session.get_ssid(bssids[0])
ap_label = f"{ssid} • {bssids[0]}"
else:
# Show the shared SSID if all BSSIDs share one, otherwise list count
ssids = list({session.get_ssid(b) for b in bssids})
ssid = ssids[0] if len(ssids) == 1 else f"{len(ssids)} networks"
ap_label = f"{ssid} • {len(bssids)} BSSIDs averaged"
# ── Draw background ───────────────────────────────────────────────────────
# ── Background ────────────────────────────────────────────────────────────
ax.set_facecolor('#1a1a1a')
fig.patch.set_facecolor('#0d0d1a')
if session.floorplan_path:
try:
img = Image.open(session.floorplan_path).convert("RGBA")
img = img.resize((w, h), Image.LANCZOS)
ax.imshow(np.array(img), extent=[0, w, h, 0], aspect='auto', zorder=1)
fp_img = Image.open(session.floorplan_path).convert("RGBA")
fp_img = fp_img.resize((w, h), Image.LANCZOS)
ax.imshow(np.array(fp_img), extent=[0, w, h, 0],
aspect='auto', zorder=1)
except Exception as e:
_draw_grid_background(ax, w, h)
print(f"[renderer] Could not load floorplan: {e}")
else:
_draw_grid_background(ax, w, h)
# ── Heatmap ───────────────────────────────────────────────────────────────
heatmap_data = None
MIN_POINTS = 4 # must match interpolator.MIN_POINTS_FOR_INTERPOLATION
MIN_POINTS = 4
if len(points) >= MIN_POINTS:
# ── Interpolate & draw heatmap ─────────────────────────────────────
heatmap_data = interpolate(points, values, w, h)
img_heatmap = ax.imshow(
heatmap_data.grid_z,
extent=[0, w, 0, h],
origin='upper',
cmap=SIGNAL_CMAP,
vmin=-90,
vmax=-30,
alpha=alpha,
zorder=2,
aspect='auto'
if len(interp_points) >= MIN_POINTS:
heatmap_data = interpolate(interp_points, interp_values, w, h)
grid = heatmap_data.grid_z
rgba = _build_ekahau_rgba(grid, alpha)
ax.imshow(
rgba,
extent=[0, w, 0, h], origin='upper',
aspect='auto', zorder=2, interpolation='bilinear'
)
if show_colorbar:
cbar = fig.colorbar(img_heatmap, ax=ax, fraction=0.03, pad=0.02)
cbar.set_label("Signal Strength (dBm)", fontsize=10)
cbar.ax.tick_params(labelsize=8)
cbar.ax.text(1.4, -90, "Poor", transform=cbar.ax.get_yaxis_transform(),
fontsize=7, color='gray', va='bottom')
cbar.ax.text(1.4, -30, "Excellent", transform=cbar.ax.get_yaxis_transform(),
fontsize=7, color='gray', va='top')
# Black swatch at the very bottom representing "no signal found"
cbar.ax.text(1.4, -95, "No signal", transform=cbar.ax.get_yaxis_transform(),
fontsize=7, color='black', va='top',
bbox=dict(facecolor='white', edgecolor='none', pad=1.5))
else:
# ── Not enough points yet — show progress indicator ────────────────
collected = len(points)
remaining = MIN_POINTS - collected
filled = "█" * collected
empty = "░" * remaining
bar = f"[{filled}{empty}] {collected}/{MIN_POINTS}"
_draw_colorbar(fig)
msg = (
f"Collecting data\n\n"
f"{bar}\n\n"
f"Add {remaining} more point{'s' if remaining != 1 else ''} to generate the heatmap.\n"
f"Measurement dots are shown below."
)
else:
collected = len(interp_points)
remaining = MIN_POINTS - collected
bar = f"[{'█' * collected}{'░' * remaining}] {collected}/{MIN_POINTS}"
msg = (f"Collecting data\n\n{bar}\n\n"
f"Add {remaining} more point{'s' if remaining != 1 else ''} "
f"to generate the heatmap.")
ax.text(w / 2, h / 2, msg,
ha='center', va='center', fontsize=12,
color='#8888bb', linespacing=1.9,
fontfamily='monospace',
bbox=dict(boxstyle='round,pad=0.8', facecolor='#10101e', alpha=0.8),
color='#8888bb', linespacing=1.9, fontfamily='monospace',
bbox=dict(boxstyle='round,pad=0.8',
facecolor='#10101e', alpha=0.8),
zorder=3)
# ── Draw measurement points ───────────────────────────────────────────────
# ── Measurement dots ──────────────────────────────────────────────────────
radius = max(w, h) * 0.012
if show_points:
# Valid signal points — colored by strength
for (px, py), dbm in zip(points, values):
color = SIGNAL_CMAP((dbm + 90) / 60)
norm_val = (dbm - VMIN) / (VMAX - VMIN)
color = SIGNAL_CMAP(np.clip(norm_val, 0.0, 1.0))
ax.add_patch(Circle((px, py), radius=radius,
facecolor=color, edgecolor='white',
linewidth=1.5, zorder=5, alpha=0.95))
ax.text(px, py - radius * 1.8, f"{int(round(dbm))}",
ha='center', va='bottom', fontsize=7, color='white',
fontweight='bold', zorder=6)
ha='center', va='bottom', fontsize=7,
color='white', fontweight='bold', zorder=6)
# Missing signal points — black circle with "?" label
for (px, py) in missing_points:
ax.add_patch(Circle((px, py), radius=radius,
facecolor='black', edgecolor='white',
linewidth=1.5, zorder=5, alpha=0.95))
ax.text(px, py, "?",
ha='center', va='center', fontsize=7, color='white',
fontweight='bold', zorder=6)
ha='center', va='center', fontsize=7,
color='white', fontweight='bold', zorder=6)
# ── Labels & styling ──────────────────────────────────────────────────────
total_points = len(points) + len(missing_points)
point_note = f"{total_points} measurement{'s' if total_points != 1 else ''}"
_draw_ap_markers(ax, session, bssids, radius)
# ── Labels & axes ─────────────────────────────────────────────────────────
total = len(points) + len(missing_points)
point_note = f"{total} measurement{'s' if total != 1 else ''}"
if missing_points:
point_note += f" • {len(missing_points)} out of range (●)"
if len(bssids) > 1:
point_note += f" • avg of {len(bssids)} BSSIDs"
n_pinned = sum(1 for b in bssids if b in session.ap_positions)
if n_pinned:
point_note += f" • {n_pinned} AP position{'s' if n_pinned != 1 else ''} pinned (◆)"
if not session.floorplan_path:
point_note += " ⚠ No floorplan — adding one increases accuracy"
ax.set_title(f"WiFi Heatmap\n{ap_label}", fontsize=12, fontweight='bold',
color='white', pad=10)
ax.set_title(f"WiFi Heatmap\n{ap_label}",
fontsize=12, fontweight='bold', color='white', pad=10)
ax.set_xlabel(point_note, fontsize=9, color='#888888')
ax.set_xlim(0, w)
ax.set_ylim(h, 0)
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor('#0d0d1a')
fig.patch.set_facecolor('#0d0d1a')
if export_path:
fig.savefig(export_path, dpi=150, bbox_inches='tight',
@@ -196,19 +195,172 @@ def render_heatmap(
return fig, ax, heatmap_data
# ── Colorbar ──────────────────────────────────────────────────────────────────
def _draw_colorbar(fig: Figure):
"""
Draw the signal strength colorbar by rendering the colormap gradient
directly as an imshow onto a dedicated axes.
This approach is backend-agnostic and guaranteed to show color — it does
not rely on fig.colorbar() interpreting a ScalarMappable, which can silently
render white on some matplotlib/backend combinations.
"""
cax = fig.add_axes([0.91, 0.15, 0.025, 0.70])
# Build the gradient image: 256 rows (dBm steps) × 1 column, RGBA
gradient = np.linspace(1.0, 0.0, 256).reshape(256, 1) # top=VMAX, bottom=VMIN
cax.imshow(gradient, aspect='auto', cmap=SIGNAL_CMAP,
extent=[0, 1, VMIN, VMAX], origin='upper')
# Style the axes
cax.yaxis.set_label_position('right')
cax.yaxis.tick_right()
cax.set_ylabel("Signal Strength (dBm)", fontsize=9, color='white', labelpad=8)
cax.tick_params(axis='y', labelsize=7, colors='white', length=3)
cax.tick_params(axis='x', which='both', bottom=False, labelbottom=False)
cax.set_xlim(0, 1)
cax.set_ylim(VMIN, VMAX)
# Spine styling
for spine in cax.spines.values():
spine.set_edgecolor('#444444')
# Qualitative labels
cax.text(1.6, VMAX, "Excellent", transform=cax.get_yaxis_transform(),
fontsize=7, color='#cccccc', va='top')
cax.text(1.6, VMIN, "Poor", transform=cax.get_yaxis_transform(),
fontsize=7, color='#cccccc', va='bottom')
# "No signal" swatch below the bar
cax.text(0.5, VMIN - 3, "No signal",
transform=cax.get_yaxis_transform(),
fontsize=6, color='white', va='top', ha='center',
bbox=dict(facecolor='black', edgecolor='#444444',
pad=2.0, boxstyle='round'))
# ── RGBA builder ──────────────────────────────────────────────────────────────
def _build_ekahau_rgba(grid: np.ndarray, max_alpha: float) -> np.ndarray:
"""
Convert a dBm grid into an RGBA uint8 image with Ekahau-style rendering.
Alpha channel:
- Signal ≥ VMAX (-30 dBm) → fully opaque (max_alpha)
- Signal ≤ FADE_FLOOR → fully transparent
- Between → cosine ramp for natural bubble-edge blending
Gaussian blur on alpha blends overlapping AP coverage zones smoothly.
"""
FADE_FLOOR = -85.0
BLUR_SIGMA = 8.0
res_h, res_w = grid.shape
norm = np.clip((grid - VMIN) / (VMAX - VMIN), 0.0, 1.0)
rgb_float = SIGNAL_CMAP(norm)[:, :, :3]
fade_range = VMAX - FADE_FLOOR
t = np.clip((grid - FADE_FLOOR) / fade_range, 0.0, 1.0)
alpha_raw = 0.5 * (1.0 - np.cos(np.pi * t))
alpha_raw[np.isnan(grid)] = 0.0
alpha_blur = gaussian_filter(alpha_raw, sigma=BLUR_SIGMA)
alpha_blur = np.clip(alpha_blur * max_alpha, 0.0, max_alpha)
rgba = np.zeros((res_h, res_w, 4), dtype=np.uint8)
rgba[:, :, 0] = (rgb_float[:, :, 0] * 255).astype(np.uint8)
rgba[:, :, 1] = (rgb_float[:, :, 1] * 255).astype(np.uint8)
rgba[:, :, 2] = (rgb_float[:, :, 2] * 255).astype(np.uint8)
rgba[:, :, 3] = (alpha_blur * 255).astype(np.uint8)
return rgba
# ── AP position markers ───────────────────────────────────────────────────────
def _draw_ap_markers(ax: Axes, session: Session, bssids: list[str], radius: float):
"""
Draw a distinct diamond ◆ icon at each AP whose physical position is known.
Visual design (intentionally different from measurement circles):
- Outer dashed pulse ring
- White-bordered diamond
- Signal-colored inner diamond
- Three WiFi arc lines above
- SSID label below
"""
for bssid in bssids:
if bssid not in session.ap_positions:
continue
px, py = session.ap_positions[bssid]
ssid = session.get_ssid(bssid)
r = radius * 1.6
# Pulse ring
ax.add_patch(Circle((px, py), radius=r * 1.9,
facecolor='none', edgecolor='white',
linewidth=0.8, zorder=7, alpha=0.35,
linestyle='--'))
# Outer white diamond
ax.add_patch(mpatches.RegularPolygon(
(px, py), numVertices=4, radius=r * 1.15,
orientation=np.pi / 4,
facecolor='white', edgecolor='white',
linewidth=0, zorder=8, alpha=0.95))
# Signal-colored inner diamond
real_pts, real_vals = session.get_points_and_values(bssid)
anchor_dbm = min(-25, max(real_vals) + 5) if real_vals else -35
norm_val = np.clip((anchor_dbm - VMIN) / (VMAX - VMIN), 0.0, 1.0)
color = SIGNAL_CMAP(norm_val)
ax.add_patch(mpatches.RegularPolygon(
(px, py), numVertices=4, radius=r * 0.80,
orientation=np.pi / 4,
facecolor=color, edgecolor='none',
zorder=9, alpha=0.95))
# WiFi arcs
for arc_r, arc_alpha in [(r * 0.55, 0.9), (r * 0.9, 0.65), (r * 1.25, 0.40)]:
ax.add_patch(mpatches.Arc(
(px, py - r * 0.15),
width=arc_r * 2, height=arc_r * 2,
angle=0, theta1=30, theta2=150,
color='white', linewidth=1.4,
zorder=10, alpha=arc_alpha))
# SSID label
ax.text(px, py + r * 2.2, ssid,
ha='center', va='top', fontsize=7,
color='white', fontweight='bold', zorder=10,
bbox=dict(boxstyle='round,pad=0.3',
facecolor='#000000', alpha=0.55,
edgecolor='none'))
# Centre glyph
ax.text(px, py, '◆',
ha='center', va='center', fontsize=6,
color='white', zorder=11, alpha=0.7)
# ── Grid background ───────────────────────────────────────────────────────────
def _draw_grid_background(ax: Axes, w: int, h: int):
"""Draw a subtle technical grid when no floorplan is available."""
ax.set_facecolor('#0d0d1a')
grid_spacing = max(w, h) // 10
"""Draw a subtle coordinate grid when no floorplan is loaded."""
ax.set_facecolor('#1a1a1a')
spacing = max(w, h) // 10
for x in range(0, w + 1, grid_spacing):
ax.axvline(x, color='#1e2a4a', linewidth=0.6, zorder=0)
for y in range(0, h + 1, grid_spacing):
ax.axhline(y, color='#1e2a4a', linewidth=0.6, zorder=0)
for x in range(0, w + 1, spacing):
ax.axvline(x, color='#2a2a2a', linewidth=0.6, zorder=0)
for y in range(0, h + 1, spacing):
ax.axhline(y, color='#2a2a2a', linewidth=0.6, zorder=0)
for x in range(0, w + 1, grid_spacing * 2):
for x in range(0, w + 1, spacing * 2):
ax.text(x, h - 4, str(x), ha='center', va='bottom',
fontsize=6, color='#2a3a5a')
for y in range(0, h + 1, grid_spacing * 2):
fontsize=6, color='#3a3a3a')
for y in range(0, h + 1, spacing * 2):
ax.text(2, y, str(y), ha='left', va='center',
fontsize=6, color='#2a3a5a')
fontsize=6, color='#3a3a3a')
+12 -4
View File
@@ -293,9 +293,16 @@ def _wlanapi_enumerate_and_scan(wlan, handle) -> list[AccessPoint]:
("InterfaceInfo", WLAN_INTERFACE_INFO * 64)]
# ── WLAN_BSS_ENTRY ────────────────────────────────────────────────────────
# DOT11_SSID is { ULONG uSSIDLength; UCHAR ucSSID[32]; } = 36 bytes.
# It must NOT be packed as c_ubyte*33 — uSSIDLength is a 4-byte ULONG,
# not a single byte, so the SSID data starts at offset 4, not offset 1.
class DOT11_SSID(ctypes.Structure):
_fields_ = [("uSSIDLength", wt.ULONG),
("ucSSID", ctypes.c_ubyte * 32)]
class WLAN_BSS_ENTRY(ctypes.Structure):
_fields_ = [
("dot11Ssid", ctypes.c_ubyte * 33), # DOT11_SSID (length + ucSSID)
("dot11Ssid", DOT11_SSID),
("uPhyId", wt.ULONG),
("dot11Bssid", ctypes.c_ubyte * 6),
("dot11BssType", wt.DWORD),
@@ -357,9 +364,10 @@ def _wlanapi_enumerate_and_scan(wlan, handle) -> list[AccessPoint]:
for j in range(bss_list.dwNumberOfItems):
entry = bss_list.wlanBssEntries[j]
# Decode SSID (first byte = length in DOT11_SSID)
ssid_len = entry.dot11Ssid[0]
ssid_bytes = bytes(entry.dot11Ssid[1:1 + ssid_len])
# Decode SSID using the correct DOT11_SSID field layout:
# uSSIDLength is the number of valid bytes in ucSSID (max 32).
ssid_len = entry.dot11Ssid.uSSIDLength
ssid_bytes = bytes(entry.dot11Ssid.ucSSID[:ssid_len])
try:
ssid = ssid_bytes.decode("utf-8", errors="replace").strip("\x00")
except Exception: