-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheatwave.py
executable file
·2210 lines (1895 loc) · 95.9 KB
/
heatwave.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Heatwave - Real-time RF Spectrum Analyzer with Waterfall Display
for use with Linux framebuffer.
==============================================================
A feature-rich RF spectrum analyzer that provides real-time visualization of radio frequency signals
using RTL-SDR and other SDR devices through the SoapySDR interface.
Features:
- Real-time waterfall display of RF spectrum
- Multiple color schemes and display modes
- Frequency band presets and markers
- Time-based annotations and signal analysis
- Automatic gain control (AGC)
- Recording and export capabilities
- Comprehensive keyboard controls
Requirements:
- Python 3.6+
- numpy
- SoapySDR
- scipy
- PIL (Pillow)
- Compatible SDR device (RTL-SDR, HackRF, etc.)
Author: XQTR // https://github.com/xqtr // https://cp737.net
License: GPL-3.0+
Version: 1.0.0
"""
import numpy as np
import SoapySDR
from SoapySDR import SOAPY_SDR_RX, SOAPY_SDR_CF32
import mmap
import struct
import argparse
import time
from scipy import signal
from PIL import Image, ImageDraw, ImageFont
import os
import sys
import termios
import tty
import select
from datetime import datetime
import json
import os.path
import fcntl
import array
class FrequencyHeatmap:
def __init__(self, start_freq, end_freq, sample_rate=2.4e6, color_mode=32):
"""Initialize the frequency heatmap display"""
# Store color mode
self.color_mode = color_mode
# Remove custom band configuration
self.config_dir = os.path.expanduser('~/.config/heatwave/')
os.makedirs(self.config_dir, exist_ok=True)
self.settings_file = os.path.join(self.config_dir, 'settings.json')
# Remove: self.band_file = os.path.join(self.config_dir, 'bands.json')
# Initialize basic parameters
self.start_freq = start_freq
self.end_freq = end_freq
self.sample_rate = sample_rate
self.freq_range = end_freq - start_freq
self._center_freq = start_freq + (self.freq_range / 2)
# Initialize built-in bands with comprehensive frequency ranges
self.bands = {
# Broadcast Bands
"AM": (535e3, 1.7e6),
"SW": (2.3e6, 26.1e6),
"FM": (88e6, 108e6),
"DAB": (174e6, 240e6),
# Aviation Bands
"AIR-L": (108e6, 118e6), # VOR/ILS/Markers
"AIR-V": (118e6, 137e6), # Voice Communications
"AIR-M": (978e6, 1090e6), # ADS-B/Mode S
# Amateur Radio Bands
"HAM160": (1.8e6, 2.0e6),
"HAM80": (3.5e6, 4.0e6),
"HAM40": (7.0e6, 7.3e6),
"HAM20": (14.0e6, 14.35e6),
"HAM2M": (144e6, 148e6),
"HAM70": (420e6, 450e6),
# Public Safety
"NOA": (162.4e6, 162.55e6), # NOAA Weather
"POLICE": (450e6, 470e6), # Police/Emergency
"EMG": (851e6, 869e6), # Emergency Services
# Television
"VHF-TV": (54e6, 88e6), # VHF Low
"VHF-TV2": (174e6, 216e6), # VHF High
"UHF-TV": (470e6, 698e6), # UHF TV
# Satellite
"GPS-L1": (1575.42e6, 1575.42e6),
"GOES": (1670e6, 1698e6),
"NOAA-SAT": (137e6, 138e6),
"METEOR-SAT": (137.9e6, 137.9e6),
# Mobile & Cellular
"CELL-850": (824e6, 894e6),
"GSM900": (890e6, 960e6),
"GSM1800": (1710e6, 1880e6),
"DECT": (1880e6, 1900e6),
# ISM & IoT
"ISM-433": (433.05e6, 434.79e6),
"ISM-868": (868e6, 868.6e6),
"ISM-915": (902e6, 928e6),
"ZIGBEE": (2400e6, 2483.5e6),
# Marine
"MAR-VHF": (156e6, 174e6),
"MAR-AIS": (161.975e6, 162.025e6),
"MAR-DSC": (156.525e6, 156.525e6),
# Digital Radio
"DAB": (174e6, 240e6),
"DSTAR": (145.375e6, 145.375e6),
"DMR": (446e6, 446.2e6),
"TETRA": (380e6, 400e6),
# Remote Control
"RC-AIR": (72e6, 73e6),
"RC-CAR": (26.995e6, 27.255e6),
"RC-GENERAL": (433e6, 435e6),
# Utilities
"PAGER": (929e6, 932e6),
"RFID": (13.56e6, 13.56e6),
"TRUNKING": (851e6, 869e6),
"SCADA": (450e6, 470e6),
# Microphones
"MIC-VHF": (169.445e6, 171.905e6),
"MIC-UHF": (470e6, 698e6),
"MIC-PRO": (944e6, 952e6),
# Weather
"WEATHER-SAT": (137e6, 138e6),
"WEATHER-RADIO": (162.4e6, 162.55e6),
"WEATHER-FAX": (2.0e6, 25e6),
# Time Signals
"WWV": (2.5e6, 20e6),
"WWVH": (2.5e6, 15e6),
"DCF77": (77.5e3, 77.5e3),
"MSF": (60e3, 60e3)
}
# Initialize band details with comprehensive information
self.band_details = {
"AM": {
"mode": "AM",
"spacing": 10e3,
"description": "AM Broadcasting"
},
"FM": {
"mode": "WFM",
"spacing": 200e3,
"description": "FM Broadcasting"
},
"AIR-V": {
"mode": "AM",
"spacing": 25e3,
"description": "Aircraft Voice Communications"
},
"AIR-L": {
"mode": "AM",
"spacing": 50e3,
"description": "Aircraft Navigation (VOR/ILS)"
},
"HAM2M": {
"mode": "NFM",
"spacing": 12.5e3,
"description": "2-meter Amateur Radio Band"
},
"NOA": {
"mode": "NFM",
"spacing": 25e3,
"description": "NOAA Weather Radio"
},
"POLICE": {
"mode": "NFM",
"spacing": 12.5e3,
"description": "Police and Emergency Services"
},
"GPS-L1": {
"mode": "BPSK",
"spacing": 2e6,
"description": "GPS L1 Signal"
},
"ISM-433": {
"mode": "NFM",
"spacing": 25e3,
"description": "ISM Band 433MHz"
},
"MAR-VHF": {
"mode": "NFM",
"spacing": 25e3,
"description": "Marine VHF Communications"
},
"CELL-850": {
"mode": "DIGITAL",
"spacing": 200e3,
"description": "Cellular 850MHz Band"
},
"DAB": {
"mode": "DIGITAL",
"spacing": 1.536e6,
"description": "Digital Audio Broadcasting"
},
"TETRA": {
"mode": "DIGITAL",
"spacing": 25e3,
"description": "TETRA Digital Radio"
},
"WEATHER-SAT": {
"mode": "APT",
"spacing": 30e3,
"description": "Weather Satellite Transmissions"
},
"WWV": {
"mode": "AM",
"spacing": 1e3,
"description": "NIST Time Signal Station"
}
# Add more band details as needed
}
# Remove: self.load_custom_bands()
# Initialize basic parameters first
self.ppm = 0 # Initialize PPM correction to 0
# Setup terminal settings first
self.old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
# Initialize SDR after parameters and terminal settings are set
self.sdr = None
self.setup_sdr()
# Now set the center frequency on the SDR
self.center_freq = self._center_freq
# Detect framebuffer resolution
with open('/sys/class/graphics/fb0/virtual_size', 'r') as f:
self.width, self.height = map(int, f.read().strip().split(','))
# Get bits per pixel
with open('/sys/class/graphics/fb0/bits_per_pixel', 'r') as f:
self.bits_per_pixel = int(f.read().strip())
# Bytes per pixel
self.bytes_per_pixel = self.bits_per_pixel // 8
print(f"Framebuffer: {self.width}x{self.height}, {self.bits_per_pixel} bits per pixel")
# Initialize framebuffer
self.fb = open('/dev/fb0', 'rb+')
self.fb_info = self.get_fix_info()
# Set bytes per pixel based on color mode parameter
self.bytes_per_pixel = 4 if self.color_mode == 32 else 2
self.fb_size = self.width * self.height * self.bytes_per_pixel
# Create memory mapping for framebuffer
try:
self.fb_data = mmap.mmap(
self.fb.fileno(),
self.fb_size,
mmap.MAP_SHARED,
mmap.PROT_READ | mmap.PROT_WRITE,
offset=0
)
except Exception as e:
print(f"Error mapping framebuffer: {e}")
# Try fallback with just the file object
self.fb_data = self.fb
# Configure RTL-SDR
self.sdr.setSampleRate(SOAPY_SDR_RX, 0, self.sample_rate)
self.sdr.setFrequency(SOAPY_SDR_RX, 0, self._center_freq) # Use the stored value
self.sdr.setGain(SOAPY_SDR_RX, 0, 20) # Initial gain setting
# Add font initialization
try:
self.font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 12)
except:
# Fallback to default font if DejaVu Sans is not available
self.font = ImageFont.load_default()
# Reserve space for labels and margins
self.left_margin = 0 # Space for time labels
self.top_margin = 30 # Space for information display
self.bottom_margin = 30 # Space for frequency labels
self.graph_height = self.height - self.bottom_margin - self.top_margin
self.graph_width = self.width - self.left_margin
self.heatmap = np.zeros((self.graph_height, self.graph_width))
# Initialize time tracking
self.start_time = time.time()
# Initialize cursor at start frequency
self.cursor_freq = start_freq
self.cursor_step = 0.1e6 # 0.1MHz step
# Add pause state
self.paused = False
# Add new state variables
self.peak_hold = False
self.averaging = False
self.auto_scale = True
self.recording = False
self.record_file = None
self.color_scheme = 0 # 0: default, 1: hot, 2: viridis, 3: plasma, 4: magma
self.scroll_speed = 1.0
self.markers = {} # Dictionary to store frequency markers
self.shift_pressed = False # For marker setting
self.last_char = None # Track the last character pressed
# Initialize peak hold array
self.peak_values = np.zeros_like(self.heatmap)
# Initialize averaging buffer
self.avg_buffer = []
self.avg_length = 5 # Number of spectrums to average
# Add timestamp tracking
self.last_timestamp = time.time()
self.timestamps = [] # List to store timestamps
# Add message display variables
self.display_message = ""
self.message_time = 0
self.message_duration = 3 # Message display duration in seconds
# Add AGC parameters
self.agc_enabled = False
self.agc_target = -30 # Target power level in dB
self.agc_speed = 0.3 # AGC adjustment speed (0-1)
self.agc_min_gain = 0
self.agc_max_gain = 49.6
self.current_gain = 20 # Starting gain
self.agc_history = []
self.agc_history_len = 10 # Number of measurements to average
self.last_agc_update = time.time()
self.agc_update_interval = 0.5 # Seconds between AGC updates
# Get script directory
self.script_dir = os.path.dirname(os.path.abspath(__file__))
# Load settings if they exist
self.load_settings()
# Add time tracking and annotation support
self.annotations = []
self.timestamps = []
self.base_pixels_per_second = self.graph_height / (10 * 60) # 10 minutes total height
self.export_directory = os.path.join(self.script_dir, 'exports')
# Create exports directory if it doesn't exist
if not os.path.exists(self.export_directory):
os.makedirs(self.export_directory)
# Add annotation position tracking
self.annotation_positions = {} # Store y-positions for annotations
self.annotation_shift = 0 # Track total shift amount
# Add scan time tracking with averaging
self.last_scan_time = 0
self.scan_times = [] # List to store recent scan times
self.scan_times_max = 10 # Number of samples to average
# Initialize FFT planning and window
self._init_fft_processing()
# Add tracking for framebuffer fill level
self.fb_fill_level = 0
self.fb_filled = False
self.export_count = 0
self.auto_export_enabled = False # New flag for automatic export
# Create exports directory if it doesn't exist
self.export_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'exports')
def setup_sdr(self):
"""Initialize SoapySDR device with user selection"""
# List all available devices
results = SoapySDR.Device.enumerate()
if len(results) == 0:
raise RuntimeError("No SDR devices found")
# If only one device, use it automatically
if len(results) == 1:
self.sdr = SoapySDR.Device(results[0])
else:
# Temporarily restore normal terminal behavior for device selection
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
# Display available devices
print("\nAvailable SDR devices:")
print("----------------------")
for i, device in enumerate(results):
# Access device info directly from kwargs
try:
driver = str(device["driver"]) if "driver" in device else "Unknown"
label = str(device["label"]) if "label" in device else "Unnamed"
serial = str(device["serial"]) if "serial" in device else "No serial"
except:
driver = "Unknown"
label = "Unnamed"
serial = "No serial"
print(f"{i + 1}. Driver: {driver}")
print(f" Label: {label}")
print(f" Serial: {serial}")
print("----------------------")
# Get user selection
while True:
try:
selection = input(f"Select device (1-{len(results)}): ")
device_index = int(selection) - 1
if 0 <= device_index < len(results):
self.sdr = SoapySDR.Device(results[device_index])
break
else:
print(f"Please enter a number between 1 and {len(results)}")
except ValueError:
print("Please enter a valid number")
finally:
# Restore non-blocking input mode
tty.setcbreak(sys.stdin.fileno())
os.system('clear') # Clear the terminal
# Setup streaming
self.sdr.setSampleRate(SOAPY_SDR_RX, 0, self.sample_rate)
self.sdr.setFrequency(SOAPY_SDR_RX, 0, self._center_freq)
self.sdr.setGain(SOAPY_SDR_RX, 0, 20) # Initial gain setting
# Setup the stream
self.rx_stream = self.sdr.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32)
self.sdr.activateStream(self.rx_stream)
# Add after other SDR setup commands
if hasattr(self.sdr, 'setFrequencyCorrection'):
self.sdr.setFrequencyCorrection(SOAPY_SDR_RX, 0, self.ppm)
def save_settings(self):
"""Save current settings to JSON file"""
settings = {
'sample_rate': self.sample_rate,
'color_scheme': self.color_scheme,
'scroll_speed': self.scroll_speed,
'current_gain': self.current_gain,
'agc_enabled': self.agc_enabled,
'agc_target': self.agc_target,
'agc_speed': self.agc_speed,
'peak_hold': self.peak_hold,
'averaging': self.averaging,
'auto_scale': self.auto_scale,
'markers': {str(k): v for k, v in self.markers.items()}, # Convert keys to strings for JSON
'cursor_step': self.cursor_step,
'ppm': self.ppm,
}
try:
with open(self.settings_file, 'w') as f:
json.dump(settings, f, indent=4)
self.display_message = "Settings saved successfully"
except Exception as e:
self.display_message = f"Error saving settings: {str(e)}"
self.message_time = time.time()
def add_msg(self,msg):
self.display_message = msg
self.message_time = time.time()
def load_settings(self):
"""Load settings from JSON file"""
try:
if os.path.exists(self.settings_file):
with open(self.settings_file, 'r') as f:
settings = json.load(f)
# Apply loaded settings
self.sample_rate = settings.get('sample_rate', self.sample_rate)
self.sdr.setSampleRate(SOAPY_SDR_RX, 0, self.sample_rate)
self.color_scheme = settings.get('color_scheme', 0)
self.scroll_speed = settings.get('scroll_speed', 1.0)
self.current_gain = settings.get('current_gain', 20)
self.sdr.setGain(SOAPY_SDR_RX, 0, self.current_gain)
self.agc_enabled = settings.get('agc_enabled', False)
self.agc_target = settings.get('agc_target', -30)
self.agc_speed = settings.get('agc_speed', 0.3)
self.peak_hold = settings.get('peak_hold', False)
self.averaging = settings.get('averaging', False)
self.auto_scale = settings.get('auto_scale', True)
# Convert marker keys back to integers
markers = settings.get('markers', {})
self.markers = {int(k): v for k, v in markers.items()}
self.cursor_step = settings.get('cursor_step', 0.1e6)
self.ppm = settings.get('ppm', 0)
self.display_message = "Settings loaded successfully"
except Exception as e:
self.display_message = f"Error loading settings: {str(e)}"
self.message_time = time.time()
def check_keyboard(self):
"""Non-blocking keyboard check"""
if select.select([sys.stdin], [], [], 0)[0] != []:
char = sys.stdin.read(1)
# Check if character is a digit and handle shift state
if char in '12345':
marker_num = int(char)
if marker_num in self.markers:
self.cursor_freq = self.markers[marker_num]
self.add_msg(f"Jumped to marker {marker_num}: {self.cursor_freq/1e6:.3f} MHz")
else:
self.add_msg(f"Marker {marker_num} not set")
# Handle marker sets (6-0 sets markers 1-5)
elif char in '67890':
marker_map = {'6': 1, '7': 2, '8': 3, '9': 4, '0': 5}
marker_num = marker_map[char]
self.markers[marker_num] = self.cursor_freq
self.add_msg(f"Marker {marker_num} set to {self.cursor_freq/1e6:.3f} MHz")
elif char == '<': # Input start frequency
# Temporarily restore normal terminal behavior for input
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
self.paused = True
# Get user input
os.system('clear')
start_input = input("\nEnter start frequency in MHz: ")
try:
new_start = float(start_input) * 1e6 # Convert MHz to Hz
# Validate frequency is within reasonable range
if 24e6 <= new_start < self.end_freq: # typical RTL-SDR range
self.start_freq = new_start
self.freq_range = self.end_freq - self.start_freq
self.center_freq = self.start_freq + (self.freq_range / 2)
self.sdr.setFrequency(SOAPY_SDR_RX, 0, self.center_freq)
self.clear_heatmap() # Clear display
self.add_msg(f"Frequency range: {self.start_freq/1e6:.3f}-{self.end_freq/1e6:.3f} MHz")
else:
self.add_msg("Start frequency must be between 24 MHz and end frequency")
except ValueError:
self.add_msg("Invalid frequency format. Please enter a number.")
finally:
# Restore non-blocking input mode
tty.setcbreak(sys.stdin.fileno())
self.paused = False
elif char == '>': # Input end frequency
# Temporarily restore normal terminal behavior for input
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
self.paused = True
# Get user input
os.system('clear')
end_input = input("\nEnter end frequency in MHz: ")
try:
new_end = float(end_input) * 1e6 # Convert MHz to Hz
# Validate frequency is within reasonable range
if self.start_freq < new_end <= 1766e6: # typical RTL-SDR range
self.end_freq = new_end
self.freq_range = self.end_freq - self.start_freq
self.center_freq = self.start_freq + (self.freq_range / 2)
self.sdr.setFrequency(SOAPY_SDR_RX, 0, self.center_freq)
self.clear_heatmap() # Clear display
self.add_msg(f"Frequency range: {self.start_freq/1e6:.3f}-{self.end_freq/1e6:.3f} MHz")
else:
self.add_msg(f"End frequency must be between start frequency and 1766 MHz")
except ValueError:
self.add_msg("Invalid frequency format. Please enter a number.")
finally:
# Restore non-blocking input mode
tty.setcbreak(sys.stdin.fileno())
self.paused = False
elif char == 'h': # Show help
self.show_help()
elif char == ' ': # Space key to toggle pause
self.paused = not self.paused
self.add_msg("Scanning " + ("paused" if self.paused else "resumed"))
elif char == 'k': # Toggle peak hold
self.peak_hold = not self.peak_hold
self.add_msg(f"Peak hold {'enabled' if self.peak_hold else 'disabled'}")
elif char == 'v': # Toggle averaging
self.averaging = not self.averaging
self.add_msg(f"Averaging {'enabled' if self.averaging else 'disabled'}")
elif char == 'l': # Toggle auto-scaling
self.auto_scale = not self.auto_scale
self.add_msg(f"Auto-scaling {'enabled' if self.auto_scale else 'disabled'}")
elif char == 't': # Cycle color scheme
self.color_scheme = (self.color_scheme + 1) % 6 # Update to cycle through 6 schemes
schemes = ['Default', 'Hot', 'Viridis', 'Plasma', 'Magma', 'Grayscale']
self.add_msg(f"Color scheme: {schemes[self.color_scheme]}")
elif char == '+': # Zoom in around cursor
# Calculate new range (half the current range)
new_range = max(0.5e6, self.freq_range * 0.5)
# Calculate how much to adjust start/end to maintain cursor position
cursor_ratio = (self.cursor_freq - self.start_freq) / self.freq_range
range_change = self.freq_range - new_range
# Adjust start and end frequencies while keeping cursor position ratio
new_start = self.start_freq + (range_change * cursor_ratio)
new_end = new_start + new_range
# Check if new range is within original bounds
if self.start_freq <= new_start and new_end <= self.end_freq:
self.freq_range = new_range
self.center_freq = new_start + (new_range / 2)
self.sdr.setFrequency(SOAPY_SDR_RX, 0, self.center_freq)
self.clear_heatmap() # Clear display when zooming
self.add_msg(f"Zoom: {self.freq_range/1e6:.1f} MHz span")
else:
self.add_msg(f"Cannot zoom further: would exceed frequency bounds")
elif char == '-': # Zoom out around cursor
# Calculate new range (double the current range)
new_range = min(self.end_freq - self.start_freq, self.freq_range * 2)
# Calculate how much to adjust start/end to maintain cursor position
cursor_ratio = (self.cursor_freq - self.start_freq) / self.freq_range
range_change = new_range - self.freq_range
# Adjust start and end frequencies while keeping cursor position ratio
new_start = self.start_freq - (range_change * cursor_ratio)
new_end = new_start + new_range
# Check if new range is within original bounds
if new_start >= self.start_freq and new_end <= self.end_freq:
self.freq_range = new_range
self.center_freq = new_start + (new_range / 2)
self.sdr.setFrequency(SOAPY_SDR_RX, 0, self.center_freq)
self.clear_heatmap() # Clear display when zooming
self.add_msg(f"Zoom: {self.freq_range/1e6:.1f} MHz span")
else:
self.add_msg("Cannot zoom further: would exceed frequency bounds")
elif char == 'w': # Slow down waterfall
self.scroll_speed = max(0.05, self.scroll_speed - 0.05)
self.add_msg(f"Waterfall speed: {self.scroll_speed:.2f}x")
elif char == 'W': # Speed up waterfall
self.scroll_speed = min(2.0, self.scroll_speed + 0.05)
self.add_msg(f"Waterfall speed: {self.scroll_speed:.2f}x")
elif char == 'R': # Toggle recording
if not self.recording:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.record_file = f"spectrum_{timestamp}.iq"
self.recording = True
self.add_msg(f"Recording to {self.record_file}")
else:
self.recording = False
self.record_file = None
self.add_msg("Recording stopped")
elif char == 's': # Save screenshot
# Calculate frequency range
freq_start = self.center_freq - (self.freq_range / 2)
freq_end = self.center_freq + (self.freq_range / 2)
# Create timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Get script directory
script_dir = os.path.dirname(os.path.abspath(__file__))
# Create filename with timestamp and frequency range
filename = os.path.join(script_dir,
f"spectrum_{timestamp}_{freq_start/1e6:.3f}-{freq_end/1e6:.3f}MHz.png")
# Create PIL image from current display
img = Image.fromarray(self.get_display_array())
img.save(filename)
self.add_msg(f"Saved screenshot to {filename}")
elif char == 'q': # Quit on 'q'
self.add_msg("Quitting...")
self.cleanup()
os._exit(0) # Force exit the program
elif char == '[': # Existing controls
self.cursor_freq = max(
self.center_freq - (self.freq_range / 2),
self.cursor_freq - self.cursor_step
)
elif char == ']':
self.cursor_freq = min(
self.center_freq + (self.freq_range / 2),
self.cursor_freq + self.cursor_step
)
elif char == ',': # Fine control (0.001MHz = 1kHz)
self.cursor_freq = max(
self.center_freq - (self.freq_range / 2),
self.cursor_freq - 0.001e6
)
elif char == '.':
self.cursor_freq = min(
self.center_freq + (self.freq_range / 2),
self.cursor_freq + 0.001e6
)
elif char == '{': # Existing controls
self.cursor_freq = max(
self.center_freq - (self.freq_range / 2),
self.cursor_freq - self.cursor_step*2
)
elif char == '}':
self.cursor_freq = min(
self.center_freq + (self.freq_range / 2),
self.cursor_freq + self.cursor_step*2
)
elif char == 'j': # Jump to frequency
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
self.paused = True
os.system('clear')
freq_input = input("\nEnter frequency (append 'M' for MHz, or Hz by default): ")
try:
# Remove any spaces and convert to uppercase
freq_input = freq_input.strip().upper()
# Check if input ends with 'M' for MHz
if freq_input.endswith('M'):
freq = float(freq_input[:-1]) * 1e6 # Convert MHz to Hz
else:
freq = float(freq_input) # Assume Hz
# Validate frequency is within range
if self.start_freq <= freq <= self.end_freq:
self.cursor_freq = freq
self.add_msg(f"Jumped to {freq/1e6:.3f} MHz")
else:
self.add_msg(f"Frequency must be between {self.start_freq/1e6:.3f} and {self.end_freq/1e6:.3f} MHz")
except ValueError:
self.add_msg("Invalid frequency format")
finally:
# Restore non-blocking input mode
tty.setcbreak(sys.stdin.fileno())
self.paused = False
elif char == 'd': # Set gain
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
self.paused = True
os.system('clear')
gain_input = input("\nEnter gain (0-49.6 dB): ")
try:
gain = float(gain_input)
if 0 <= gain <= 49.6:
self.sdr.setGain(SOAPY_SDR_RX, 0, gain)
self.add_msg(f"Gain set to: {gain:.1f} dB")
else:
self.add_msg("Gain must be between 0 and 49.6 dB")
except ValueError:
self.add_msg("Invalid gain format")
finally:
# Restore non-blocking input mode
tty.setcbreak(sys.stdin.fileno())
self.paused = False
elif char == 'r': # Sample rate control
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
os.system('clear')
rate_input = input("\nEnter sample rate in MHz (0.25-3.2): ")
try:
new_rate = float(rate_input) * 1e6
if 0.25e6 <= new_rate <= 3.2e6:
self.sdr.setSampleRate(SOAPY_SDR_RX, 0, new_rate)
self.sample_rate = new_rate
self.add_msg(f"Sample rate set to: {new_rate/1e6:.2f} MHz")
else:
self.add_msg("Rate out of valid range (0.25-3.2 MHz)")
except ValueError:
self.add_msg("Invalid rate format. Please enter a number.")
finally:
tty.setcbreak(sys.stdin.fileno())
elif char == 'b': # Band selection
# Temporarily restore normal terminal behavior for input
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
self.paused = True
selected_band = self.show_band_selection()
if selected_band:
new_start, new_end = self.bands[selected_band]
# Update frequency range
self.start_freq = new_start
self.end_freq = new_end
self.freq_range = new_end - new_start
self.center_freq = new_start + (self.freq_range / 2)
self.sdr.setFrequency(SOAPY_SDR_RX, 0, self.center_freq)
# Update cursor to center of new band
self.cursor_freq = self.center_freq
# Clear the heatmap for the new band
self.clear_heatmap()
self.display_message = f"Switched to {selected_band} band"
finally:
# Restore non-blocking input mode
tty.setcbreak(sys.stdin.fileno())
self.paused = False
os.system('clear')
elif char == 'a': # AGC Toggle (using 'k' for automatic)
self.agc_enabled = not self.agc_enabled
if self.agc_enabled:
self.agc_history = [] # Reset history when enabling
self.display_message = "AGC enabled"
else:
self.display_message = "AGC disabled"
self.message_time = time.time()
elif char == 'A': # AGC target
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
self.paused = True
target = input("\nEnter AGC target level (dB): ")
try:
new_target = float(target)
if -60 <= new_target <= 0:
self.agc_target = new_target
self.display_message = f"AGC target set to {new_target} dB"
else:
self.display_message = "Target must be between -60 and 0 dB"
except ValueError:
self.display_message = "Invalid target value"
finally:
tty.setcbreak(sys.stdin.fileno())
self.paused = False
self.message_time = time.time()
elif char == 'z': # AGC speed
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
try:
self.paused = True
os.system('clear')
speed = input("\nEnter AGC speed (0.1-1.0): ")
try:
new_speed = float(speed)
if 0.1 <= new_speed <= 1.0:
self.agc_speed = new_speed
self.display_message = f"AGC speed set to {new_speed}"
else:
self.display_message = "Speed must be between 0.1 and 1.0"
except ValueError:
self.display_message = "Invalid speed value"
finally:
tty.setcbreak(sys.stdin.fileno())
self.paused = False
self.message_time = time.time()
elif char == 'y': # Save settings
self.save_settings()
elif char == 'l': # Load settings
self.load_settings()
elif char == 'i': # Show band information
self.show_band_info()
elif char == 'n': # Add annotation
self.add_time_annotation()
elif char == 'e': # Export data
self.export_spectrum_data()
elif char == 'p': # Decrease PPM
self.ppm = max(-100, self.ppm - 1) # Limit to -100 PPM
if hasattr(self.sdr, 'setFrequencyCorrection'):
self.sdr.setFrequencyCorrection(SOAPY_SDR_RX, 0, self.ppm)
self.add_msg(f"PPM correction: {self.ppm}")
elif char == 'P': # Increase PPM
self.ppm = min(100, self.ppm + 1) # Limit to +100 PPM
if hasattr(self.sdr, 'setFrequencyCorrection'):
self.sdr.setFrequencyCorrection(SOAPY_SDR_RX, 0, self.ppm)
self.add_msg(f"PPM correction: {self.ppm}")
elif char == 'g': # Decrease gain
new_gain = max(0, self.current_gain - 1) # Decrease by 1 dB, minimum 0
self.sdr.setGain(SOAPY_SDR_RX, 0, new_gain)
self.current_gain = new_gain
self.add_msg(f"Gain: {self.current_gain:.1f} dB")
elif char == 'G': # Increase gain
new_gain = min(49.6, self.current_gain + 1) # Increase by 1 dB, maximum 49.6
self.sdr.setGain(SOAPY_SDR_RX, 0, new_gain)
self.current_gain = new_gain
self.add_msg(f"Gain: {self.current_gain:.1f} dB")
elif char == 'S': # Toggle automatic screenshots
self.auto_export_enabled = not self.auto_export_enabled
self.add_msg(f"Automatic screenshots {'enabled' if self.auto_export_enabled else 'disabled'}")
def get_power_spectrum(self):
"""Get the power spectrum using SoapySDR with improved error handling"""
start_time = time.perf_counter()
# Use pre-calculated FFT size
buffer = np.zeros(self.fft_size, np.complex64)
# Read samples with timeout and retry mechanism
max_retries = 3
for retry in range(max_retries):
try:
status = self.sdr.readStream(self.rx_stream, [buffer], len(buffer), timeoutUs=1000000)
if status.ret > 0: # Successful read
# Process only valid samples
valid_samples = buffer[:status.ret]
# Apply pre-calculated window and compute FFT
windowed_samples = valid_samples * self._window[:len(valid_samples)]
fft = np.fft.fft(windowed_samples)
fft_shifted = np.fft.fftshift(fft)
# Calculate power spectrum
power_db = 20 * np.log10(np.abs(fft_shifted) + 1e-15)
# Process spectrum through enhanced signal processing
power_db = self.process_spectrum(power_db)
# Resample to match display width
power_db_resized = signal.resample(
power_db,
self.graph_width,
window=('kaiser', 8.0)
)
# Update scan timing statistics
scan_duration = int((time.perf_counter() - start_time) * 1000)
if scan_duration > 0:
self.scan_times.append(scan_duration)
if len(self.scan_times) > self.scan_times_max:
self.scan_times.pop(0)
self.last_scan_time = int(sum(self.scan_times) / len(self.scan_times))
return power_db_resized
elif status.ret == -4: # Timeout
if retry < max_retries - 1:
time.sleep(0.1)
continue
else:
self.display_message = "Stream timeout after retries"
return np.zeros(self.graph_width)
else:
self.display_message = f"Stream error: {status.ret}"
return np.zeros(self.graph_width)
except Exception as e:
if retry < max_retries - 1:
self.display_message = f"Read error, retrying... ({e})"
time.sleep(0.1)
else:
self.display_message = f"Failed to read spectrum: {e}"
return np.zeros(self.graph_width)
return np.zeros(self.graph_width)
def update_agc(self, spectrum):
"""Update AGC based on current signal levels"""
if not self.agc_enabled:
return
current_time = time.time()
if current_time - self.last_agc_update < self.agc_update_interval:
return
# Calculate current average power
avg_power = np.mean(spectrum)
self.agc_history.append(avg_power)
if len(self.agc_history) > self.agc_history_len:
self.agc_history.pop(0)
# Calculate smoothed power level
smoothed_power = np.mean(self.agc_history)
# Calculate error from target
error = self.agc_target - smoothed_power
# Calculate new gain
gain_delta = error * self.agc_speed
new_gain = np.clip(
self.current_gain + gain_delta,
self.agc_min_gain,
self.agc_max_gain
)
# Update gain if it changed significantly (avoid tiny adjustments)
if abs(new_gain - self.current_gain) > 0.5:
self.current_gain = new_gain
self.sdr.setGain(SOAPY_SDR_RX, 0, self.current_gain)