Module: PWN::SDR::GQRX

Defined in:
lib/pwn/sdr/gqrx.rb

Overview

This plugin interacts with the remote control interface of GQRX.

Class Method Summary collapse

Class Method Details

.analyze_log(opts = {}) ⇒ Object

Supported Method Parameters

PWN::SDR::GQRX.analyze_log( scan_log: 'required - Path to signals log file', target: 'optional - GQRX target IP address (defaults to 127.0.0.1)', port: 'optional - GQRX target port (defaults to 7356)' )



1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
# File 'lib/pwn/sdr/gqrx.rb', line 1741

public_class_method def self.analyze_log(opts = {})
  scan_log = opts[:scan_log]
  raise 'ERROR: scan_log path is required.' unless File.exist?(scan_log)

  scan_resp = JSON.parse(File.read(scan_log), symbolize_names: true)
  raise 'ERROR: No signals found in log.' if scan_resp[:signals].nil? || scan_resp[:signals].empty?

  target = opts[:target]
  port = opts[:port]

  analyze_scan(
    scan_resp: scan_resp,
    target: target,
    port: port
  )
rescue StandardError => e
  raise e
end

.analyze_scan(opts = {}) ⇒ Object

Supported Method Parameters

PWN::SDR::GQRX.analyze_scan( scan_resp: 'required - Scan response hash returned from #scan_range method', target: 'optional - GQRX target IP address (defaults to 127.0.0.1)', port: 'optional - GQRX target port (defaults to 7356)' )



1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
# File 'lib/pwn/sdr/gqrx.rb', line 1670

public_class_method def self.analyze_scan(opts = {})
  scan_resp = opts[:scan_resp]
  raise 'ERROR: scan_resp is required.' if scan_resp.nil? || scan_resp[:signals].nil? || scan_resp[:signals].empty?

  target = opts[:target]
  port = opts[:port]
  gqrx_sock = connect(
    target: target,
    port: port
  )

  scan_resp[:signals].each do |signal|
    # puts JSON.pretty_generate(signal)
    signal[:gqrx_sock] = gqrx_sock

    # This is required to keep connection alive during analysis
    signal[:keep_alive] = true

    # We do this because we need keep_alive true for init_freq calls below
    squelch = signal[:squelch]
    squelch = cmd(gqrx_sock: gqrx_sock, cmd: 'l SQL').to_f if squelch.nil?
    change_squelch_resp = cmd(
      gqrx_sock: gqrx_sock,
      cmd: "L SQL #{squelch}",
      resp_ok: 'RPRT 0'
    )

    audio_gain_db = signal[:audio_gain_db] ||= 0.0
    audio_gain_db = audio_gain_db.to_f
    audio_gain_db_resp = cmd(
      gqrx_sock: gqrx_sock,
      cmd: "L AF #{audio_gain_db}",
      resp_ok: 'RPRT 0'
    )

    demodulator_mode = signal[:demodulator_mode] || :WFM
    mode_str = demodulator_mode.to_s.upcase

    bandwidth = signal[:bandwidth] ||= '200.000'
    passband_hz = PWN::SDR.hz_to_i(freq: bandwidth)
    cmd(
      gqrx_sock: gqrx_sock,
      cmd: "M #{mode_str} #{passband_hz}",
      resp_ok: 'RPRT 0'
    )

    freq_obj = init_freq(signal)
    freq_obj = signal.merge(freq_obj)
    # Redact gqrx_sock from output
    freq_obj.delete(:gqrx_sock)
    unless freq_obj[:decoder]
      puts JSON.pretty_generate(freq_obj)
      print 'Press [ENTER] to continue...'
      gets
    end
    puts "\n" * 3
  end
rescue Interrupt
  puts "\nCTRL+C detected - goodbye."
rescue StandardError => e
  raise e
ensure
  disconnect(gqrx_sock: gqrx_sock)
end

.apply_band_plan_input_rate(opts = {}) ⇒ Object

Supported Method Parameters

result = PWN::SDR::GQRX.apply_band_plan_input_rate( band_plan: 'required - key from PWN::SDR::FrequencyAllocation.band_plans (e.g. :fm_radio, :ads_b1090)', path: 'optional - GQRX conf path', clamp: 'optional - snap to device-legal rate (default true)', restart: 'optional - bounce GQRX after write (default false)', input_rate: 'optional - override the band-plan recommended rate' ) Looks up FrequencyAllocation, clamps to the currently configured SDR's legal rates, and writes it into GQRX's conf.



2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
# File 'lib/pwn/sdr/gqrx.rb', line 2129

public_class_method def self.apply_band_plan_input_rate(opts = {})
  key = opts[:band_plan] || opts[:profile] || opts[:assume_band_plan]
  raise 'ERROR: :band_plan required' if key.nil?

  plans = PWN::SDR::FrequencyAllocation.band_plans
  plan_key = key.to_s.strip.downcase.tr('-', '_').to_sym
  plan = plans[plan_key]
  raise "ERROR: unknown band plan #{key.inspect}. Known: #{plans.keys.sort.join(', ')}" if plan.nil?

  desired = (opts[:input_rate] || opts[:sample_rate] || plan[:input_rate] || 1_000_000).to_i
  result = set_input_rate(
    input_rate: desired,
    path: opts[:path],
    clamp: opts.fetch(:clamp, true),
    restart: opts[:restart],
    gqrx_bin: opts[:gqrx_bin]
  )
  result.merge(
    band_plan: plan_key,
    band_plan_input_rate: plan[:input_rate],
    bandwidth: plan[:bandwidth],
    demodulator_mode: plan[:demodulator_mode]
  )
rescue StandardError => e
  raise e
end

.authorsObject



3000
3001
3002
3003
3004
# File 'lib/pwn/sdr/gqrx.rb', line 3000

public_class_method def self.authors
  "AUTHOR(S):
    0day Inc. <support@0dayinc.com>
  "
end

.cmd(opts = {}) ⇒ Object

Supported Method Parameters

gqrx_resp = PWN::SDR::GQRX.cmd( gqrx_sock: 'required - GQRX socket object returned from #connect method', cmd: 'required - GQRX command to execute', resp_ok: 'optional - Expected response from GQRX to indicate success' )



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/pwn/sdr/gqrx.rb', line 18

public_class_method def self.cmd(opts = {})
  gqrx_sock = opts[:gqrx_sock]
  cmd = opts[:cmd]
  resp_ok = opts[:resp_ok]

  # Most Recent GQRX Command Set:
  # https://raw.githubusercontent.com/gqrx-sdr/gqrx/master/resources/remote-control.txt
  # Remote control protocol.
  #
  # Supported commands:
  #  f
  #     Get frequency [Hz]
  #  F <frequency>
  #     Set frequency [Hz]
  #  m
  #     Get demodulator mode and passband
  #  M <mode> [passband]
  #     Set demodulator mode and passband [Hz]
  #     Passing a '?' as the first argument instead of 'mode' will return
  #     a space separated list of radio backend supported modes.
  #  l|L ?
  #     Get a space separated list of settings available for reading (l) or writing (L).
  #  l STRENGTH
  #     Get signal strength [dBFS]
  #  l SQL
  #     Get squelch threshold [dBFS]
  #  L SQL <sql>
  #     Set squelch threshold to <sql> [dBFS]
  #  l AF
  #     Get audio gain [dB]
  #  L AF <gain>
  #     Set audio gain to <gain> [dB]
  #  l <gain_name>_GAIN
  #     Get the value of the gain setting with the name <gain_name>
  #  L <gain_name>_GAIN <value>
  #     Set the value of the gain setting with the name <gain_name> to <value>
  #  p RDS_PI
  #     Get the RDS PI code (in hexadecimal). Returns 0000 if not applicable.
  #  p RDS_PS_NAME
  #     Get the RDS Program Service (PS) name
  #  p RDS_RADIOTEXT
  #     Get the RDS RadioText message
  #  u RECORD
  #     Get status of audio recorder
  #  U RECORD <status>
  #     Set status of audio recorder to <status>
  #  u IQRECORD
  #     Get status of IQ recorder
  #  U IQRECORD <status>
  #     Set status of IQ recorder to <status>
  #  u DSP
  #     Get DSP (SDR receiver) status
  #  U DSP <status>
  #     Set DSP (SDR receiver) status to <status>
  #  u RDS
  #     Get RDS decoder status.  Only functions in WFM mode.
  #  U RDS <status>
  #     Set RDS decoder to <status>.  Only functions in WFM mode.
  #  u MUTE
  #     Get audio mute status
  #  U MUTE <status>
  #     Set audio mute to <status>
  #  q|Q
  #     Close connection
  #  AOS
  #     Acquisition of signal (AOS) event, start audio recording
  #  LOS
  #     Loss of signal (LOS) event, stop audio recording
  #  LNB_LO [frequency]
  #     If frequency [Hz] is specified set the LNB LO frequency used for
  #     display. Otherwise print the current LNB LO frequency [Hz].
  #  \chk_vfo
  #     Get VFO option status (only usable for hamlib compatibility)
  #  \dump_state
  #     Dump state (only usable for hamlib compatibility)
  #  \get_powerstat
  #     Get power status (only usable for hamlib compatibility)
  #  v
  #     Get 'VFO' (only usable for hamlib compatibility)
  #  V
  #     Set 'VFO' (only usable for hamlib compatibility)
  #  s
  #     Get 'Split' mode (only usable for hamlib compatibility)
  #  S
  #     Set 'Split' mode (only usable for hamlib compatibility)
  #  _
  #     Get version
  #
  #
  # Reply:
  #  RPRT 0
  #     Command successful
  #  RPRT 1
  #     Command failed

  gqrx_sock.write("#{cmd}\n")
  response = []
  start_time = Time.now

  # Wait up to 2 seconds for initial response
  if gqrx_sock.wait_readable(2.0)
    response.push(gqrx_sock.readline.chomp)
    # Drain any additional lines quickly
    loop do
      break if gqrx_sock.wait_readable(0.0001).nil?

      response.push(gqrx_sock.readline.chomp)
    end
  end

  raise "No response for command: #{cmd}" if response.empty?

  response_str = response.length == 1 ? response.first : response.join(' ')

  raise "ERROR!!! Command: #{cmd} Expected Resp: #{resp_ok}, Got: #{response_str}" if resp_ok && response_str != resp_ok

  # Reformat positive integer frequency responses (e.g., from 'f')
  response_str = PWN::SDR.hz_to_s(freq: response_str) if response_str.match?(/^\d+$/) && response_str.to_i.positive?

  response_str
rescue RuntimeError => e
  response_str = 'Function not supported by this radio backend.' if e.message.include?('RF_GAIN') || e.message.include?('IF_GAIN') || e.message.include?('BB_GAIN')

  raise e unless e.message.include?('RF_GAIN') ||
                 e.message.include?('IF_GAIN') ||
                 e.message.include?('BB_GAIN')
rescue StandardError => e
  raise e
end

.config_path(opts = {}) ⇒ Object

Supported Method Parameters

path = PWN::SDR::GQRX.config_path( path: 'optional - absolute path to a GQRX .conf (defaults to ~/.config/gqrx/default.conf or recentconfig)' )



1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
# File 'lib/pwn/sdr/gqrx.rb', line 1888

public_class_method def self.config_path(opts = {})
  return opts[:path].to_s if opts[:path] && !opts[:path].to_s.empty?

  conf_dir = File.join(Dir.home, '.config', 'gqrx')
  recent = File.join(conf_dir, 'recentconfig.cfg')
  if File.file?(recent)
    # recentconfig.cfg is usually a single path line
    candidate = File.read(recent).to_s.lines.map(&:strip).find { |l| !l.empty? && !l.start_with?('#') }
    return candidate if candidate && File.file?(candidate)
  end

  default = File.join(conf_dir, 'default.conf')
  return default if File.file?(default)

  # last resort: newest *.conf
  newest = Dir.glob(File.join(conf_dir, '*.conf')).max_by { |f| File.mtime(f) }
  return newest if newest

  default
rescue StandardError => e
  raise e
end

.connect(opts = {}) ⇒ Object



1059
1060
1061
1062
1063
1064
1065
1066
# File 'lib/pwn/sdr/gqrx.rb', line 1059

public_class_method def self.connect(opts = {})
  target = opts[:target] ||= '127.0.0.1'
  port = opts[:port] ||= 7356

  PWN::Plugins::Sock.connect(target: target, port: port)
rescue StandardError => e
  raise e
end

.device_input_rates(opts = {}) ⇒ Object

Supported Method Parameters

rates = PWN::SDR::GQRX.device_input_rates( device: 'optional - SoapySDR args string (defaults to [input] device= from conf)', path: 'optional - GQRX conf path used when :device omitted' ) Returns Array of legal sample rates (Hz). Empty when unprobeable.



1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
# File 'lib/pwn/sdr/gqrx.rb', line 1948

public_class_method def self.device_input_rates(opts = {})
  device = opts[:device].to_s
  if device.empty?
    conf = read_input_config(path: opts[:path])
    device = conf[:device].to_s
  end

  # Prefer SoapySDRUtil --probe (works for every Soapy driver GQRX uses).
  # device strings look like:
  #   "device=HackRF Pro,driver=hackrf,..."  or  "driver=plutosdr,..."
  # Conf may be stale (e.g. still names Pluto while a HackRF is what is
  # actually attached) — fall through a probe chain until rates resolve.
  candidates = []
  candidates << device unless device.empty?
  if (driver = device[/driver=([^,]+)/, 1])
    candidates << "driver=#{driver}"
  end
  begin
    find_out = `SoapySDRUtil --find 2>/dev/null`.to_s
    find_out.scan(/driver\s*=\s*(\S+)/i).flatten.uniq.each do |d|
      candidates << "driver=#{d}"
    end
  rescue StandardError
    nil
  end
  candidates.uniq!

  out = ''
  candidates.each do |probe_arg|
    next if probe_arg.to_s.empty?

    candidate_out = `SoapySDRUtil --probe="#{probe_arg.to_s.gsub('"', '\\"')}" 2>/dev/null`
    if candidate_out.to_s =~ /Sample rates:/i
      out = candidate_out
      break
    end
  end
  return [] if out.to_s.strip.empty?

  rates = []
  out.each_line do |line|
    next unless line =~ /Sample rates:\s*(.+)/i

    spec = Regexp.last_match(1).strip
    # Formats observed:
    #   "1, 2, 3, 4, 5, ..., 16, 17, 18, 19, 20 MSps"
    #   "0.25, 0.5, ..., 3.2 MSps"
    #   "250000, 1024000, 1800000, 2400000, 3200000 Hz"
    unit = :hz
    unit = :msps if spec =~ %r{MSps|MS/s|MHz}i
    unit = :ksps if spec =~ %r{kSps|kS/s|kHz}i

    nums = spec.scan(/(\d+(?:\.\d+)?)/).flatten.map(&:to_f)
    # When "...," range ellipsis is present with endpoints, expand integers.
    if spec.include?('...') && nums.length >= 2 && unit == :msps
      # HackRF style: 1,2,3,...,20 → integer Msps
      lo = nums.first
      hi = nums.last
      step = 1.0
      step = nums[1] - nums[0] if nums.length >= 3 && (nums[1] - nums[0]).positive?
      n = lo
      while n <= hi + 1e-9
        rates << (n * 1_000_000).round
        n += step
      end
    else
      nums.each do |n|
        hz = case unit
             when :msps then (n * 1_000_000).round
             when :ksps then (n * 1_000).round
             else n.round
             end
        rates << hz
      end
    end
  end
  rates.uniq.sort
rescue StandardError
  []
end

.disconnect(opts = {}) ⇒ Object

Supported Method Parameters

PWN::SDR::GQRX.disconnect( gqrx_sock: 'required - GQRX socket object returned from #connect method' )



1854
1855
1856
1857
1858
1859
1860
# File 'lib/pwn/sdr/gqrx.rb', line 1854

public_class_method def self.disconnect(opts = {})
  gqrx_sock = opts[:gqrx_sock]

  PWN::Plugins::Sock.disconnect(sock_obj: gqrx_sock) unless gqrx_sock.closed?
rescue StandardError => e
  raise e
end

.disconnect_udp(opts = {}) ⇒ Object

Supported Method Parameters

PWN::SDR::GQRX.disconnect_udp( udp_listener: 'required - UDP socket object returned from #listen_udp method' )



1785
1786
1787
1788
1789
1790
1791
1792
# File 'lib/pwn/sdr/gqrx.rb', line 1785

public_class_method def self.disconnect_udp(opts = {})
  udp_listener = opts[:udp_listener]
  raise 'ERROR: udp_sock is required!' if udp_listener.nil?

  PWN::Plugins::Sock.disconnect(sock_obj: udp_listener) unless udp_listener.closed?
rescue StandardError => e
  raise e
end

.fast_scan_range(opts = {}) ⇒ Object

Supported Method Parameters

fast_resp = PWN::SDR::GQRX.fast_scan_range( gqrx_sock: 'required - GQRX socket object', ranges: 'required - Array of {start_freq:, target_freq: }', sample_rate: 'optional - Set this to GQRX visible input sample rate (the span width)', nfft: 'optional - FFT size', avg: 'optional', capture_secs: 'optional', strength_lock: 'optional', min_snr_db: 'optional - Minimum SNR in dB above per-chunk noise floor to report (defaults to 12.0)', precision: 'optional - Band-plan channel raster; detections snapped to 10**(precision-1) Hz grid (defaults to 5)', min_bw_ratio: 'optional - Reject FFT peaks narrower than min_bw_ratio * plan bandwidth as spurs (defaults to 0.0 = off; half-power carrier BW is often << plan BW)', demodulator_mode: 'optional - Demodulator mode APPLIED to GQRX + attributed to detections (defaults to WFM)', bandwidth: 'optional - Passband bandwidth APPLIED to GQRX + attributed to detections (defaults to "200.000")', squelch: 'optional - Squelch level APPLIED to GQRX (defaults to strength_lock - 3.0)', audio_gain_db: 'optional - Audio gain in dB APPLIED to GQRX (defaults to 0.0)', rf_gain: 'optional - RF gain APPLIED to GQRX (defaults to 0.0)', intermediate_gain: 'optional - Intermediate gain APPLIED to GQRX (defaults to 32.0)', baseband_gain: 'optional - Baseband gain APPLIED to GQRX (defaults to 10.0)', decoder: 'optional - Decoder key (e.g. :gsm) to attribute to detections', location: 'optional - Location string for AI analysis', keep_spectrum: 'optional - if true return raw spectrum arrays too (large)', refine: 'optional - After panoramic FFT, re-walk each detection with traditional edge_detection + find_best_peak scoped around the candidate to lock the exact channel frequency (defaults to true)' )

Uses chunk-wise retuning where chunk = sample_rate so that the entire visible band (waterfall width) is captured via a single FFT each time rather than point-by-point hops. This yields near real-time panoramic coverage. Update rate is roughly (retune + capture + fft) per chunk.

Per-signal output shape is INTENTIONALLY IDENTICAL to #scan_range / #init_freq (:freq, :demodulator_mode, :bandwidth, :strength_db, :decoder, :squelch, :strength_lock, :iteration, :ai_analysis) so that #analyze_scan / #analyze_log and downstream decoders behave the same regardless of which scan mode produced the log. FFT-specific extras (:hz, :bw_hz, :snr_db, :prominence_db, :noise_floor_db, :chunk_center, :method) are appended for provenance.



2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
# File 'lib/pwn/sdr/gqrx.rb', line 2567

public_class_method def self.fast_scan_range(opts = {})
  gqrx_sock = opts[:gqrx_sock]
  raise 'gqrx_sock required' if gqrx_sock.nil?

  ranges = opts[:ranges]
  raise 'ranges required as array of hashes' unless ranges.is_a?(Array) && !ranges.empty?

  sr = (opts[:sample_rate] || 1_000_000).to_i
  nfft = (opts[:nfft] || 2048).to_i
  # avg/capture defaults lean fast — lock-hunt refine recovers weak-edge hits.
  avgs = (opts[:avg] || 6).to_i
  cap = (opts[:capture_secs] || 0.08).to_f
  strength_lock = (opts[:strength_lock] || -70.0).to_f
  min_snr_db = (opts[:min_snr_db] || 18.0).to_f
  keep_spec = opts[:keep_spectrum] ? true : false
  res_hz = sr / nfft.to_f
  demodulator_mode = opts[:demodulator_mode] ||= :WFM
  bandwidth = opts[:bandwidth] ||= '200.000'
  squelch = (opts[:squelch] || (strength_lock - 3.0)).to_f
  decoder = opts[:decoder]
  location = opts[:location] ||= 'United States'
  log_timestamp = Time.now.strftime('%Y-%m-%d')

  # ---- Band-plan-aware candidate validation -------------------------
  # `:precision` and `:bandwidth` come straight from
  # PWN::SDR::FrequencyAllocation.band_plans. They encode two facts the
  # raw FFT peak detector cannot know:
  #   1. The channel *raster* (step_hz = 10**(precision-1)) that real
  #      emitters are aligned to. Detections are snapped to this grid so
  #      the same station seen in overlapping chunks lands on ONE hz.
  #   2. The expected *occupied bandwidth* of a single legitimate
  #      emitter. Any FFT peak narrower than min_bw_ratio * plan_bw_hz
  #      is a spur / pilot / IMD product, not a channel; any two peaks
  #      closer than ~half a plan_bw_hz are sub-components of the SAME
  #      emitter (e.g. WFM stereo pilot @19k, RDS @57k) and are merged.
  precision = (opts[:precision] || 5).to_i
  precision = precision.clamp(1, 12)
  step_hz = 10**(precision - 1)
  plan_bw_hz = PWN::SDR.hz_to_i(freq: bandwidth)
  plan_bw_hz = step_hz if plan_bw_hz.zero?
  # min_bw_ratio is OPTIONAL and OFF by default (0.0). Half-power occupied
  # width of a real FLEX/POCSAG/NBFM carrier is often << channel assignment
  # (e.g. ~1–5 kHz vs plan 20 kHz), so a 0.30*plan floor rejected the
  # actual strongest peaks. Floor is always ≥ 1 FFT bin; callers wanting
  # spur rejection by width can still pass --min-bw-ratio.
  min_bw_ratio = (opts[:min_bw_ratio] || 0.0).to_f
  min_bw_hz = [res_hz.ceil, 1].max
  min_bw_hz = [min_bw_hz, (plan_bw_hz * min_bw_ratio).to_i].max if min_bw_ratio.positive?

  range_str = ranges.map do |rr|
    a = PWN::SDR.hz_to_s(freq: PWN::SDR.hz_to_i(freq: rr[:start_freq]))
    b = PWN::SDR.hz_to_s(freq: PWN::SDR.hz_to_i(freq: rr[:target_freq]))
    "#{a}-#{b}"
  end.join('_')
  scan_log = opts[:scan_log] ||= "/tmp/pwn_sdr_gqrx_scan_#{range_str}_#{log_timestamp}.json"

  ts_start = Time.now.strftime('%Y-%m-%d %H:%M:%S%z')
  detected = []
  all_specs = [] if keep_spec

  # ---- Panoramic capture radio setup --------------------------------
  # CRITICAL: GQRX IQRECORD dumps the *demodulator IF* stream, not the
  # raw ADC. Forcing the band-plan demod/passband here (e.g. FM / 20 kHz
  # for pager_flex) collapsed the panoramic view to a 20 kHz keyhole and
  # destroyed edge/BW detection. Capture always uses RAW with a passband
  # equal to sample_rate so each chunk really spans `sr` Hz. Band-plan
  # demod/bandwidth/squelch are applied later (during refine / analyze)
  # and still attributed onto every detection hash for decoder re-tunes.
  mode_str = demodulator_mode.to_s.upcase
  passband_hz = plan_bw_hz # decoder IF — applied only in refine phase
  capture_mode = 'RAW'
  capture_passband_hz = sr
  audio_gain_db = (opts[:audio_gain_db] || 0.0).to_f
  rf_gain = (opts[:rf_gain] || 0.0).to_f
  intermediate_gain = (opts[:intermediate_gain] || 32.0).to_f
  baseband_gain = (opts[:baseband_gain] || 10.0).to_f
  user_strength_lock = !opts[:strength_lock].nil? # honour explicit -S (driver may pass key:nil)

  puts '-' * 86
  puts '[FAST-SCAN] SESSION PARAMS >> panoramic capture + deferred band-plan IF:'
  puts "  capture mode     : #{capture_mode} #{PWN::SDR.hz_to_s(freq: capture_passband_hz)} Hz  (full sample_rate span)"
  puts "  band-plan mode   : #{mode_str} #{PWN::SDR.hz_to_s(freq: passband_hz)} Hz  (applied at refine / decoder)"
  puts "  squelch (L SQL)  : #{squelch} dBFS"
  puts "  strength_lock    : #{strength_lock} dBFS  (S-meter edge gate; auto-calibrated unless -S given)"
  puts "  audio_gain (AF)  : #{audio_gain_db} dB"
  puts "  rf_gain          : #{rf_gain}"
  puts "  intermediate_gain: #{intermediate_gain}"
  puts "  baseband_gain    : #{baseband_gain}"
  puts "  decoder          : #{decoder.inspect}"
  puts "  raster/precision : #{PWN::SDR.hz_to_s(freq: step_hz)} Hz (precision #{precision})"
  puts "  plan_bw/min_bw   : #{PWN::SDR.hz_to_s(freq: plan_bw_hz)} Hz / min occupied >= #{PWN::SDR.hz_to_s(freq: min_bw_hz)} Hz (ratio #{min_bw_ratio})"
  puts "  min_snr          : #{min_snr_db} dB  (FFT scale, not S-meter)"
  puts "  sample_rate/nfft : #{sr} SPS / #{nfft}"
  puts '-' * 86

  # Floor squelch for capture so we never mute I/Q while sweeping.
  cmd(
    gqrx_sock: gqrx_sock,
    cmd: 'L SQL -150.0',
    resp_ok: 'RPRT 0'
  )

  # Disable RDS during the panoramic scan.
  begin
    cmd(gqrx_sock: gqrx_sock, cmd: 'U RDS 0', resp_ok: 'RPRT 0')
  rescue StandardError
    nil
  end

  # RAW + sample_rate passband = full panoramic IF for IQRECORD.
  cmd(
    gqrx_sock: gqrx_sock,
    cmd: "M #{capture_mode} #{capture_passband_hz}",
    resp_ok: 'RPRT 0'
  )

  cmd(
    gqrx_sock: gqrx_sock,
    cmd: "L AF #{audio_gain_db}",
    resp_ok: 'RPRT 0'
  )

  cmd(
    gqrx_sock: gqrx_sock,
    cmd: "L RF_GAIN #{rf_gain}",
    resp_ok: 'RPRT 0'
  )

  cmd(
    gqrx_sock: gqrx_sock,
    cmd: "L IF_GAIN #{intermediate_gain}",
    resp_ok: 'RPRT 0'
  )

  cmd(
    gqrx_sock: gqrx_sock,
    cmd: "L BB_GAIN #{baseband_gain}",
    resp_ok: 'RPRT 0'
  )

  # Brief settle so the backend reconfigures IF filter around RAW span.
  sleep 0.20

  begin
    applied_mode = cmd(gqrx_sock: gqrx_sock, cmd: 'm').to_s.strip
    puts "[FAST-SCAN] GQRX capture mode/passband='#{applied_mode}' (expect RAW #{capture_passband_hz})"
  rescue StandardError => e
    puts "[FAST-SCAN] WARNING: could not read back mode (#{e.class}: #{e.message})"
  end

  ranges.each do |r|
    s_hz = PWN::SDR.hz_to_i(freq: r[:start_freq])
    t_hz = PWN::SDR.hz_to_i(freq: r[:target_freq])
    dir = t_hz >= s_hz ? 1 : -1
    # Soft chunk-edge guard (also applied post-snapshot). Cap so a
    # wide plan (fm_radio 200 kHz) at modest sample_rate (1 Msps) does
    # not eat the entire usable span.
    edge_floor = [plan_bw_hz, 2 * step_hz, 1_000].max
    edge_floor = [edge_floor, (sr * 0.12).to_i].min # never >12% of span
    edge_guard_hz = [(sr * 0.05).to_i, edge_floor].max
    usable = sr - (2 * edge_guard_hz)
    usable = [usable, (sr * 0.50).to_i].max
    # Step so successive usable regions OVERLAP by ~15% (was fixed
    # 0.85*sr, which for FM left ~350 kHz holes per chunk at 1 Msps).
    step = (usable * 0.85).to_i
    step = [step, step_hz, 50_000].max
    step = sr if step > sr

    puts "[FAST-SCAN] Panoramic covering #{PWN::SDR.hz_to_s(freq: s_hz)}..#{PWN::SDR.hz_to_s(freq: t_hz)} using #{sr} SPS chunks (step #{PWN::SDR.hz_to_s(freq: step)}, edge_guard=#{PWN::SDR.hz_to_s(freq: edge_guard_hz)}, usable≈#{PWN::SDR.hz_to_s(freq: usable)})"

    h = s_hz
    while dir.positive? ? (h <= t_hz) : (h >= t_hz)
      # retune to put this chunk in the visible IF
      tune_to(gqrx_sock: gqrx_sock, hz: h)
      sleep 0.08 # allow GQRX / SDR to settle the IF filter & AGC etc.

      snap = get_spectrum_snapshot(
        gqrx_sock: gqrx_sock,
        center_freq: h,
        sample_rate: sr,
        nfft: nfft,
        avg: avgs,
        capture_secs: cap,
        strength_offset_db: opts[:strength_offset_db],
        channel_bw_hz: plan_bw_hz,
        step_hz: step_hz
      )

      all_specs << snap if keep_spec

      sigs = snap[:signals] || []
      # Gate on SNR (scale-independent) rather than absolute power_db,
      # because 10*log10(|FFT|^2) is uncalibrated and cannot be compared
      # against the -70 dBFS S-meter strength_lock without a
      # user-supplied strength_offset_db. NO fallback: a quiet chunk
      # correctly contributes zero detections.
      # Upper BW bound: half-power estimate should not exceed ~2× plan.
      # Stops continuum / multi-carrier blobs from surviving as one "signal".
      max_bw_hz = [(plan_bw_hz * 2), (step_hz * 8), min_bw_hz].max
      # edge_guard_hz / usable computed once per range above so the
      # step and post-snapshot acceptance region stay consistent.
      chunk_lo = h - (sr / 2) + edge_guard_hz
      chunk_hi = h + (sr / 2) - edge_guard_hz
      # Also clamp to the requested scan range.
      range_lo = [s_hz, t_hz].min
      range_hi = [s_hz, t_hz].max

      sigs.each do |sig|
        next if sig[:snr_db] && sig[:snr_db] < min_snr_db

        raw_candidate_hz = (sig[:hz] || sig[:freq_hz]).to_i
        next if raw_candidate_hz < range_lo || raw_candidate_hz > range_hi
        next if raw_candidate_hz < chunk_lo || raw_candidate_hz > chunk_hi
        # Require decent prominence when present (noise continuum has low prom).
        next if sig[:prominence_db] && sig[:prominence_db].to_f < 8.0

        # NOTE: strength_lock is an S-meter (dBFS) gate. FFT power_db is
        # uncalibrated 10*log10(|X|^2) and MUST NOT be compared to it
        # unless the caller supplied strength_offset_db. Skip that gate
        # for panoramic detections — min_snr_db is the correct filter.
        next if opts[:strength_offset_db] && sig[:power_db] && sig[:power_db] < strength_lock
        # Band-plan width gates (relative half-power BW estimator).
        next if sig[:bw_hz] && sig[:bw_hz] < min_bw_hz
        next if sig[:bw_hz] && sig[:bw_hz] > max_bw_hz

        raw_hz = sig[:hz] || sig[:freq_hz]
        # Snap to the band-plan channel raster so the same emitter seen
        # in multiple overlapping chunks / at multiple sub-peaks lands
        # on ONE canonical frequency before dedup.
        hz = ((raw_hz.to_f / step_hz).round * step_hz).to_i
        # Shape MUST match #scan_range / #init_freq freq_obj so that
        # analyze_scan / analyze_log and downstream decoders work
        # identically regardless of which scan mode produced the log.
        detected << {
          freq: PWN::SDR.hz_to_s(freq: hz),
          demodulator_mode: demodulator_mode,
          bandwidth: bandwidth,
          strength_db: sig[:power_db].to_f.round(2),
          decoder: decoder,
          squelch: squelch,
          strength_lock: strength_lock,
          audio_gain_db: audio_gain_db,
          rf_gain: rf_gain,
          intermediate_gain: intermediate_gain,
          baseband_gain: baseband_gain,
          iteration: 1,
          hz: hz,
          raw_peak_hz: raw_hz.to_i,
          bw_hz: sig[:bw_hz].to_i,
          snr_db: sig[:snr_db].to_f.round(2),
          prominence_db: sig[:prominence_db].to_f.round(2),
          noise_floor_db: sig[:noise_floor_db].to_f.round(2),
          chunk_center: PWN::SDR.hz_to_s(freq: h),
          method: :fast_spectrum_sdrangel_like
        }
      end
      h += step * dir
    end
  end

  # Cross-chunk / intra-emitter merge. A single legitimate emitter
  # occupies ~plan_bw_hz, so ANY peaks within half that width (or one
  # raster step, or half the *measured* width, whichever is largest) are
  # the same channel. Keep the highest-SNR representative.
  detected.sort_by! { |d| d[:hz] }
  merged = []
  detected.each do |d|
    prev = merged.last
    tol = fft_plan_geometry(
      plan_bw_hz: plan_bw_hz,
      step_hz: step_hz,
      res_hz: res_hz,
      measured_bw_hz: d[:bw_hz].to_i
    )[:merge_tol_hz]
    if prev && (d[:hz] - prev[:hz]).abs <= tol
      merged[-1] = d if (d[:snr_db] || -999) > (prev[:snr_db] || -999)
    else
      merged << d
    end
  end
  detected = merged

  # ---- Exact-channel refine pass ------------------------------------
  # Preliminary FFT peaks are only as precise as the bin resolution
  # (sample_rate/nfft) and the band-plan raster snap. For decoding we
  # want the true channel centre, so re-walk each survivor with the
  # traditional S-meter edge_detection + find_best_peak pipeline,
  # scoped to a tight window around the FFT estimate. Opt-out via
  # refine: false for pure-panorama speed.
  refine = opts.fetch(:refine, true)
  if refine && !detected.empty?
    # Switch GQRX into the band-plan demod/passband BEFORE S-meter
    # walks — edge_detection / find_best_peak read l STRENGTH which is
    # only meaningful inside the decoder IF (FM 20 kHz for FLEX, etc.).
    begin
      cmd(
        gqrx_sock: gqrx_sock,
        cmd: "M #{mode_str} #{passband_hz}",
        resp_ok: 'RPRT 0'
      )
      cmd(
        gqrx_sock: gqrx_sock,
        cmd: "L SQL #{squelch}",
        resp_ok: 'RPRT 0'
      )
      sleep 0.15
    rescue StandardError => e
      puts "[FAST-SCAN] WARNING: could not apply band-plan IF for refine (#{e.class}: #{e.message})"
    end

    # Auto-calibrate strength_lock against the *live* S-meter noise floor
    # unless the user passed an explicit -S/--strength-lock. The default
    # -70 dBFS is meaningless across SDRs / bands (live FLEX band here
    # sits at ≈ -55…-83 dBFS); without this, edge walks either flood the
    # entire band or refuse to engage at all.
    unless user_strength_lock
      seed_hz_for_nf = detected.map { |d| d[:hz].to_i }.reject(&:zero?)
      seed_hz_for_nf = [PWN::SDR.hz_to_i(freq: ranges.first[:start_freq])] if seed_hz_for_nf.empty?
      nf_samples = []
      seed_hz_for_nf.first(5).each do |hz|
        # Probe a few offsets off-channel to estimate quiet floor.
        [-3 * plan_bw_hz, -plan_bw_hz, plan_bw_hz, 3 * plan_bw_hz].each do |off|
          ph = hz + off
          next if ph <= 0

          tune_to(gqrx_sock: gqrx_sock, hz: ph)
          3.times do
            nf_samples << cmd(gqrx_sock: gqrx_sock, cmd: 'l STRENGTH').to_f
            sleep 0.02
          end
        end
      end
      if nf_samples.any?
        nf_samples.sort!
        live_nf = nf_samples[nf_samples.length / 2] # median
        auto_lock = (live_nf + 8.0).round(1)
        puts "[FAST-SCAN] auto strength_lock: live S-meter nf≈#{live_nf.round(1)} dBFS → lock=#{auto_lock} dBFS (was #{strength_lock})"
        strength_lock = auto_lock
        # Keep squelch a few dB under the lock for any later decoder use.
        squelch = strength_lock - 3.0 if squelch >= strength_lock || opts[:squelch].nil?
        detected.each do |d|
          d[:strength_lock] = strength_lock
          d[:squelch] = squelch
        end
      end
    end

    # Default refine is lock-hunt (S-meter probe ±N raster steps) —
    # ~5–10× faster than local-FFT zoom and more accurate on FM where
    # panoramic centroids often land one channel off. Pass
    # refine_mode: :fft for the legacy high-res FFT zoom, or
    # refine_mode: :hybrid to run both.
    refine_mode = opts.fetch(:refine_mode, :lock)
    detected = refine_detections(
      gqrx_sock: gqrx_sock,
      detections: detected,
      precision: precision,
      step_hz: step_hz,
      strength_lock: strength_lock,
      plan_bw_hz: plan_bw_hz,
      demodulator_mode: demodulator_mode,
      bandwidth: bandwidth,
      squelch: squelch,
      refine_mode: refine_mode
    )
  elsif !refine
    puts '[FAST-SCAN] refine:false — skipping iterative edge/peak refinement'
  end

  # Final in-range gate (refine can drift a little past the requested
  # edges via local zoom). Drop anything outside the union of ranges.
  if detected.any?
    global_lo = ranges.map { |rr| PWN::SDR.hz_to_i(freq: rr[:start_freq]) }.min
    global_hi = ranges.map { |rr| PWN::SDR.hz_to_i(freq: rr[:target_freq]) }.max
    before = detected.length
    detected.select! { |d| d[:hz].to_i.between?(global_lo, global_hi) }
    puts "[FAST-SCAN] dropped #{before - detected.length} out-of-range detection(s) after refine" if detected.length != before
  end

  # Attach AI analysis only when explicitly requested. LLM calls per
  # detection dominate wall-clock on dense bands (fm_radio ~25 hits) and
  # defeat the point of panoramic/FFT scanning. Opt-in via ai_analysis:true
  # (iterative #scan_range still does AI by default for parity with its
  # slower, fewer-hit flow).
  do_ai = opts[:ai_analysis] ? true : false
  detected.each do |freq_obj|
    puts "\n**** Detected Signal ****"
    if do_ai
      begin
        ai_analysis = PWN::AI::Agent::GQRX.analyze(
          request: freq_obj.to_json,
          location: location
        )
        freq_obj[:ai_analysis] = ai_analysis unless ai_analysis.nil?
      rescue StandardError
        # AI analysis is best-effort; never let it kill the scan.
        nil
      end
    end
    puts JSON.pretty_generate(freq_obj)
    puts '-' * 86
  end

  meta = {
    sample_rate_used: sr,
    nfft: nfft,
    precision: precision,
    plan_bw_hz: plan_bw_hz,
    demodulator_mode: demodulator_mode,
    bandwidth: bandwidth,
    squelch: squelch,
    strength_lock: strength_lock,
    audio_gain_db: audio_gain_db,
    rf_gain: rf_gain,
    intermediate_gain: intermediate_gain,
    baseband_gain: baseband_gain,
    decoder: decoder,
    method: :fast_scan_range
  }
  meta[:spectrums] = all_specs if keep_spec

  # Single write through log_signals so top-level keys always match
  # the iterative #scan_range schema (plus FFT-only provenance).
  log_signals(
    signals_detected: detected,
    timestamp_start: ts_start,
    scan_log: scan_log,
    meta: meta
  )
rescue StandardError => e
  raise e
end

.get_spectrum_snapshot(opts = {}) ⇒ Object

Author(s)

0day Inc. support@0dayinc.com



2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
# File 'lib/pwn/sdr/gqrx.rb', line 2216

public_class_method def self.get_spectrum_snapshot(opts = {})
  gqrx_sock = opts[:gqrx_sock]
  raise 'ERROR: gqrx_sock is required!' if gqrx_sock.nil?

  center_freq = opts[:center_freq]
  center_freq ||= cmd(gqrx_sock: gqrx_sock, cmd: 'f')
  center_hz = PWN::SDR.hz_to_i(freq: center_freq)

  sample_rate = (opts[:sample_rate] || 1_000_000).to_i
  nfft = (opts[:nfft] || 2048).to_i
  avg = (opts[:avg] || 8).to_i
  capture_secs = (opts[:capture_secs] || 0.10).to_f
  strength_offset_db = (opts[:strength_offset_db] || 0.0).to_f

  num_samples = (sample_rate * capture_secs).to_i
  num_samples = [num_samples, nfft].max
  num_samples = ((num_samples.to_f / nfft).ceil * nfft).to_i

  puts "[*] Capturing ~#{format('%.3f', capture_secs)}s I/Q (#{num_samples} samples @ #{sample_rate} SPS) => #{sample_rate / 1_000_000.0} MHz instantaneous span"

  # Start a fresh short IQ recording for snapshot (entire visible band at once)
  begin
    cmd(gqrx_sock: gqrx_sock, cmd: 'U IQRECORD 0', resp_ok: 'RPRT 0')
  rescue StandardError
    nil
  end
  sleep 0.02
  cmd(gqrx_sock: gqrx_sock, cmd: 'U IQRECORD 1', resp_ok: 'RPRT 0')
  sleep(capture_secs + 0.06)
  cmd(gqrx_sock: gqrx_sock, cmd: 'U IQRECORD 0', resp_ok: 'RPRT 0')

  # Newest raw I/Q produced by GQRX (usually ~/gqrx_*.raw , float32 I/Q interleaved @ sample_rate)
  home = Dir.home
  iq_raw_file = Dir.glob("#{home}/gqrx_*.raw").max_by { |f| File.mtime(f) }
  raise "ERROR: No GQRX .raw file found after capture (looked in #{home})" unless iq_raw_file && File.exist?(iq_raw_file)

  # Read tail of most recent bytes
  total_bytes = num_samples * 8 # float32 * 2 channels
  fsize = File.size(iq_raw_file)
  start_pos = [0, fsize - total_bytes].max
  raw_bytes = File.binread(iq_raw_file, total_bytes, start_pos)

  # ---- FFT (FFTW3 when available, pure-Ruby Cooley-Tukey fallback) ----
  raise 'ERROR: I/Q read empty or short' if raw_bytes.nil? || raw_bytes.bytesize < 8

  # GQRX raw I/Q: little-endian float32 interleaved I,Q,I,Q,...
  floats = raw_bytes.unpack('e*')
  n_iq = [floats.length / 2, num_samples].min
  # Keep flat interleaved I/Q for FFTW path; Complex array for Ruby path.
  raise "ERROR: nfft (#{nfft}) must be a power of two" unless nfft.nobits?(nfft - 1)

  two_pi = 2.0 * Math::PI
  hann = Array.new(nfft) { |k| 0.5 * (1.0 - Math.cos(two_pi * k / (nfft - 1))) }
  hop = [nfft / 2, 1].max
  use_fftw = begin
    defined?(PWN::FFI::FFTW) && PWN::FFI::FFTW.available?
  rescue StandardError
    false
  end

  specs = []
  if use_fftw
    # Native complex DFT via libfftw3f — orders of magnitude faster than
    # pure-Ruby butterflies at nfft>=2048 / avg>=4. Flat interleaved
    # windowed block is handed to cfft; we fftshift |X|^2 ourselves.
    pos = 0
    while (pos + nfft) <= n_iq && specs.length < avg
      blk = Array.new(2 * nfft)
      nfft.times do |k|
        base = 2 * (pos + k)
        w = hann[k]
        blk[2 * k] = floats[base].to_f * w
        blk[(2 * k) + 1] = floats[base + 1].to_f * w
      end
      begin
        pairs = PWN::FFI::FFTW.cfft(iq: blk, n: nfft)
        half = nfft / 2
        # fftshift: out[0:half]=in[half:n], out[half:n]=in[0:half]
        # → bins aligned -sr/2 .. +sr/2 matching pure-Ruby path.
        shifted_pwr = Array.new(nfft)
        (0...half).each do |i|
          re, im = pairs[i + half]
          shifted_pwr[i] = (re * re) + (im * im)
          re, im = pairs[i]
          shifted_pwr[i + half] = (re * re) + (im * im)
        end
        specs << shifted_pwr
      rescue StandardError
        use_fftw = false
        break
      end
      pos += hop
    end
  end

  unless use_fftw && !specs.empty?
    # Pure-Ruby complex FFT fallback (radix-2 Cooley-Tukey).
    iq = Array.new(n_iq) { |i| Complex(floats[2 * i], floats[(2 * i) + 1]) }
    log2n = Math.log2(nfft).to_i
    fft_proc = lambda do |x|
      n = x.length
      j = 0
      (0...(n - 1)).each do |i|
        x[i], x[j] = x[j], x[i] if i < j
        k = n >> 1
        while k <= j
          j -= k
          k >>= 1
        end
        j += k
      end
      (1..log2n).each do |stage|
        m = 1 << stage
        half = m >> 1
        wm = Complex.polar(1.0, -two_pi / m)
        (0...n).step(m) do |kk|
          w = Complex(1.0, 0.0)
          (0...half).each do |jj|
            t = w * x[kk + jj + half]
            u = x[kk + jj]
            x[kk + jj] = u + t
            x[kk + jj + half] = u - t
            w *= wm
          end
        end
      end
      x
    end

    specs = []
    pos = 0
    while pos + nfft <= iq.length && specs.length < avg
      blk = Array.new(nfft) { |k| iq[pos + k] * hann[k] }
      sp = fft_proc.call(blk)
      half = nfft / 2
      shifted = sp[half, nfft - half] + sp[0, half]
      specs << shifted.map(&:abs2)
      pos += hop
    end
    if specs.empty?
      blk = Array.new(nfft) do |k|
        (k < iq.length ? iq[k] : Complex(0.0, 0.0)) * hann[k]
      end
      sp = fft_proc.call(blk)
      half = nfft / 2
      shifted = sp[half, nfft - half] + sp[0, half]
      specs << shifted.map(&:abs2)
    end
  end

  avg_pwr = Array.new(nfft, 0.0)
  specs.each { |ps| ps.each_with_index { |v, i| avg_pwr[i] += v } }
  cnt = specs.length.to_f
  avg_pwr.map! { |v| v / cnt }

  db = avg_pwr.map { |v| (10.0 * Math.log10(v + 1e-12)) + strength_offset_db }

  # fftshift(fftfreq(nfft, 1/sr)) => bins from -sr/2 .. +sr/2 (exclusive), step sr/nfft
  res_hz = sample_rate / nfft.to_f
  freq_off = Array.new(nfft) { |i| (i - (nfft / 2)) * res_hz }

  bins_out = Array.new(nfft) do |ii|
    fh = (center_hz + freq_off[ii]).to_i
    {
      bin: ii,
      freq_hz: fh,
      freq: PWN::SDR.hz_to_s(freq: fh),
      power_db: db[ii].round(2)
    }
  end

  # Null DC / LO-leakage bin and band-edge guard bins BEFORE detection so
  # they neither skew the noise-floor estimate nor register as phantom
  # signals at the centre of every retune step.
  guard = [(nfft * 0.02).to_i, 2].max
  dc = nfft / 2
  sorted_db = db.sort
  median_nf = sorted_db[sorted_db.length / 2].to_f
  db[dc] = median_nf
  (0...guard).each do |gi|
    db[gi] = median_nf
    db[nfft - 1 - gi] = median_nf
  end

  # Noise floor: median of dB (robust). Callers may supply expected
  # channel_bw_hz so min_dist tracks real channel spacing (pager_flex
  # 20 kHz / fm_radio 200 kHz) instead of a fixed 6 kHz heuristic that
  # over-fragments wide carriers and under-separates dense narrow ones.
  noise_floor = median_nf
  channel_bw_hz = (opts[:channel_bw_hz] || opts[:plan_bw_hz] || 0).to_f
  channel_bw_hz = 0.0 if channel_bw_hz.negative?

  # Peak picker (relative thresholds only — absolute S-meter dBFS is
  # meaningless on uncalibrated 10*log10(|FFT|^2)):
  #   height   : median_nf + height_db (default 12)
  #   prom     : >= prom_thr (default 8)
  #   min_dist : plan-parametric via #fft_plan_geometry — half channel /
  #              raster / step-aware floor, converted to bins by res_hz.
  # Callers may tighten with opts[:peak_height_db]/[:peak_prom_db]/
  # opts[:step_hz] (raster) for denser narrowband plans.
  height_db = (opts[:peak_height_db] || 12.0).to_f
  prom_thr = (opts[:peak_prom_db] || 8.0).to_f
  height_thr = noise_floor + height_db
  step_for_geo = (opts[:step_hz] || opts[:raster_hz] || 0).to_f
  geo = fft_plan_geometry(
    plan_bw_hz: channel_bw_hz,
    step_hz: step_for_geo,
    res_hz: res_hz
  )
  sep_hz = geo[:sep_hz]
  min_dist = geo[:min_dist_bins]

  candidates = []
  (1...(nfft - 1)).each do |i|
    next unless db[i] >= height_thr
    next unless db[i] > db[i - 1] && db[i] >= db[i + 1]

    # prominence: peak - highest of the two side-valley minima toward the
    # nearest higher-or-equal neighbour (scipy.signal.peak_prominences)
    left_min = db[i]
    li = i - 1
    while li >= 0 && db[li] <= db[i]
      left_min = db[li] if db[li] < left_min
      li -= 1
    end
    right_min = db[i]
    ri = i + 1
    while ri < nfft && db[ri] <= db[i]
      right_min = db[ri] if db[ri] < right_min
      ri += 1
    end
    prom = db[i] - [left_min, right_min].max
    next if prom < prom_thr

    candidates << { idx: i, pwr: db[i], prom: prom }
  end

  # Enforce minimum distance between peaks (keep strongest first)
  candidates.sort_by! { |c| -c[:pwr] }
  selected = []
  candidates.each do |c|
    selected << c unless selected.any? { |s2| (s2[:idx] - c[:idx]).abs < min_dist }
  end
  selected.sort_by! { |c| c[:idx] }

  # Occupied-BW edge walk is RELATIVE TO THE PEAK, never to the global
  # noise floor. Walking down to noise+3.5 dB on a dense paging band
  # (or any band with elevated continuum / many neighbours) floods the
  # whole lobe and reports hundreds of kHz of "occupied" bandwidth —
  # which then breaks min_bw_ratio filtering, merge tolerance, and the
  # refine window. Use a -6 dB from-peak contour (≈ half-power / 3 dB
  # each side) with a hard cap of ~2 * channel_bw when known.
  half_pwr_drop_db = 6.0
  # Cap occupied-BW walk to ~1 plan_bw each side of peak (plan-parametric).
  max_half_bins = geo[:max_half_bins]

  signals = selected.map do |c|
    p = c[:idx]
    edge_rel = c[:pwr] - half_pwr_drop_db
    l = p
    l -= 1 while l.positive? && (p - l) < max_half_bins && db[l - 1] >= edge_rel
    r = p
    r += 1 while r < (nfft - 1) && (r - p) < max_half_bins && db[r + 1] >= edge_rel
    bw_hz = ([r - l + 1, 1].max * res_hz).to_i

    # Power-weighted centroid over the -6 dB lobe → sub-bin centre that
    # lands much closer to the true channel than the peak bin alone
    # (critical for precision-4 / 1 kHz FLEX raster snaps).
    lin_sum = 0.0
    mom_sum = 0.0
    (l..r).each do |bi|
      lin = 10.0**(db[bi] / 10.0)
      lin_sum += lin
      mom_sum += lin * bi
    end
    centroid_bin = lin_sum.positive? ? (mom_sum / lin_sum) : p.to_f
    center = (center_hz + ((centroid_bin - (nfft / 2)) * res_hz)).round
    {
      hz: center,
      freq: PWN::SDR.hz_to_s(freq: center),
      power_db: c[:pwr].round(2),
      noise_floor_db: noise_floor.round(2),
      bw_hz: bw_hz,
      snr_db: (c[:pwr] - noise_floor).round(2),
      peak_bin: p,
      prominence_db: c[:prom].round(2)
    }
  end

  # NOTE: no fallback. A quiet chunk correctly returns signals: [].

  {
    center_freq_hz: center_hz,
    center_freq: PWN::SDR.hz_to_s(freq: center_hz),
    sample_rate: sample_rate,
    visible_span_hz: sample_rate,
    nfft: nfft,
    avg: avg,
    resolution_hz: res_hz.round(2),
    samples: n_iq,
    capture_secs: capture_secs,
    spectrum: bins_out,
    signals: signals,
    noise_floor_db: noise_floor.round(2),
    timestamp: Time.now.strftime('%Y-%m-%d %H:%M:%S%z')
  }
rescue StandardError => e
  begin
    cmd(gqrx_sock: gqrx_sock, cmd: 'U IQRECORD 0', resp_ok: 'RPRT 0')
  rescue StandardError
    nil
  end
  raise e
end

.helpObject

Display Usage for this Module



3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
# File 'lib/pwn/sdr/gqrx.rb', line 3008

public_class_method def self.help
  puts <<~USAGE
    USAGE:
      gqrx_sock = #{self}.connect(
        target: 'optional - GQRX target IP address (defaults to 127.0.0.1)',
        port: 'optional - GQRX target port (defaults to 7356)'
      )

      gqrx_resp = #{self}.cmd(
        gqrx_sock: 'required - GQRX socket object returned from #connect method',
        cmd: 'required - GQRX command to send',
        resp_ok: 'optional - Expected OK response (defaults to nil / no check)'
      )

      freq_obj = #{self}.init_freq(
        gqrx_sock: 'required - GQRX socket object returned from #connect method',
        freq: 'required - Frequency to set',
        precision: 'optional - Frequency step precision (number of digits; defaults to 6)',
        demodulator_mode: 'optional - Demodulator mode (defaults to WFM)',
        bandwidth: 'optional - Bandwidth (defaults to "200.000")',
        decoder: 'optional - Decoder key (e.g., :gsm / :rds) to start live decoding',
        interactive: 'optional - false → decoder.sample Hash (default true = TTY decode)',
        settle_secs: 'optional - seconds for decoder.sample (RDS default 8)',
        suppress_details: 'optional - Boolean to include extra frequency details in return hash (defaults to false)',
        keep_alive: 'optional - Boolean to keep GQRX connection alive after method completion (defaults to false)'
      )

      scan_resp = #{self}.scan_range(
        gqrx_sock: 'required - GQRX socket object returned from #connect method',
        ranges: 'required - Array of Hash objects with :start_freq and :target_freq keys defining scan ranges',
        demodulator_mode: 'optional - Demodulator mode (e.g. WFM, AM, FM, USB, LSB, RAW, CW, RTTY / defaults to WFM)',
        bandwidth: 'optional - Bandwidth in Hz (Defaults to "200.000")',
        precision: 'optional - Precision (Defaults to 1)',
        strength_lock: 'optional - Strength lock (defaults to -70.0)',
        squelch: 'optional - Squelch level (defaults to strength_lock - 3.0)',
        audio_gain_db: 'optional - Audio gain in dB (defaults to 0.0)',
        rf_gain: 'optional - RF gain (defaults to 0.0)',
        intermediate_gain: 'optional - Intermediate gain (defaults to 32.0)',
        baseband_gain: 'optional - Baseband gain (defaults to 10.0)',
        keep_looping: 'optional - Boolean to keep scanning indefinitely (defaults to false)',
        scan_log: 'optional - Path to save detected signals log (defaults to /tmp/pwn_sdr_gqrx_scan_<start_freq>-<target_freq>_<timestamp>.json)',
        location: 'optional - Location string to include in AI analysis (e.g., "New York, NY", 90210, GPS coords, etc.)'
      )

      snapshot = #{self}.get_spectrum_snapshot(
        gqrx_sock: 'required - GQRX socket object returned from #connect method',
        center_freq: 'optional - Center frequency (Hz) for snapshot (defaults to current tuned freq)',
        sample_rate: 'optional - Instantaneous bandwidth / sample rate in Hz (defaults to 1_000_000)',
        nfft: 'optional - FFT bin size (defaults to 2048)',
        avg: 'optional - Number of FFT averages (defaults to 8)',
        capture_secs: 'optional - Duration of I/Q capture in seconds (defaults to 0.10)',
        strength_offset_db: 'optional - Add this many dB to all power levels (defaults to 0.0)'
      )

      fast_scan_resp = #{self}.fast_scan_range(
        gqrx_sock: 'required - GQRX socket object returned from #connect method',
        ranges: 'required - Array of Hash objects with :start_freq and :target_freq keys defining scan ranges',
        sample_rate: 'optional - Chunk size / visible span in Hz (defaults to 1_000_000)',
        nfft: 'optional - FFT size (defaults to 2048)',
        avg: 'optional - Number of averages (defaults to 8)',
        capture_secs: 'optional - Seconds of capture per chunk (defaults to 0.10)',
        strength_lock: 'optional - Minimum signal strength in dBFS to report (defaults to -70.0; only meaningful with strength_offset_db calibration)',
        min_snr_db: 'optional - Minimum SNR in dB above per-chunk noise floor to report (defaults to 12.0)',
        precision: 'optional - Band-plan channel raster; detections snapped to 10**(precision-1) Hz grid (defaults to 5)',
        min_bw_ratio: 'optional - Reject FFT peaks narrower than min_bw_ratio * plan bandwidth as spurs (defaults to 0.0 = off; half-power carrier BW is often << plan BW)',
        demodulator_mode: 'optional - Demodulator mode APPLIED to GQRX + attributed to detections (defaults to WFM)',
        bandwidth: 'optional - Passband bandwidth APPLIED to GQRX + attributed (defaults to "200.000")',
        squelch: 'optional - Squelch level in dBFS APPLIED to GQRX (defaults to strength_lock - 3.0)',
        audio_gain_db: 'optional - Audio gain in dB APPLIED to GQRX (defaults to 0.0)',
        rf_gain: 'optional - RF gain APPLIED to GQRX (defaults to 0.0)',
        intermediate_gain: 'optional - Intermediate gain APPLIED to GQRX (defaults to 32.0)',
        baseband_gain: 'optional - Baseband gain APPLIED to GQRX (defaults to 10.0)',
        decoder: 'optional - Decoder key (e.g. :gsm) to attribute to each detection',
        location: 'optional - Location string to include in AI analysis',
        keep_spectrum: 'optional - If true, include full spectrum data in result (can be large, defaults to false)',
        refine: 'optional - After panoramic FFT, re-walk each detection with traditional edge_detection + find_best_peak scoped around the candidate to lock the exact channel frequency (defaults to true)',
        strength_offset_db: 'optional - Add this many dB to all power levels (defaults to 0.0)',
        scan_log: 'optional - Path to save detected signals log (defaults to /tmp/pwn_sdr_gqrx_scan_<start_freq>-<target_freq>_<timestamp>.json)'
      )

      #{self}.analyze_scan(
        scan_resp: 'required - Scan response object from #scan_range or #fast_scan_range method',
        target: 'optional - GQRX target IP address (defaults to 127.0.0.1)',
        port: 'optional - GQRX target port (defaults to 7356)'
      )

      #{self}.analyze_log(
        scan_log: 'required - Path to signals log file',
        target: 'optional - GQRX target IP address (defaults to 127.0.0.1)',
        port: 'optional - GQRX target port (defaults to 7356)'
      )

      udp_listener = #{self}.listen_udp(
        udp_ip: 'optional - IP address to bind UDP listener (defaults to 127.0.0.1)',
        udp_port: 'optional - Port to bind UDP listener (defaults to 7355)'
      )

      #{self}.disconnect_udp(
        udp_listener: 'required - UDP socket object returned from #listen_udp method'
      )

      iq_raw_file = #{self}.record(
        gqrx_sock: 'required - GQRX socket object returned from #connect method'
      )

      #{self}.stop_recording(
        gqrx_sock: 'required - GQRX socket object returned from #connect method',
        iq_raw_file: 'required - iq_raw_file returned from #record method'
      )

      #{self}.read_input_config(
        path: 'optional - GQRX conf (defaults to ~/.config/gqrx/default.conf)'
      )

      #{self}.device_input_rates(
        device: 'optional - SoapySDR device args (defaults to conf [input] device=)'
      )

      #{self}.set_input_rate(
        input_rate: 'required - Input rate Hz (rewrites conf [input] sample_rate=)',
        path: 'optional - GQRX conf path',
        clamp: 'optional - Snap to nearest device-legal rate (default true)',
        restart: 'optional - Kill+respawn gqrx so rate takes effect (default false)'
      )

      #{self}.apply_band_plan_input_rate(
        band_plan: 'required - e.g. :fm_radio / :ads_b1090 (reads FrequencyAllocation input_rate)',
        clamp: 'optional - Snap to device-legal rate (default true)',
        restart: 'optional - Bounce GQRX after write (default false)'
      )

      #{self}.disconnect(
        gqrx_sock: 'required - GQRX socket object returned from #connect method'
      )

      #{self}.authors
  USAGE
end

.init_freq(opts = {}) ⇒ Object

Supported Method Parameters

freq_obj = PWN::SDR::GQRX.init_freq( gqrx_sock: 'required - GQRX socket object returned from #connect method', freq: 'required - Frequency to set', demodulator_mode: 'optional - Demodulator mode (defaults to WFM)', bandwidth: 'optional - Bandwidth (defaults to "200.000")', squelch: 'optional - Squelch level to set (Defaults to current value)', decoder: 'optional - Decoder key (e.g., :gsm / :rds) to start live decoding (starts recording if provided)', interactive: 'optional - Boolean; when false AND decoder responds to .sample, call sample (non-interactive Hash) instead of decode (TTY). Defaults to true.', settle_secs: 'optional - Seconds for decoder.sample (e.g. RDS; default 8)', udp_ip: 'optional - UDP IP address for decoder module (defaults to 127.0.0.1)', udp_port: 'optional - UDP port for decoder module (defaults to 7355)', suppress_details: 'optional - Boolean to include extra frequency details in return hash (defaults to false)', keep_alive: 'optional - Boolean to keep GQRX connection alive after method completion (defaults to false)' )



1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
# File 'lib/pwn/sdr/gqrx.rb', line 1083

public_class_method def self.init_freq(opts = {})
  gqrx_sock = opts[:gqrx_sock]
  freq = opts[:freq]
  precision = opts[:precision] ||= 6
  valid_demodulator_modes = %i[
    AM
    AM_SYNC
    CW
    CWL
    CWU
    FM
    OFF
    LSB
    RAW
    USB
    WFM
    WFM_ST
    WFM_ST_OIRT
  ]
  demodulator_mode = opts[:demodulator_mode] ||= :WFM
  raise "ERROR: Invalid demodulator_mode '#{demodulator_mode}'. Valid modes: #{valid_demodulator_modes.join(', ')}" unless valid_demodulator_modes.include?(demodulator_mode.to_sym)

  bandwidth = opts[:bandwidth] ||= '200.000'
  squelch = opts[:squelch]
  decoder = opts[:decoder]
  # interactive: false → prefer decoder.sample (structured Hash) over
  # decoder.decode (TTY spinner). Used by agents / Extrospection / cron.
  interactive = opts.key?(:interactive) ? !opts[:interactive].nil? && opts[:interactive] != false : true
  settle_secs = opts[:settle_secs]
  udp_ip = opts[:udp_ip]
  udp_port = opts[:udp_port]
  suppress_details = opts[:suppress_details] || false
  keep_alive = opts[:keep_alive] || false

  unless keep_alive
    squelch = cmd(gqrx_sock: gqrx_sock, cmd: 'l SQL').to_f if squelch.nil?
    change_squelch_resp = cmd(
      gqrx_sock: gqrx_sock,
      cmd: "L SQL #{squelch}",
      resp_ok: 'RPRT 0'
    )

    mode_str = demodulator_mode.to_s.upcase
    passband_hz = PWN::SDR.hz_to_i(freq: bandwidth)
    cmd(
      gqrx_sock: gqrx_sock,
      cmd: "M #{mode_str} #{passband_hz}",
      resp_ok: 'RPRT 0'
    )
  end

  tune_to(gqrx_sock: gqrx_sock, hz: freq)
  strength_db = measure_signal_strength(
    gqrx_sock: gqrx_sock,
    freq: freq,
    precision: precision,
    phase: :init_freq
  )

  freq_obj = {
    freq: freq,
    demodulator_mode: demodulator_mode,
    bandwidth: bandwidth,
    strength_db: strength_db,
    decoder: decoder,
    squelch: squelch
  }

  unless suppress_details
    demod_n_passband = cmd(
      gqrx_sock: gqrx_sock,
      cmd: 'm'
    )

    audio_gain_db = cmd(
      gqrx_sock: gqrx_sock,
      cmd: 'l AF'
    ).to_f

    squelch = cmd(
      gqrx_sock: gqrx_sock,
      cmd: 'l SQL'
    ).to_f

    rf_gain = cmd(
      gqrx_sock: gqrx_sock,
      cmd: 'l RF_GAIN'
    )

    if_gain = cmd(
      gqrx_sock: gqrx_sock,
      cmd: 'l IF_GAIN'
    )

    bb_gain = cmd(
      gqrx_sock: gqrx_sock,
      cmd: 'l BB_GAIN'
    )

    freq_obj[:audio_gain_db] = audio_gain_db
    freq_obj[:demod_mode_n_passband] = demod_n_passband
    freq_obj[:bb_gain] = bb_gain
    freq_obj[:if_gain] = if_gain
    freq_obj[:rf_gain] = rf_gain
    freq_obj[:squelch] = squelch

    # Start recording and decoding if decoder provided
    if decoder
      # Resolve decoder module via central registry (see
      # PWN::SDR::Decoder::REGISTRY) so new protocols only need an
      # autoload + REGISTRY entry — no edit here.
      decoder_module = PWN::SDR::Decoder.resolve(decoder: decoder)

      # Initialize and start decoder (uniform .decode(freq_obj:) API).
      # When interactive:false and the module exposes .sample (e.g.
      # Decoder::RDS), return a structured Hash instead of the TTY loop.
      freq_obj[:gqrx_sock] = gqrx_sock
      freq_obj[:udp_ip] = udp_ip
      freq_obj[:udp_port] = udp_port
      freq_obj[:decoder_module] = decoder_module
      if !interactive && decoder_module.respond_to?(:sample)
        sample_opts = {
          freq_obj: freq_obj,
          gqrx_sock: gqrx_sock
        }
        sample_opts[:settle_secs] = settle_secs unless settle_secs.nil?
        freq_obj[:sample] = decoder_module.sample(sample_opts)
      else
        decoder_module.decode(freq_obj: freq_obj)
      end
    end
  end

  freq_obj
rescue StandardError => e
  raise e
ensure
  disconnect(gqrx_sock: gqrx_sock) if gqrx_sock.is_a?(TCPSocket) && !keep_alive
end

.listen_udp(opts = {}) ⇒ Object

Supported Method Parameters

udp_listener = PWN::SDR::GQRX.listen_udp( udp_ip: 'optional - IP address to bind UDP listener (defaults to 127.0.0.1)', upd_port: 'optional - Port to bind UDP listener (defaults to 7355)' )



1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
# File 'lib/pwn/sdr/gqrx.rb', line 1766

public_class_method def self.listen_udp(opts = {})
  udp_ip = opts[:udp_ip] ||= '127.0.0.1'
  udp_port = opts[:udp_port] ||= 7355

  PWN::Plugins::Sock.listen(
    server_ip: udp_ip,
    port: udp_port,
    protocol: :udp,
    detach: true
  )
rescue StandardError => e
  raise e
end

.nearest_input_rate(opts = {}) ⇒ Object

Supported Method Parameters

hz = PWN::SDR::GQRX.nearest_input_rate( input_rate: 'required - desired input rate Hz', rates: 'optional - Array of legal rates (defaults to #device_input_rates)' ) Snaps desired rate onto the closest legal device rate (>= preferred when possible, else nearest). Returns desired unchanged when rates empty.



2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
# File 'lib/pwn/sdr/gqrx.rb', line 2036

public_class_method def self.nearest_input_rate(opts = {})
  desired = (opts[:input_rate] || opts[:sample_rate]).to_i
  raise 'ERROR: :input_rate required' unless desired.positive?

  rates = opts[:rates]
  rates = device_input_rates(device: opts[:device], path: opts[:path]) if rates.nil?
  return desired if rates.nil? || rates.empty?

  # Prefer the smallest legal rate that still covers the ask (Nyquist /
  # panoramic span), else the max the hardware can do.
  ge = rates.select { |r| r >= desired }
  return ge.min if ge.any?

  rates.max
rescue StandardError => e
  raise e
end

.read_input_config(opts = {}) ⇒ Object

Supported Method Parameters

info = PWN::SDR::GQRX.read_input_config( path: 'optional - GQRX conf path (defaults to #config_path)' ) Returns Hash with :path, :device, :frequency, :input_rate, :raw



1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
# File 'lib/pwn/sdr/gqrx.rb', line 1916

public_class_method def self.read_input_config(opts = {})
  path = config_path(path: opts[:path])
  raise "ERROR: GQRX conf not found: #{path}" unless File.file?(path)

  text = File.read(path)
  # Restrict to the [input] section (until next [section] or EOF).
  input = text[/^\[input\][^\[]*/m].to_s
  raise "ERROR: no [input] section in #{path}" if input.empty?

  device = input[/^device=(.*)$/, 1].to_s.strip
  # strip surrounding quotes GQRX sometimes writes
  device = device.sub(/\A"(.*)"\z/, '\1')
  freq_s = input[/^frequency=(.*)$/, 1].to_s.strip
  rate_s = input[/^sample_rate=(.*)$/, 1].to_s.strip

  {
    path: path,
    device: device,
    frequency: (freq_s.empty? ? nil : freq_s.to_i),
    input_rate: (rate_s.empty? ? nil : rate_s.to_i),
    raw: input
  }
rescue StandardError => e
  raise e
end

.record(opts = {}) ⇒ Object

Supported Method Parameters

iq_raw_file = PWN::SDR::GQRX.record( gqrx_sock: 'required - GQRX socket object returned from #connect method' )



1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
# File 'lib/pwn/sdr/gqrx.rb', line 1799

public_class_method def self.record(opts = {})
  gqrx_sock = opts[:gqrx_sock]
  raise 'ERROR: gqrx_sock is required!' if gqrx_sock.nil?

  # Toggle I/Q RECORD on in GQRX for brevity
  cmd(
    gqrx_sock: gqrx_sock,
    cmd: 'U IQRECORD 0',
    resp_ok: 'RPRT 0'
  )

  cmd(
    gqrx_sock: gqrx_sock,
    cmd: 'U IQRECORD 1',
    resp_ok: 'RPRT 0'
  )

  record_dir = Dir.home
  iq_raw_file = Dir.glob("#{record_dir}/gqrx_*.raw").max_by { |f| File.mtime(f) }
  raise 'ERROR: No GQRX .raw I/Q data file found!' unless iq_raw_file

  iq_raw_file
rescue StandardError => e
  raise e
end

.restart_gqrx(opts = {}) ⇒ Object

Supported Method Parameters

ok = PWN::SDR::GQRX.restart_gqrx( gqrx_bin: 'optional - path to gqrx binary', conf_path: 'optional - pass -c on relaunch' ) Best-effort: SIGTERM any running gqrx, then relaunch detached. Returns true when a new process was spawned.



2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
# File 'lib/pwn/sdr/gqrx.rb', line 2163

public_class_method def self.restart_gqrx(opts = {})
  bin = opts[:gqrx_bin].to_s
  bin = `which gqrx 2>/dev/null`.to_s.strip if bin.empty?
  raise 'ERROR: gqrx binary not found' if bin.empty? || !File.executable?(bin)

  # Graceful stop so conf is flushed.
  pids = `pgrep -x gqrx 2>/dev/null`.to_s.split.map(&:to_i)
  pids.each do |pid|
    Process.kill('TERM', pid)
  rescue Errno::ESRCH
    nil
  end
  # Wait up to ~5s for exit
  50.times do
    break if `pgrep -x gqrx 2>/dev/null`.to_s.strip.empty?

    sleep 0.1
  end
  # Force if still up
  `pgrep -x gqrx 2>/dev/null`.to_s.split.map(&:to_i).each do |pid|
    Process.kill('KILL', pid)
  rescue Errno::ESRCH
    nil
  end

  conf = opts[:conf_path].to_s
  conf = config_path if conf.empty?
  cmd = if conf && File.file?(conf)
          [bin, '-c', conf]
        else
          [bin]
        end

  pid = spawn(
    *cmd,
    out: '/dev/null',
    err: '/dev/null',
    pgroup: true
  )
  Process.detach(pid)
  # Brief wait for remote control to come up (best effort).
  30.times do
    break if system('bash', '-c', 'exec 3<>/dev/tcp/127.0.0.1/7356', out: File::NULL, err: File::NULL)

    sleep 0.2
  end
  true
rescue StandardError => e
  raise e
end

.scan_range(opts = {}) ⇒ Object

Supported Method Parameters

scan_resp = PWN::SDR::GQRX.scan_range( gqrx_sock: 'required - GQRX socket object returned from #connect method', ranges: 'required - Array of Hash objects with :start_freq and :target_freq keys defining scan ranges', demodulator_mode: 'optional - Demodulator mode (e.g. WFM, AM, FM, USB, LSB, RAW, CW, RTTY / defaults to WFM)', bandwidth: 'optional - Bandwidth in Hz (Defaults to "200.000")', precision: 'optional - Frequency step precision (number of digits; defaults to 1)', strength_lock: 'optional - Strength lock in dBFS (defaults to -70.0)', squelch: 'optional - Squelch level in dBFS (defaults to strength_lock - 3.0)', audio_gain_db: 'optional - Audio gain in dB (defaults to 0.0)', rf_gain: 'optional - RF gain (defaults to 0.0)', intermediate_gain: 'optional - Intermediate gain (defaults to 32.0)', baseband_gain: 'optional - Baseband gain (defaults to 10.0)', keep_looping: 'optional - Boolean to keep scanning indefinitely (defaults to false)', scan_log: 'optional - Path to save detected signals log (defaults to /tmp/pwn_sdr_gqrx_scan_<start_freq>-<target_freq>__lN.json)', location: 'optional - Location string to include in AI analysis (e.g., "New York, NY", 90210, GPS coords, etc.)' )



1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
# File 'lib/pwn/sdr/gqrx.rb', line 1241

public_class_method def self.scan_range(opts = {})
  timestamp_start = Time.now.strftime('%Y-%m-%d %H:%M:%S%z')
  range_timestamp_start = ''

  gqrx_sock = opts[:gqrx_sock]

  ranges = opts[:ranges]
  raise 'ERROR: ranges must be an Array of Hash objects with :start_freq and :target_freq keys.' unless ranges.is_a?(Array) && ranges.all? { |r| r.is_a?(Hash) && r.key?(:start_freq) && r.key?(:target_freq) }

  demodulator_mode = opts[:demodulator_mode]

  bandwidth = opts[:bandwidth] ||= '200.000'

  precision = opts[:precision] ||= 1
  raise 'ERROR: precision must be an Integer between 1 and 12.' unless precision.is_a?(Integer) && precision.between?(1, 12)

  step_hz = 10**(precision - 1)

  # Honour explicit CLI/API -S / -Q. Default strength_lock = -70.0 is only
  # a starting guess and is re-calibrated against the live S-meter noise
  # floor below unless the user provided -S. Stored squelch is always a
  # few dB under strength_lock for later decoder re-tunes; during the
  # candidate / edge walk itself we open GQRX SQL fully so I/Q + S-meter
  # are never muted.
  user_strength_lock = !opts[:strength_lock].nil?
  user_squelch = !opts[:squelch].nil?
  strength_lock = (opts[:strength_lock] || -70.0).to_f
  squelch = (opts[:squelch] || (strength_lock - 3.0)).to_f
  raise 'ERROR: squelch must always be less than strength_lock.' if squelch >= strength_lock

  decoder = opts[:decoder]
  keep_looping = opts[:keep_looping] || false
  log_timestamp = Time.now.strftime('%Y-%m-%d')

  location = opts[:location] ||= 'United States'

  # This is for looping through ranges indefinitely if keep_looping is true
  # Generate ranges strings for log filename
  range_str = ''
  ranges.each do |range|
    start_freq = range[:start_freq]
    hz_start = PWN::SDR.hz_to_i(freq: start_freq)
    hz_start_str = PWN::SDR.hz_to_s(freq: hz_start)

    target_freq = range[:target_freq]
    hz_target = PWN::SDR.hz_to_i(freq: target_freq)
    hz_target_str = PWN::SDR.hz_to_s(freq: hz_target)

    range_str = "#{range_str}_#{hz_start_str}-#{hz_target_str}"
  end
  scan_log = opts[:scan_log] ||= "/tmp/pwn_sdr_gqrx_scan#{range_str}_#{log_timestamp}.json"

  iteration_metrics = []
  candidate_signals = []
  signals_detected = []
  iteration_total = 1
  signals_detected_total = 0
  loop do
    signals_detected_delta = 0
    iter_metrics_hash = {}
    ranges.each do |range|
      range_timestamp_start = Time.now.strftime('%Y-%m-%d %H:%M:%S%z')
      iter_metrics_hash[:iteration] = iteration_total
      iter_metrics_hash[:range] = range
      iter_metrics_hash[:timestamp_start] = range_timestamp_start

      # Verify all frequencies are valid
      start_freq = range[:start_freq]
      hz_start = PWN::SDR.hz_to_i(freq: start_freq)
      raise "ERROR: Invalid start_freq '#{start_freq}' provided." if hz_start.zero?

      target_freq = range[:target_freq]
      hz_target = PWN::SDR.hz_to_i(freq: target_freq)
      hz_target_str = PWN::SDR.hz_to_s(freq: hz_target)
      raise "ERROR: Invalid target_freq '#{target_freq}' provided." if hz_target.zero?

      step_hz_direction = hz_start > hz_target ? -step_hz : step_hz
      noise_floor = measure_noise_floor(
        gqrx_sock: gqrx_sock,
        freq: start_freq,
        precision: precision,
        step_hz_direction: step_hz_direction
      )
      # Auto-calibrate strength_lock from live S-meter noise floor unless
      # the user passed an explicit -S. The historical rule
      #   squelch = nf.round + 7; strength_lock = squelch + 3
      # RAISED the gate into the signal cloud on dense bands (fm_radio
      # stations sit only ~10–20 dB above the quiet floor) which made
      # edge_detection refuse to drop and paint multi-MHz occupied-BW
      # blobs. Mirror #fast_scan_range: lock = nf + 8, squelch = lock - 3.
      if user_strength_lock
        if !user_squelch && squelch < noise_floor
          # Explicit -S but no -Q: keep lock, just park squelch under the
          # quieter of (lock-3, nf+1) so decoder SQL is sane later.
          squelch = [strength_lock - 3.0, noise_floor.to_f + 1.0].min.round(1)
          puts "[SCAN] derived squelch=#{squelch} dBFS under strength_lock=#{strength_lock} (nf≈#{noise_floor})"
        end
      else
        # nf + 12 dB: high enough that quiet interstitial spectrum
        # (side-lobes, distant carriers) stays under the gate, low
        # enough that real FM main lobes (~15–30 dB above nf) still
        # trip. The historical nf.round+7 formula sat *inside* the
        # carrier cloud and refused to drop on edges.
        auto_lock = (noise_floor.to_f + 12.0).round(1)
        puts "[SCAN] auto strength_lock: live S-meter nf≈#{noise_floor} dBFS → lock=#{auto_lock} dBFS (was #{strength_lock})"
        strength_lock = auto_lock
        squelch = (strength_lock - 3.0).round(1) unless user_squelch
      end
      if squelch >= strength_lock
        squelch = (strength_lock - 3.0).round(1)
        puts "[SCAN] clamped squelch to #{squelch} dBFS (< strength_lock #{strength_lock})"
      end

      # Begin scanning range
      puts "\n"
      puts '-' * 86
      puts 'SESSION PARAMS >> Scan Range(s):'
      puts ranges
      puts "SESSION PARAMS >> Step Increment: #{PWN::SDR.hz_to_s(freq: step_hz_direction.abs)} Hz."
      puts "SESSION PARAMS >> Continuously Loop through Scan Range(s): #{keep_looping}"
      puts "\nIf scans are slow and/or you're experiencing false positives/negatives,"
      puts 'consider adjusting the following:'
      puts "1. The SDR's sample rate in GQRX (device Input rate — NOT remote-control)"
      puts "\s\s- Prefer: PWN::SDR::GQRX.apply_band_plan_input_rate(band_plan: :fm_radio, restart: true)"
      puts "\s\s- Or: click Configure I/O devices and set Input rate to the band-plan input_rate."
      puts "\s\s- Lower Input rate can improve regular-scan responsiveness (e.g. Pluto/HackRF ~ 1e6 for FM)."
      puts '2. Adjust the :strength_lock parameter.'
      puts '3. Adjust the :precision parameter.'
      puts '4. Disable AI module_reflection in PWN::Env'
      puts 'Happy scanning!'
      puts '-' * 86
      # print 'Pressing ENTER to begin scan...'
      # gets
      puts "\n\n\n"

      # Floor GQRX SQL during the candidate / edge / peak walk so the
      # S-meter is never muted. The calibrated :squelch is stored on
      # each detection for later decoder re-tunes (analyze_scan).
      change_squelch_resp = cmd(
        gqrx_sock: gqrx_sock,
        cmd: 'L SQL -150.0',
        resp_ok: 'RPRT 0'
      )
      puts "[SCAN] GQRX SQL floored to -150.0 for S-meter walks (stored squelch=#{squelch} dBFS, strength_lock=#{strength_lock} dBFS)"

      # We always disable RDS decoding during the scan
      # to prevent unnecessary processing overhead.
      # We return the rds boolean in the scan_resp object
      # so it will be picked up and used appropriately
      # when calling analyze_scan or analyze_log methods.
      rds_resp = cmd(
        gqrx_sock: gqrx_sock,
        cmd: 'U RDS 0',
        resp_ok: 'RPRT 0'
      )

      # Set demodulator mode & passband once for the scan
      mode_str = demodulator_mode.to_s.upcase
      passband_hz = PWN::SDR.hz_to_i(freq: bandwidth)
      cmd(
        gqrx_sock: gqrx_sock,
        cmd: "M #{mode_str} #{passband_hz}",
        resp_ok: 'RPRT 0'
      )

      audio_gain_db = opts[:audio_gain_db] ||= 0.0
      audio_gain_db = audio_gain_db.to_f
      audio_gain_db_resp = cmd(
        gqrx_sock: gqrx_sock,
        cmd: "L AF #{audio_gain_db}",
        resp_ok: 'RPRT 0'
      )

      rf_gain = opts[:rf_gain] ||= 0.0
      rf_gain = rf_gain.to_f
      rf_gain_resp = cmd(
        gqrx_sock: gqrx_sock,
        cmd: "L RF_GAIN #{rf_gain}",
        resp_ok: 'RPRT 0'
      )

      intermediate_gain = opts[:intermediate_gain] ||= 32.0
      intermediate_gain = intermediate_gain.to_f
      intermediate_resp = cmd(
        gqrx_sock: gqrx_sock,
        cmd: "L IF_GAIN #{intermediate_gain}",
        resp_ok: 'RPRT 0'
      )

      baseband_gain = opts[:baseband_gain] ||= 10.0
      baseband_gain = baseband_gain.to_f
      baseband_resp = cmd(
        gqrx_sock: gqrx_sock,
        cmd: "L BB_GAIN #{baseband_gain}",
        resp_ok: 'RPRT 0'
      )

      prev_freq_obj = init_freq(
        gqrx_sock: gqrx_sock,
        freq: hz_start,
        precision: precision,
        demodulator_mode: demodulator_mode,
        bandwidth: bandwidth,
        squelch: squelch,
        decoder: decoder,
        suppress_details: true,
        keep_alive: true
      )

      start_freq = range[:start_freq]
      hz_start = PWN::SDR.hz_to_i(freq: start_freq)
      hz = hz_start

      target_freq = range[:target_freq]
      hz_target = PWN::SDR.hz_to_i(freq: target_freq)

      # puts "#{range} #{start_freq} (#{hz_start})to #{target_freq} (#{hz_target})"
      # gets
      # while step_hz_direction.positive? ? hz <= hz_target : hz >= hz_target
      while (step_hz_direction.positive? && hz <= hz_target) || (step_hz_direction.negative? && hz >= hz_target)
        tune_to(gqrx_sock: gqrx_sock, hz: hz)
        strength_db = measure_signal_strength(
          gqrx_sock: gqrx_sock,
          freq: hz,
          precision: precision,
          strength_lock: strength_lock,
          phase: :find_candidates
        )

        if strength_db >= strength_lock
          puts '-' * 86
          # Find left and right edges of the signal
          # Bound the edge walk to ~± plan_bw (or a few raster steps) so
          # adjacent co-channel carriers (fm_radio 200 kHz spacing) cannot
          # merge into a multi-MHz "occupied" lobe when strength_lock is
          # a hair too low. Hard bounds reuse the optional min_hz/max_hz
          # already supported by #edge_detection for #refine_detections.
          plan_bw_for_edge = PWN::SDR.hz_to_i(freq: bandwidth)
          plan_bw_for_edge = step_hz if plan_bw_for_edge.zero?
          # Keep the next co-channel neighbour outside the window:
          # half ≈ 0.6·plan (capped at plan itself), floored by the raster.
          half_edge = [
            (plan_bw_for_edge * 0.6).to_i,
            step_hz
          ].max
          half_edge = [half_edge, plan_bw_for_edge].min
          half_edge = step_hz if half_edge < 1
          candidate_signals = edge_detection(
            gqrx_sock: gqrx_sock,
            hz: hz,
            step_hz: step_hz,
            precision: precision,
            strength_lock: strength_lock,
            min_hz: hz - half_edge,
            max_hz: hz + half_edge
          )
        elsif candidate_signals.length.positive?
          best_peak = find_best_peak(
            gqrx_sock: gqrx_sock,
            candidate_signals: candidate_signals,
            precision: precision,
            step_hz: step_hz,
            strength_lock: strength_lock
          )

          # Accept peaks a few dB under strength_lock: the candidate
          # gate already verified something in this window was hot,
          # and find_best_peak averages multi-pass samples so a peaky
          # FM main lobe can report slightly under the trip level.
          if best_peak[:hz] && best_peak[:strength_db] > (strength_lock - 3.0)
            puts "\n**** Detected Signal ****"
            best_freq = PWN::SDR.hz_to_s(freq: best_peak[:hz])
            best_strength_db = best_peak[:strength_db]
            prev_freq_obj = init_freq(
              gqrx_sock: gqrx_sock,
              freq: best_freq,
              precision: precision,
              demodulator_mode: demodulator_mode,
              bandwidth: bandwidth,
              squelch: squelch,
              decoder: decoder,
              suppress_details: true,
              keep_alive: true
            )
            prev_freq_obj[:strength_lock] = strength_lock
            prev_freq_obj[:strength_db] = best_strength_db.round(2)
            prev_freq_obj[:iteration] = iteration_total

            # Schema parity with #fast_scan_range signals so both
            # modes emit the same key set (see log_signals / example
            # scan JSON). Values are derived from edge detection +
            # the measured noise floor rather than an FFT bin map.
            best_hz = PWN::SDR.hz_to_i(freq: best_peak[:hz])
            edge_hzs = candidate_signals.map { |s| PWN::SDR.hz_to_i(freq: s[:hz]) }
            edge_lo = edge_hzs.min
            edge_hi = edge_hzs.max
            occupied_bw_hz = ((edge_hi - edge_lo).abs + step_hz).to_i
            plan_bw_for_sig = PWN::SDR.hz_to_i(freq: bandwidth)
            plan_bw_for_sig = step_hz if plan_bw_for_sig.zero?
            # Prefer measured occupied BW when the edge walk resolved a
            # plausible span (≤ 2× plan BW). Anything wider is almost
            # always a multi-station merge from an under-shot lock —
            # fall back to the band-plan channel width instead of
            # advertising multi-MHz "signals".
            max_plausible_bw = [plan_bw_for_sig * 2, step_hz * 4, plan_bw_for_sig].max
            sig_bw_hz = if occupied_bw_hz.positive? && occupied_bw_hz <= max_plausible_bw
                          occupied_bw_hz
                        else
                          plan_bw_for_sig
                        end
            nf_db = noise_floor.to_f
            snr = (best_strength_db.to_f - nf_db).round(2)
            prev_freq_obj[:hz] = best_hz
            prev_freq_obj[:raw_peak_hz] = best_hz
            prev_freq_obj[:bw_hz] = sig_bw_hz
            prev_freq_obj[:snr_db] = snr
            prev_freq_obj[:prominence_db] = snr
            prev_freq_obj[:noise_floor_db] = nf_db.round(2)
            prev_freq_obj[:chunk_center] = PWN::SDR.hz_to_s(freq: ((edge_lo + edge_hi) / 2.0).to_i)
            prev_freq_obj[:method] = :iterative_edge_peak

            # Soft-fail AI analysis so a missing PWN::Env[:ai] (or
            # engine outage) never aborts an otherwise successful
            # detection. module_reflection=false or bare `require
            # 'pwn'` without Driver::Parser both leave Env[:ai] nil.
            begin
              ai_analysis = PWN::AI::Agent::GQRX.analyze(
                request: prev_freq_obj.to_json,
                location: location
              )
              prev_freq_obj[:ai_analysis] = ai_analysis unless ai_analysis.nil?
            rescue StandardError => e
              puts "[SCAN] AI analysis skipped: #{e.class}: #{e.message}"
            end
            puts JSON.pretty_generate(prev_freq_obj)
            puts '-' * 86
            puts "\n\n\n"
            signals_detected.push(prev_freq_obj)
            log_signals(
              signals_detected: signals_detected,
              timestamp_start: timestamp_start,
              scan_log: scan_log,
              meta: {
                precision: precision,
                plan_bw_hz: plan_bw_for_sig,
                method: :scan_range
              }
            )
            hz = candidate_signals.last[:hz]
            # gets
          end
          candidate_signals.clear
        end
        hz += step_hz_direction
      end

      log_signals(
        signals_detected: signals_detected,
        timestamp_start: timestamp_start,
        scan_log: scan_log,
        meta: {
          precision: precision,
          plan_bw_hz: PWN::SDR.hz_to_i(freq: bandwidth),
          method: :scan_range
        }
      )
    end
    break unless keep_looping

    # Determine how many new signals were detected this iteration
    # Reduces signals_detected to an array of unique frequencies only
    signals_detected.uniq! { |s| PWN::SDR.hz_to_i(freq: s[:freq]) }
    signals_detected_total = signals_detected.select { |s| s[:iteration] == iteration_total }.length
    signals_detected_delta = signals_detected_total - signals_detected_delta
    start_next_iteration = case signals_detected_delta
                           when 0
                             30
                           when 1..5
                             10
                           else
                             5
                           end

    range_timestamp_end = Time.now.strftime('%Y-%m-%d %H:%M:%S%z')
    iter_metrics_hash[:timestamp_end] = range_timestamp_end

    duration = duration_between(timestamp_start: range_timestamp_start, timestamp_end: range_timestamp_end)
    iter_metrics_hash[:duration] = duration
    iter_metrics_hash[:signals_detected] = signals_detected_delta

    iteration_metrics.push(iter_metrics_hash)
    puts "\nScan iteration(s) ##{iteration_total} complete."
    puts JSON.pretty_generate(iter_metrics_hash)

    puts "Resuming next scan iteration in #{start_next_iteration} seconds.  Press CTRL+C to exit"
    start_next_iteration.times do
      print '.'
      sleep 1
    end
    puts "\n"

    # Log current signals one last time just to capture scan iterations accurately
    iteration_total += 1
    log_signals(
      signals_detected: signals_detected,
      timestamp_start: timestamp_start,
      scan_log: scan_log,
      iteration_metrics: iteration_metrics,
      meta: {
        precision: precision,
        plan_bw_hz: PWN::SDR.hz_to_i(freq: bandwidth),
        method: :scan_range
      }
    )
  end
rescue Interrupt
  puts "\nCTRL+C detected - goodbye."
rescue StandardError => e
  raise e
ensure
  disconnect(gqrx_sock: gqrx_sock) if defined?(gqrx_sock) && gqrx_sock.is_a?(TCPSocket)
end

.set_input_rate(opts = {}) ⇒ Object

Supported Method Parameters

result = PWN::SDR::GQRX.set_input_rate( input_rate: 'required - desired GQRX Input rate in Hz (Integer)', path: 'optional - GQRX conf path (defaults to #config_path)', clamp: 'optional - snap to nearest legal device rate (default true)', restart: 'optional - kill+respawn gqrx so the new rate is applied (default false)', gqrx_bin: 'optional - gqrx binary path when restart:true (default which gqrx)' ) Rewrites [input] sample_rate= in the active GQRX conf. Does NOT use the remote-control socket — input rate is not part of that protocol. Returns { path:, previous:, input_rate:, clamped_from:, restarted:, device: }.



2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
# File 'lib/pwn/sdr/gqrx.rb', line 2065

public_class_method def self.set_input_rate(opts = {})
  desired = (opts[:input_rate] || opts[:sample_rate]).to_i
  raise 'ERROR: :input_rate required (positive Integer Hz)' unless desired.positive?

  path = config_path(path: opts[:path])
  conf = read_input_config(path: path)
  previous = conf[:input_rate]
  device = conf[:device]

  applied = desired
  clamped_from = nil
  clamp = opts.key?(:clamp) ? !opts[:clamp].nil? && opts[:clamp] != false : true
  if clamp
    snapped = nearest_input_rate(
      input_rate: desired,
      device: device,
      path: path
    )
    if snapped != desired
      clamped_from = desired
      applied = snapped
    end
  end

  text = File.read(path)
  if text.match?(/^\[input\][^\[]*sample_rate=/m)
    text = text.sub(/^(sample_rate=).*$/, "\\1#{applied}")
  else
    # Insert sample_rate under [input] if the key is somehow missing.
    text = text.sub(/^\[input\]\s*$/, "[input]\nsample_rate=#{applied}")
  end
  File.write(path, text)

  restarted = false
  if opts[:restart]
    restarted = restart_gqrx(
      gqrx_bin: opts[:gqrx_bin],
      conf_path: path
    )
  end

  {
    path: path,
    previous: previous,
    input_rate: applied,
    clamped_from: clamped_from,
    restarted: restarted,
    device: device,
    note: restarted ? 'GQRX restarted to apply input_rate' : 'Restart GQRX (or reopen I/O devices) to apply input_rate'
  }
rescue StandardError => e
  raise e
end

.stop_recording(opts = {}) ⇒ Object

Supported Method Parameters

PWN::SDR::GQRX.stop_recording( gqrx_sock: 'required - GQRX socket object returned from #connect method', iq_raw_file: 'required - iq_raw_file returned from #connect method' )



1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
# File 'lib/pwn/sdr/gqrx.rb', line 1831

public_class_method def self.stop_recording(opts = {})
  gqrx_sock = opts[:gqrx_sock]
  raise 'ERROR: gqrx_sock is required!' if gqrx_sock.nil?

  iq_raw_file = opts[:iq_raw_file]
  raise 'ERROR: iq_raw_file is required!' if iq_raw_file.nil?

  # Toggle IQRECORD off
  cmd(
    gqrx_sock: gqrx_sock,
    cmd: 'U IQRECORD 0',
    resp_ok: 'RPRT 0'
  )

  FileUtils.rm_f(iq_raw_file)
rescue StandardError => e
  raise e
end