#!/usr/bin/env python3
"""wifi24_scan.py - watch 2.4 GHz Wi-Fi channel activity with a HackRF.

A HackRF cannot demodulate 802.11, and nothing here recovers a single bit. A
20 MHz OFDM burst is far wider than a sweeping SDR captures coherently, and
the sweep revisits each slice of the band only a few hundred times a second.

What a sweep does show is where the energy is: which channels carry traffic,
how hard, and how that changes second to second. That is enough to see the
shape of the band - a saturated channel 6, a quiet channel 1, a microwave oven
sitting on 2450 MHz - and to decide where to point a real capture. For actual
frames, use wifi24_capture.py beside this file.

Reads the CSV that hackrf_sweep writes on stdout:

    date, time, hz_low, hz_high, hz_bin_width, num_samples, dB, dB, ...

Each line is one slice of the band. A sweep is finished when a slice we have
already filled comes round again, which is how the display is paced.
"""

import argparse
import collections
import math
import shutil
import signal
import statistics
import subprocess
import sys
import tempfile

# Channel centres in MHz. 1-13 are 5 MHz apart; 14 is the odd one out and is
# only legal in Japan, for 802.11b alone.
CHANNELS = {n: 2412 + 5 * (n - 1) for n in range(1, 14)}
CHANNELS[14] = 2484

# A 20 MHz channel with its guard bands is ~22 MHz wide, so a bin counts
# towards a channel when it falls within 11 MHz of the centre. Channels
# therefore overlap heavily, which is the whole reason 1/6/11 are special.
HALF_WIDTH_MHZ = 11
NON_OVERLAPPING = (1, 6, 11)

SPARK = " .:-=+*#%"
BAR_WIDTH = 34
# Peak energy near a channel says "something loud happened within 11 MHz of
# here", which with overlapping channels is true of most of the band at once.
# Mean energy across the channel's bins is what distinguishes a channel
# carrying traffic from a quiet one, so the bar and the sparkline use the mean
# and the peak is reported as a number beside it.
#
# The mean is a mean of *power*, not of decibels - see power_mean_db(). With
# correct averaging a loaded channel sits tens of dB over the floor, so the
# bar needs a far wider range than a dB-domain average would suggest.
MEAN_RANGE_DB = 35.0
PEAK_RANGE_DB = 45.0


def power_mean_db(samples_db):
    """Mean power of dB samples, averaged linearly and returned in dB.

    Averaging decibels arithmetically is not averaging power, and the
    difference is not subtle. Wi-Fi is bursty: a channel carrying beacons and
    traffic is idle most of the time, so most of the samples a sweeping SDR
    takes in it are noise. The arithmetic mean of the dB values is therefore
    pinned near the noise floor no matter how loud the bursts are, which hides
    exactly the activity this tool exists to show.

    Measured on a band with 58 access points, all on channels 1, 6 and 11:
    averaging dB gave a 3.5 dB spread across the whole band and no peak at any
    channel centre, while averaging power gave 33 dB and put the maximum where
    the traffic actually was.
    """
    if not samples_db:
        return -math.inf
    watts = statistics.fmean(10.0 ** (d / 10.0) for d in samples_db)
    # At low gain hackrf_sweep can report bins as -inf, which is zero power.
    return 10.0 * math.log10(watts) if watts > 0.0 else -math.inf


def parse_args(argv=None):
    p = argparse.ArgumentParser(
        description="Show 2.4 GHz Wi-Fi channel activity using a HackRF sweep.",
        epilog="This measures RF energy per channel. It does not decode frames.",
    )
    p.add_argument("--min-mhz", type=int, default=2400, help="sweep start (default 2400)")
    p.add_argument("--max-mhz", type=int, default=2500, help="sweep end (default 2500)")
    p.add_argument("--bin-hz", type=int, default=1_000_000,
                   help="FFT bin width in Hz, 2445-5000000 (default 1000000)")
    p.add_argument("--lna", type=int, default=16, help="RX LNA gain, 0-40 in 8 dB steps (default 16)")
    p.add_argument("--vga", type=int, default=20, help="RX VGA gain, 0-62 in 2 dB steps (default 20)")
    p.add_argument("--amp", action="store_true", help="enable the RX RF amplifier")
    p.add_argument("--device", help="HackRF serial number, when more than one is attached")
    p.add_argument("--threshold", type=float, default=6.0,
                   help="dB above the noise floor that counts as busy (default 6)")
    p.add_argument("--history", type=int, default=30, help="sweeps kept per channel sparkline (default 30)")
    p.add_argument("--sweeps", type=int, default=0, help="stop after N sweeps (default: run until Ctrl-C)")
    p.add_argument("--once", action="store_true", help="print one reading and exit, no screen clearing")
    return p.parse_args(argv)


def build_sweep_cmd(args):
    cmd = ["hackrf_sweep",
           "-f", f"{args.min_mhz}:{args.max_mhz}",
           "-w", str(args.bin_hz),
           "-l", str(args.lna),
           "-g", str(args.vga)]
    if args.amp:
        cmd += ["-a", "1"]
    if args.device:
        cmd += ["-d", args.device]
    return cmd


def channels_for_bin(freq_mhz, cache={}):
    """Which Wi-Fi channels a bin at freq_mhz contributes to."""
    key = round(freq_mhz, 3)
    hit = cache.get(key)
    if hit is None:
        hit = tuple(n for n, c in CHANNELS.items() if abs(freq_mhz - c) <= HALF_WIDTH_MHZ)
        cache[key] = hit
    return hit


def parse_line(line):
    """-> (hz_low, bin_width, [dB, ...]) or None if the line is not a sweep row."""
    parts = line.split(",")
    if len(parts) < 7:
        return None
    try:
        hz_low = int(parts[2])
        bin_width = float(parts[4])
        powers = [float(x) for x in parts[6:]]
    except ValueError:
        return None
    return hz_low, bin_width, powers


def fold_into_channels(slices):
    """Collapse {hz_low: (bin_width, powers)} into per-channel bin lists.

    Returns (per_channel, everything, swept), where `swept` counts the bins the
    sweep actually visited per channel including the unusable ones. Coverage is
    a question about the sweep's frequency range, so it has to be measured
    before dropping bins for any other reason.
    """
    per_channel = collections.defaultdict(list)
    swept = collections.Counter()
    everything = []
    for hz_low, (bin_width, powers) in slices.items():
        for i, db in enumerate(powers):
            centre_mhz = (hz_low + (i + 0.5) * bin_width) / 1e6
            chans = channels_for_bin(centre_mhz)
            for ch in chans:
                swept[ch] += 1
            # hackrf_sweep reports an empty bin as -inf, especially at low
            # gain. Keeping those poisons the noise floor and every mean
            # computed from them, so they count as swept but not as data.
            if not math.isfinite(db):
                continue
            everything.append(db)
            for ch in chans:
                per_channel[ch].append(db)
    return per_channel, everything, swept


def coverage_fraction(swept, bin_width_hz):
    """How much of each channel's ~22 MHz the sweep actually covered, 0.0-1.0.

    A sweep narrower than the band leaves the channels at its edges with only
    a few of their bins. Their mean is then computed over a sliver of the
    channel and means nothing, so it has to be marked rather than shown as an
    ordinary reading. hackrf_sweep also rounds the requested range up to a
    multiple of its 20 MHz tile width, so the edges are rarely where you asked
    for them: -f 2400:2450 actually sweeps to 2460.
    """
    if not bin_width_hz:
        return {}
    expected = max(1, round(2 * HALF_WIDTH_MHZ / (bin_width_hz / 1e6)))
    return {ch: min(1.0, n / expected) for ch, n in swept.items()}


def render(levels, floor, history, args, sweeps, coverage=None, out=sys.stdout):
    coverage = coverage or {}
    width = shutil.get_terminal_size((100, 40)).columns
    print(f"2.4 GHz channel activity - noise floor {floor:6.1f} dBm - "
          f"busy = mean {args.threshold:.0f} dB over floor - sweep {sweeps}", file=out)
    print(f"{'ch':>3} {'MHz':>5}  {'occupancy':<{BAR_WIDTH}} {'mean':>7} {'peak':>7}  recent",
          file=out)
    partial_seen = False
    for ch in sorted(CHANNELS):
        if ch not in levels:
            continue
        mean, peak = levels[ch]
        # A channel the sweep only clipped the edge of has a meaningless mean.
        partial = coverage.get(ch, 1.0) < 0.9
        over = mean - floor if math.isfinite(mean) and math.isfinite(floor) else 0.0
        over = max(0.0, min(over, MEAN_RANGE_DB))
        filled = min(BAR_WIDTH, int(round(BAR_WIDTH * over / MEAN_RANGE_DB)))
        busy = over >= args.threshold and not partial
        bar = ("#" * filled).ljust(BAR_WIDTH)
        if partial:
            partial_seen = True
            bar = f"(only {coverage[ch] * 100:.0f}% of this channel was swept)".ljust(BAR_WIDTH)
        mark = "*" if ch in NON_OVERLAPPING else " "
        spark = "".join(
            SPARK[min(len(SPARK) - 1, int(len(SPARK) * v / MEAN_RANGE_DB))]
            for v in history[ch]
        )
        # Keep the sparkline inside the terminal.
        room = max(8, width - (3 + 1 + 5 + 2 + BAR_WIDTH + 1 + 7 + 1 + 7 + 2 + 2))
        print(f"{ch:>3}{mark}{CHANNELS[ch]:>5}  {bar} {mean:>7.1f} {peak:>7.1f}  "
              f"{spark[-room:]}{' <' if busy else ''}", file=out)
    print("* = non-overlapping channel. Energy only; no frames are decoded.", file=out)
    if partial_seen:
        print("Channels marked as partly swept fall outside --min-mhz/--max-mhz; "
              "widen the range to read them.", file=out)


def main(argv=None):
    args = parse_args(argv)
    if shutil.which("hackrf_sweep") is None:
        print("wifi24_scan: hackrf_sweep not found (install the hackrf tools)", file=sys.stderr)
        return 1

    cmd = build_sweep_cmd(args)
    # hackrf_sweep explains its own failures on stderr - a missing device, a
    # bad serial, a bin width out of range. Keep them so a sweep that produces
    # nothing can say why instead of exiting quietly.
    errlog = tempfile.TemporaryFile(mode="w+")
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=errlog, text=True)
    except OSError as e:
        print(f"wifi24_scan: cannot start hackrf_sweep: {e}", file=sys.stderr)
        return 1

    # Ctrl-C should stop the sweep and leave the terminal usable.
    signal.signal(signal.SIGINT, lambda *_: proc.terminate())

    history = {ch: collections.deque([0.0] * args.history, maxlen=args.history) for ch in CHANNELS}
    floors = collections.deque(maxlen=10)
    slices = {}
    sweeps = 0
    live = sys.stdout.isatty() and not args.once
    status = 0

    try:
        for line in proc.stdout:
            row = parse_line(line)
            if row is None:
                continue
            hz_low, bin_width, powers = row

            if hz_low in slices:
                # This slice has come round again: the previous sweep is complete.
                per_channel, everything, swept = fold_into_channels(slices)
                if everything:
                    everything.sort()
                    floors.append(everything[len(everything) // 10])
                    floor = statistics.median(floors)
                    levels = {ch: (power_mean_db(bins), max(bins))
                              for ch, bins in per_channel.items()}
                    for ch, (mean, _peak) in levels.items():
                        rise = mean - floor if math.isfinite(mean) and math.isfinite(floor) else 0.0
                        history[ch].append(max(0.0, min(rise, MEAN_RANGE_DB)))
                    sweeps += 1
                    if live:
                        print("\033[H\033[J", end="")
                    render(levels, floor, history, args, sweeps,
                           coverage_fraction(swept, bin_width))
                    if args.once or (args.sweeps and sweeps >= args.sweeps):
                        break
                slices = {}

            slices[hz_low] = (bin_width, powers)
    except BrokenPipeError:
        status = 0
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=5)
        except subprocess.TimeoutExpired:
            proc.kill()

    if sweeps == 0:
        # No completed sweep means no data at all, which is a failure however
        # cleanly hackrf_sweep exited. Saying nothing and returning 0 here
        # reads as "the band is empty".
        print("wifi24_scan: no sweep data - hackrf_sweep produced nothing usable.",
              file=sys.stderr)
        errlog.seek(0)
        lines = [ln.rstrip() for ln in errlog.read().splitlines() if ln.strip()]
        # hackrf_sweep answers a bad argument with its whole usage text, so the
        # last few lines are the help rather than the complaint. Pick out the
        # lines that actually look like the problem.
        hits = [ln for ln in lines
                if any(w in ln.lower() for w in
                       ("error", "failed", "not found", "no hackrf", "cannot",
                        "invalid", "busy", "permission"))]
        for line in (hits or lines)[-4:]:
            print(f"  {line}", file=sys.stderr)
        print("  check that the HackRF is attached and free (hackrf_info), that "
              "--device matches\n  its serial, and that --bin-hz is within "
              "2445-5000000.", file=sys.stderr)
        return 1

    return status


if __name__ == "__main__":
    sys.exit(main())
