-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpyspecsdr.py
executable file
·3147 lines (2658 loc) · 124 KB
/
pyspecsdr.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/python3
'''
____ ____ ____ ____ ____
| _ \ _ _/ ___| _ __ ___ ___/ ___|| _ \| _ \
| |_) | | | \___ \| '_ \ / _ \/ __\___ \| | | | |_) |
| __/| |_| |___) | |_) | __/ (__ ___) | |_| | _ <
|_| \__, |____/| .__/ \___|\___|____/|____/|_| \_\
|___/ |_|
PySpecSDR - Python SDR Spectrum Analyzer and Signal Processor
===========================================================
A feature-rich Software Defined Radio (SDR) spectrum analyzer with real-time
visualization, demodulation, and signal analysis capabilities.
Features:
- Real-time spectrum analysis and waterfall display
- Multiple visualization modes (spectrum, waterfall, persistence, surface, gradient)
- FM, AM, SSB demodulation with audio output
- Frequency scanning and signal classification
- Bookmark management for frequencies of interest
- Automatic Gain Control (AGC)
- Recording capabilities for both RF and audio
- Band presets for common frequency ranges
- Configurable display and processing parameters
Requirements:
- RTL-SDR compatible device
- Python 3.7 or higher
- Dependencies listed in requirements.txt
License: GPL-3.0-or-later
Copyright (c) 2024 [XQTR]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Author: XQTR
Email: [email protected] // [email protected]
GitHub: https://github.com/xqtr/PySpecSDR
Version: 1.0.5
Last Updated: 2024/12/15
Usage:
python3 pyspecsdr.py
Key Bindings:
q - Quit
h - Show help menu
For full list of controls, press 'h' while running
Changelog:
Read the CHANGELOG.md file
'''
from pyspecconst import *
import numpy as np
import curses
from rtlsdr import RtlSdr
from scipy.signal import decimate
import sounddevice as sd
from scipy.signal import butter, lfilter
from scipy.signal import firwin
from scipy.signal import bilinear
from scipy.signal import hilbert
from scipy.signal import welch
from collections import deque
import time
import os
import configparser
import json
import os.path
import wave
import struct
import SoapySDR
from SoapySDR import SOAPY_SDR_RX, SOAPY_SDR_CF32
import signal
import pyspecaprs
audio_buffer = deque(maxlen=24) # Increased from 16 for better continuity
SAMPLES = 7
INTENSITY_CHARS = ' .,:|\\' # Simple ASCII characters for intensity levels
BOOKMARK_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sdr_bookmarks.json")
SETTINGS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sdr_settings.ini")
PIPE_PATH = "/tmp/sdrpipe"
PIPE_FILE = None
USE_PIPE = False
# Add global flag for audio availability
AUDIO_AVAILABLE = False
try:
import sounddevice as sd
AUDIO_AVAILABLE = True
except ImportError:
pass
# Add these constants near the top of the file
AGC_TARGET_POWER = -30 # Target power level in dB
AGC_ENABLED = False # Global flag for AGC state
AGC_UPDATE_INTERVAL = 0.5 # Seconds between AGC updates
AGC_STEP = 1.0 # Gain adjustment step size
last_agc_update = 0 # Track last AGC update time
SIGNAL_THRESHOLD = -40 # dB threshold for signal detection
SCAN_STEP = 100e3 # 100 kHz steps by default
MIN_SIGNAL_BANDWIDTH = 50e3 # Minimum bandwidth to consider as a signal
SCAN_DWELL_TIME = 0.1 # Seconds to dwell on each frequency
SCAN_ACTIVE = False # Global flag for scan state
# Add these constants near the top with other constants
WATERFALL_HISTORY = []
WATERFALL_MAX_LINES = 30 # Number of history lines to keep
WATERFALL_MODE = False # Toggle between spectrum and waterfall
WATERFALL_COLORS = [
curses.COLOR_BLACK, # Weakest signal
curses.COLOR_BLUE,
curses.COLOR_CYAN,
curses.COLOR_GREEN,
curses.COLOR_YELLOW,
curses.COLOR_RED, # Strongest signal
]
# Add these constants near the top with other constants
DEMOD_MODES = {
'NFM': {'name': 'NFM', 'bandwidth': 200e3, 'description': 'Narrow FM'},
'WFM': {'name': 'Wide FM', 'bandwidth': 180e3, 'description': 'Wide FM (Broadcast)'},
'AM': {'name': 'AM', 'bandwidth': 10e3, 'description': 'Amplitude Modulation'},
'USB': {'name': 'USB', 'bandwidth': 3e3, 'description': 'Upper Sideband'},
'LSB': {'name': 'LSB', 'bandwidth': 3e3, 'description': 'Lower Sideband'},
'RAW': {'name': 'RAW', 'bandwidth': None, 'description': 'Raw IQ Samples'}
}
CURRENT_DEMOD = 'NFM' # Default demodulation mode
# Add this with other constants near the top of the file
zoom_step = 0.1e6 # 100 kHz zoom step
# Add near other constants
PERSISTENCE_HISTORY = []
PERSISTENCE_ALPHA = 0.7 # Decay factor
PERSISTENCE_LENGTH = 10 # Number of traces to keep
PERSISTENCE_MODE = False
# Add near other constants
SURFACE_MODE = False
SURFACE_ANGLE = 45 # Viewing angle in degrees
# Add near other constants
GRADIENT_COLORS = [
(0, 0, 0), # Black
(0, 0, 139), # Dark Blue
(0, 0, 255), # Blue
(0, 255, 255), # Cyan
(0, 255, 0), # Green
(255, 255, 0), # Yellow
(255, 0, 0), # Red
]
# Add with other constants
DISPLAY_MODES = ['SPECTRUM', 'WATERFALL', 'PERSISTENCE', 'SURFACE', 'GRADIENT', 'VECTOR']
current_display_mode = 'SPECTRUM'
# Add near the top with other constants
DEFAULT_PPM = 0 # Default PPM correction value
# Add near the top with other global variables
LAST_SCAN_RESULTS = [] # Store the last scan results
# Variable to save the RTL command
RTL_COMMAND = ""
def init_colors():
curses.start_color()
curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_BLUE, curses.COLOR_BLACK)
# Add waterfall color pairs (starting from 10 to avoid conflicts)
for i, color in enumerate(WATERFALL_COLORS):
curses.init_pair(10 + i, color, curses.COLOR_BLACK)
def showhelp(stdscr):
"""Display help information with scrolling capability"""
max_height, max_width = stdscr.getmaxyx()
# Calculate total content height
total_height = sum(2 + len(section[1]) for section in help_content) + 15
# Initialize scroll position
scroll_pos = 0
max_scroll = max(0, total_height - (max_height - 2))
stdscr.nodelay(0)
while True:
# Clear screen
stdscr.clear()
current_line = 0
# Draw title
title = "PySpecSDR Help"
stdscr.addstr(0, 2, title, curses.color_pair(1) | curses.A_BOLD)
current_line += 1
# Draw horizontal line
stdscr.addstr(1, 1, "-" * (max_width - 2), curses.color_pair(2))
current_line += 1
# Draw visible content
visible_line = 0
startline = 2
for section_title, commands in help_content:
if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
try:
stdscr.addstr(startline + current_line - scroll_pos, 2,
"+" + "-" * (len(section_title) + 2) + "+",
curses.color_pair(4))
except curses.error:
pass
current_line += 1
if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
try:
stdscr.addstr(startline + current_line - scroll_pos, 2,
"| " + section_title + " |",
curses.color_pair(4) | curses.A_BOLD)
except curses.error:
pass
current_line += 1
if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
try:
stdscr.addstr(startline + current_line - scroll_pos, 2,
"+" + "-" * (len(section_title) + 2) + "+",
curses.color_pair(4))
except curses.error:
pass
current_line += 1
for key, description in commands:
if current_line - scroll_pos >= 0 and current_line - scroll_pos < max_height - 3:
try:
key_str = f"[ {key:6} ]"
stdscr.addstr(startline + current_line - scroll_pos, 4, key_str,
curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(startline + current_line - scroll_pos, 15, "->",
curses.color_pair(2))
stdscr.addstr(startline + current_line - scroll_pos, 18, description,
curses.color_pair(2))
except curses.error:
pass
current_line += 1
current_line += 1
# Draw scrollbar
if total_height > max_height - 2:
for y in range(2, max_height - 1):
pos = int((y - 2) * total_height / (max_height - 3))
if pos >= scroll_pos and pos <= scroll_pos + max_height:
char = "#"
else:
char = "|"
try:
stdscr.addstr(y, max_width - 1, char, curses.color_pair(2))
except curses.error:
pass
# Draw navigation instructions
nav_text = "[ UP/DOWN | PgUp/PgDn | q:Exit ]"
nav_pos = (max_width - len(nav_text)) // 2
try:
stdscr.addstr(max_height - 1, nav_pos, nav_text,
curses.color_pair(5) | curses.A_BOLD)
except curses.error:
pass
stdscr.refresh()
# Handle input
key = stdscr.getch()
if key == ord('q'):
break
elif key == curses.KEY_UP and scroll_pos > 0:
scroll_pos = max(0, scroll_pos - 1)
elif key == curses.KEY_DOWN and scroll_pos < max_scroll:
scroll_pos = min(max_scroll, scroll_pos + 1)
elif key == curses.KEY_PPAGE: # Page Up
scroll_pos = max(0, scroll_pos - (max_height - 3))
elif key == curses.KEY_NPAGE: # Page Down
scroll_pos = min(max_scroll, scroll_pos + (max_height - 3))
# Restore original nodelay state
stdscr.nodelay(True)
# Pipe Functions
def create_pipe():
global PIPE_PATH
"""Create a named pipe for output."""
try:
os.mkfifo(PIPE_PATH)
except FileExistsError:
pass # Pipe already exists
def open_file_pipe():
#Open file and return value
#fifo = open(PIPE_PATH, 'wb', buffering=0)
fifo = open(PIPE_PATH, 'wb', os.O_NONBLOCK)
return fifo
def write_to_pipe(fifof,data,stdscr):
"""Write audio data to the named pipe."""
if data.dtype != np.int16:
data = np.int16(data * 32767)
fifof.write(data)
def close_file_pipe(fifo):
fifo.close
def clean_pipe(signum, frame):
"""Cleanup function to remove the named pipe."""
if os.path.exists(PIPE_PATH):
#os.remove(PIPE_PATH)
os.unlink(PIPE_PATH)
def start_pipe_recording(stdscr):
global PIPE_FILE, PIPE_PATH,USE_PIPE
create_pipe()
PIPE_FILE = open_file_pipe()
USE_PIPE = True
stdscr.addstr(0, 0, f"Started recording to {PIPE_PATH}", curses.color_pair(4))
time.sleep(1)
def stop_pipe_recording(stdscr):
global PIPE_FILE, PIPE_PATH,USE_PIPE
USE_PIPE = False
close_file_pipe(PIPE_FILE)
clean_pipe(None,None)
PIPE_FILE = None
stdscr.addstr(0, 0, "Recording stopped", curses.color_pair(4))
time.sleep(1)
signal.signal(signal.SIGINT, clean_pipe)
signal.signal(signal.SIGTERM, clean_pipe) # Handle termination signal
def setfreq(stdscr):
draw_clearheader(stdscr)
stdscr.addstr(0,0,"Enter frequency in Hz: ",curses.color_pair(1) | curses.A_BOLD)
# Enable echo and cursor
curses.echo()
curses.curs_set(1)
stdscr.nodelay(False)
freq = stdscr.getstr()
draw_clearheader(stdscr)
# Disable echo and cursor after input
curses.noecho()
curses.curs_set(0)
stdscr.nodelay(True)
res = freq.decode('utf-8') # Convert bytes to string
if len(res)<3: return None
if res[-1] in 'mM' or res[-1] in 'kK':
num = res[:-1]
try:
int(num)
except:
return None
else:
try:
int(freq)
except:
return None
return res
def draw_clearheader(stdscr):
max_height, max_width = stdscr.getmaxyx()
stdscr.addstr(0, 0, " "*(max_width-1))
stdscr.addstr(1, 0, " "*(max_width-1))
def draw_header(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
sdr, is_recording=False, recording_duration=None):
max_height, max_width = stdscr.getmaxyx()
x_pos = 0
if is_recording:
recording_text = f"Recording: {recording_duration:.1f}s"
stdscr.addstr(0, max_width - len(recording_text) - 1, recording_text,
curses.color_pair(3) | curses.A_BOLD)
available_width = max_width - len(recording_text) - 2
else:
available_width = max_width
# Draw the colored header
freq_text = f"req: {center_freq/1e6:.6f} MHz"
bw_text = f"andwidth: {bandwidth/1e6:.2f} MHz"
gain_text = f"ain: {gain}"
samples_text = f"amples: {2**SAMPLES}"
step_text = f"ep: {step/1e6:.3f} MHz"
ppm_text = f"PM: {sdr.ppm}" # Add PPM text
agc_text = f"GC: {'On' if AGC_ENABLED else 'Off'}"
x_pos = 0
stdscr.addstr(0, x_pos, "F", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(0, x_pos+1, freq_text, curses.color_pair(2))
x_pos += len(freq_text) + 3
stdscr.addstr(0, x_pos, "B", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(0, x_pos+1, bw_text, curses.color_pair(2))
x_pos += len(bw_text) + 3
stdscr.addstr(0, x_pos, "G", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(0, x_pos+1, gain_text, curses.color_pair(2))
x_pos = 0
stdscr.addstr(1, x_pos, "S", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(1, x_pos+1, samples_text, curses.color_pair(2))
x_pos += len(samples_text) + 3
stdscr.addstr(1, x_pos, "S", curses.color_pair(2))
stdscr.addstr(1, x_pos+1, "t", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(1, x_pos+2, step_text, curses.color_pair(2))
x_pos += len(step_text) + 4
try:
stdscr.addstr(1, x_pos, "P", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(1, x_pos+1, ppm_text, curses.color_pair(2))
except curses.error:
pass # Ignore if screen is too small
x_pos += len(ppm_text) + 4
stdscr.addstr(1, x_pos, "A", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(1, x_pos+1, agc_text, curses.color_pair(2))
# Add signal strength indicator
peak_power = np.max(freq_data)
avg_power = np.mean(freq_data)
strength_text = f"Peak: {peak_power:.1f} dB Avg: {avg_power:.1f} dB"
stdscr.addstr(1, max_width - len(strength_text) - 1, strength_text, curses.color_pair(2))
#debug string
#txt = str(sdr.sample_rate)
#stdscr.addstr(0, max_width - len(txt) - 1, txt, curses.color_pair(2) | curses.A_BOLD)
def draw_spectrogram(stdscr, freq_data, frequencies, center_freq, bandwidth, gain, step,
sdr, is_recording=False, recording_duration=None):
"""Draw the spectrum display with improved signal-to-noise ratio visualization"""
max_height, max_width = stdscr.getmaxyx()
# Calculate display dimensions
display_width = max_width - 10 # Reserve space for dB scale
display_height = max_height - 4 # Reserve space for header and labels
# Clear the display area (preserve header)
for y in range(2, max_height-1):
try:
stdscr.addstr(y, 0, " " * (max_width-1), curses.color_pair(1))
except curses.error:
pass
# Set fixed dB range for display with noise floor adjustment
min_db = np.min(freq_data[np.isfinite(freq_data)])
max_db = np.max(freq_data[np.isfinite(freq_data)])
# Calculate noise floor (using lower percentile)
noise_floor = np.percentile(freq_data[np.isfinite(freq_data)], 20)
# Adjust dynamic range to emphasize signals above noise
db_range = max_db - noise_floor
display_min = noise_floor - (db_range * 0.1) # Show some noise below floor
display_max = max_db + (db_range * 0.05) # Add headroom
# Draw dB scale on the left
for i in range(display_height):
db_value = display_max - (i * (display_max - display_min) / display_height)
if i % 3 == 0: # Show scale every 3 lines
db_label = f"{db_value:4.0f}dB"
try:
stdscr.addstr(i + 2, 0, db_label, curses.color_pair(2))
# Add scale markers
stdscr.addstr(i + 2, 8, "|", curses.color_pair(2))
except curses.error:
pass
# Normalize data for display using adjusted range
normalized_data = np.clip((freq_data - display_min) / (display_max - display_min), 0, 1)
# Apply non-linear scaling to emphasize signals
normalized_data = np.power(normalized_data, 0.7) # Adjust exponent to taste
# Resample data to fit display width
resampled = np.interp(
np.linspace(0, len(normalized_data) - 1, display_width),
np.arange(len(normalized_data)),
normalized_data
)
# Draw spectrum with improved character selection
for x, value in enumerate(resampled):
if np.isfinite(value):
# Calculate height in display units
height = int(value * display_height)
height = min(height, display_height)
# First clear the entire column
for y in range(display_height):
try:
stdscr.addstr(y + 2, x + 9, " ", curses.color_pair(1))
except curses.error:
pass
# Then draw the bar with varied characters based on signal strength
peak_height = 0
for y in range(display_height - height, display_height):
try:
# Calculate relative position in the bar
rel_pos = (y - (display_height - height)) / height if height > 0 else 0
# Select character based on signal strength and position
if value > 0.8: # Strong signals
char = "#" if rel_pos > 0.5 else "="
elif value > 0.4: # Medium signals
char = "=" if rel_pos > 0.5 else "-"
elif value > 0.2: # Weak signals
char = "-" if rel_pos > 0.5 else "."
else: # Noise level
if rel_pos > 0.7:
char = "."
else:
char = " "
stdscr.addstr(y + 2, x + 9, char, curses.color_pair(1))
except curses.error:
pass
# Use standardized frequency labels
draw_frequency_labels(stdscr, center_freq, bandwidth, display_height, display_width)
# Run this function before using the rtl-sdr samples to remove dc offset and correct iq
def iq_correction(samples: np.ndarray) -> np.ndarray:
# Remove DC and calculate input power
centered_samples = samples - np.mean(samples)
input_power = np.var(centered_samples)
# Calculate scaling factor for Q
q_amplitude = np.sqrt(2 * np.mean(samples.imag ** 2))
# Normalize Q component
normalized_samples = samples / q_amplitude
i_samples, q_samples = normalized_samples.real, normalized_samples.imag
# Estimate alpha and sin_phi
alpha_est = np.sqrt(2 * np.mean(i_samples ** 2))
sin_phi_est = (2 / alpha_est) * np.mean(i_samples * q_samples)
# Estimate cos_phi
cos_phi_est = np.sqrt(1 - sin_phi_est ** 2)
# Apply phase and amplitude correction
i_new = (1 / alpha_est) * i_samples
q_new = (-sin_phi_est / alpha_est) * i_samples + q_samples
# Corrected signal
corrected_samples = (i_new + 1j * q_new) / cos_phi_est
# Calculate and print phase and amplitude errors
phase_error_deg = np.round(np.abs(np.arccos(cos_phi_est) * 180 / np.pi), 4)
amplitude_error_db = np.round(np.abs(20 * np.log10(alpha_est)), 4)
# Print phase and amplitude errors
#print(f"Phase Error: {phase_error_deg}")
#print(f"Amplitude Error: {amplitude_error_db}")
return corrected_samples * np.sqrt(input_power / np.var(corrected_samples))
def decode_mono(samples: np.ndarray, fs: int):
"""Decode FM modulation to mono audio."""
demod_gain = fs / (2 * np.pi * np.pi * 75e3) # 75e3 is the frequency deviation
# FM Demodulation
demod = demod_gain * np.angle(samples[:-1] * samples.conj()[1:])
# Sample rate after decimation will be 41666.67
decimation = 6
# Decimate to get mono audio
#mono = signal.decimate(demod, decimation, ftype="fir")
mono = decimate(demod, decimation, ftype="fir")
# De-emphasis is 75e-6 for North America, 50e-6 for everywhere else
deemphasis = 75e-6
# Create filter coefficients for de-emphasis
bz, az = bilinear([1], [deemphasis, 1], fs=fs)
# Apply the de-emphasis filter
mono = lfilter(bz, az, mono)
mono -= mono.mean()
mono *= 0.75 # Volume factor
mono *= 32768
mono = mono.astype(np.int16)
return mono
def demodulate_signal(samples, sample_rate, mode='NFM'):
"""Advanced demodulation function supporting multiple modes"""
samples = iq_correction(samples)
if mode == 'NFM':
return demodulate_nfm(samples, sample_rate)
elif mode == 'WFM':
return demodulate_wfm(samples, sample_rate)
elif mode == 'AM':
return demodulate_am(samples)
elif mode == 'USB':
return demodulate_ssb(samples, sample_rate, lower=False)
elif mode == 'LSB':
return demodulate_ssb(samples, sample_rate, lower=True)
elif mode == 'RAW':
return np.real(samples) # Return raw I samples
#return np.zeros_like(samples) # Return silence if mode not recognized
return np.zeros((len(samples), 2)) # Ensure it returns a shape of (n, 2)
# Filter to cut freq below/higher than 300/3000hz
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def mono_to_stereo(mono_audio):
"""Convert mono audio to stereo by duplicating the mono signal."""
stereo_audio = np.zeros((len(mono_audio), 2)) # Initialize stereo array
stereo_audio[:, 0] = mono_audio # Left channel
stereo_audio[:, 1] = mono_audio # Right channel (duplicate)
return stereo_audio
def demodulate_nfm(samples, sample_rate, target_rate=44100):
"""Simplified FM demodulation"""
# Basic FM demodulation
demod = np.angle(samples[1:] * np.conj(samples[:-1]))
# Simple scaling
demod = demod * (sample_rate / (2 * np.pi))
# Apply the bandpass filter for NFM
lowcut = 300.0 # Low cutoff frequency
highcut = 3000.0 # High cutoff frequency
filtered_demod = bandpass_filter(demod, lowcut, highcut, sample_rate)
# Basic lowpass filter
nyq = sample_rate / 2
cutoff = 15000
taps = firwin(numtaps=65, cutoff=cutoff/nyq)
filtered = lfilter(taps, 1.0, demod)
# Simple decimation
decimation_factor = int(sample_rate / target_rate)
audio = decimate(filtered, decimation_factor)
# Basic normalization
audio = audio / np.max(np.abs(audio)) * 0.95
return mono_to_stereo(audio)
def bandpass_filter(data, lowcut, highcut, sample_rate):
"""Apply a bandpass filter to the data."""
from scipy.signal import butter, sosfilt
if lowcut <= 0:
# Use a lowpass filter if lowcut is not valid
sos = butter(10, highcut / (sample_rate / 2), btype='low', output='sos')
else:
sos = butter(10, [lowcut / (sample_rate / 2), highcut / (sample_rate / 2)], btype='band', output='sos')
return sosfilt(sos, data)
def demodulate_wfm(samples, sample_rate, target_rate=44100):
"""Wide FM demodulation with stereo decoding."""
# Step 1: FM demodulation
demod = np.angle(samples[1:] * np.conj(samples[:-1]))
# Step 2: Extract the baseband (L+R), pilot, and stereo difference (L-R) signals
# Lowpass filter for L+R (0-15 kHz)
l_plus_r = bandpass_filter(demod, 0, 15000, sample_rate)
# Bandpass filter for the 19 kHz pilot tone
pilot = bandpass_filter(demod, 19000 - 200, 19000 + 200, sample_rate)
pilot = np.sin(np.unwrap(np.angle(lfilter([1], [1, -0.99], pilot)))) # Extract phase
# Bandpass filter for the 38 kHz L-R signal
l_minus_r = bandpass_filter(demod, 38000 - 15000, 38000 + 15000, sample_rate)
l_minus_r = l_minus_r * (2 * pilot) # Demodulate using the pilot tone
# Lowpass filter the demodulated L-R signal to remove high-frequency artifacts
l_minus_r = bandpass_filter(l_minus_r, 0, 15000, sample_rate)
# Step 3: Combine L+R and L-R to get L and R
left = (l_plus_r + l_minus_r) / 2
right = (l_plus_r - l_minus_r) / 2
# Step 4: De-emphasis filter (75 µs time constant)
deemph_tc = 75e-6 # 75 µs (FM standard)
alpha = np.exp(-1 / (deemph_tc * sample_rate))
b = [1 - alpha]
a = [1, -alpha]
left = lfilter(b, a, left)
right = lfilter(b, a, right)
# Step 5: Decimate to target sample rate
decimation_factor = int(sample_rate / target_rate)
if decimation_factor > 1:
left = decimate(left, decimation_factor, zero_phase=True)
right = decimate(right, decimation_factor, zero_phase=True)
# Step 6: Normalize the audio
max_val = max(np.max(np.abs(left)), np.max(np.abs(right)))
left /= max_val
right /= max_val
# Step 7: Combine into stereo
audio = np.column_stack((left, right))
return audio
def demodulate_am(samples):
"""AM demodulation using envelope detection"""
# Get the amplitude envelope
envelope = np.abs(samples)
# DC removal (high-pass filter)
envelope = envelope - np.mean(envelope)
# Apply the bandpass filter to remove low and high frequency harmonics
fs = 44100 # Sample rate (adjust as necessary)
lowcut = 300.0 # Low cutoff frequency
highcut = 3000.0 # High cutoff frequency
filtered_envelope = bandpass_filter(envelope, lowcut, highcut, fs)
# Normalize
audio = filtered_envelope / np.max(np.abs(filtered_envelope)) * 0.95
return mono_to_stereo(audio)
def demodulate_ssb(samples, sample_rate, lower=True):
"""Single-sideband demodulation"""
# Complex bandpass filter
if lower:
# LSB: negative frequencies only
taps = firwin(65, 3000/sample_rate, window='hamming')
analytical = lfilter(taps, 1.0, samples)
analytical = hilbert(np.real(analytical))
else:
# USB: positive frequencies only
taps = firwin(65, 3000/sample_rate, window='hamming')
analytical = lfilter(taps, 1.0, samples)
analytical = hilbert(np.real(analytical))
# Demodulate
demod = np.real(analytical)
# Normalize
audio = demod / np.max(np.abs(demod)) * 0.95
return mono_to_stereo(audio)
# APRS Functions
def decode_afsk(samples, sample_rate):
"""
Demodulate Bell 202 AFSK (1200/2200 Hz)
Returns bit stream
"""
# Filter for AFSK tones
filtered_1200 = bandpass_filter(samples, 1100, 1300, sample_rate)
filtered_2200 = bandpass_filter(samples, 2100, 2300, sample_rate)
# Calculate energy in each band
window = int(sample_rate / 1200) # One bit period
bits = []
for i in range(0, len(samples) - window, window):
e1200 = np.sum(filtered_1200[i:i+window]**2)
e2200 = np.sum(filtered_2200[i:i+window]**2)
bits.append(1 if e2200 > e1200 else 0)
return bits
def decode_aprs(samples, sample_rate):
"""
Decode APRS packets from audio samples
Returns list of decoded packets
"""
# Convert to real if complex
if np.iscomplexobj(samples):
samples = np.real(samples)
# Normalize audio
samples = samples / np.max(np.abs(samples))
# Demodulate AFSK to get bit stream
bits = decode_afsk(samples, sample_rate)
# Decode AX.25 frame
packet = pyspecaprs.decode_ax25_frame(bits)
return [packet] if packet else []
def show_aprs_decoder(stdscr, sdr, sample_rate):
"""
Show APRS decoder interface
"""
stdscr.clear()
stdscr.addstr(0, 0, "APRS Decoder - Press 'q' to exit")
stdscr.addstr(2, 0, "Listening for APRS packets...")
stdscr.refresh()
while True:
# Read samples
samples = sdr.read_samples(int(sample_rate * 0.5)) # 0.5 second buffer
# Decode APRS
packets = decode_aprs(samples, sample_rate)
# Display results
if packets:
for i, packet in enumerate(packets):
if packet and 4 + i < stdscr.getmaxyx()[0]:
# Clean the packet string - remove null chars and non-printable chars
clean_packet = ''.join(c for c in packet if c.isprintable() or c.isspace())
# Truncate to screen width
max_width = stdscr.getmaxyx()[1] - 1
display_str = clean_packet[:max_width]
try:
stdscr.addstr(4 + i, 0, display_str)
except:
pass # Skip if we can't display this packet
stdscr.refresh()
# Check for quit
if stdscr.getch() == ord('q'):
break
# Morse Code functions
def decode_morse(samples, sample_rate, threshold=-20):
"""
Decode Morse code from audio samples
Args:
samples: numpy array of audio samples (complex IQ data)
sample_rate: sampling rate in Hz
threshold: signal detection threshold in dB
Returns:
decoded_text: string of decoded text
timing_data: dict with timing statistics
"""
# Convert complex samples to magnitude
envelope = np.abs(samples)
# Normalize and convert to dB
envelope = envelope / np.max(envelope)
envelope_db = 20 * np.log10(envelope + 1e-10)
# Rest of the function remains the same...
# Detect signals above threshold
signals = envelope_db > threshold
# Find transitions
transitions = np.diff(signals.astype(int))
rise_times = np.where(transitions == 1)[0]
fall_times = np.where(transitions == -1)[0]
if len(rise_times) == 0 or len(fall_times) == 0:
return "", {"dot": 0, "dash": 0, "gap": 0}
# Ensure we have matching rises and falls
if fall_times[0] < rise_times[0]:
fall_times = fall_times[1:]
if len(rise_times) > len(fall_times):
rise_times = rise_times[:-1]
# Calculate pulse durations
durations = (fall_times - rise_times) / sample_rate
gaps = (rise_times[1:] - fall_times[:-1]) / sample_rate
if len(durations) == 0:
return "", {"dot": 0, "dash": 0, "gap": 0}
# Estimate dot/dash threshold using k-means clustering
if len(durations) > 1:
from scipy.cluster import vq
centroids, _ = vq.kmeans(durations.reshape(-1, 1), 2)
dot_duration = np.min(centroids)
dash_duration = np.max(centroids)
else:
dot_duration = np.min(durations)
dash_duration = dot_duration * 3
# Classify dots and dashes
morse_symbols = []
current_letter = []
for i, duration in enumerate(durations):
# Add symbol
if duration < (dot_duration + dash_duration) / 2:
current_letter.append('.')
else:
current_letter.append('-')
# Check for letter gaps
if i < len(gaps):
if gaps[i] > dot_duration * 3:
morse_symbols.append(''.join(current_letter))
current_letter = []
# Check for word gaps
if gaps[i] > dot_duration * 7:
morse_symbols.append(' ')
# Add final letter if present
if current_letter:
morse_symbols.append(''.join(current_letter))
# Translate to text
decoded_text = ''
for symbol in morse_symbols:
if symbol == ' ':
decoded_text += ' '
elif symbol in MORSE_CODE:
decoded_text += MORSE_CODE[symbol]
else:
decoded_text += '?'
timing_data = {
"dot": dot_duration,
"dash": dash_duration,
"gap": np.mean(gaps) if len(gaps) > 0 else 0
}
return decoded_text, timing_data
def show_morse_decoder(stdscr, sdr, sample_rate):
"""Display Morse code decoder interface with continuous decoding"""
max_height, max_width = stdscr.getmaxyx()
# Save original SDR settings
original_freq = sdr.center_freq
original_sample_rate = sdr.sample_rate
original_gain = sdr.gain
try:
# Configure SDR for Morse reception
sdr.sample_rate = 48000 # Lower sample rate for CW
sdr.bandwidth = 2000 # Narrow bandwidth for CW
time.sleep(0.1) # Let the SDR settle
# Enable nodelay for continuous updates
stdscr.nodelay(True)
# Initialize display buffer for scrolling text
text_buffer = []
max_buffer_lines = max_height - 12 # Reserve space for header and timing info
while True:
try:
# Read new samples
num_samples = int(sdr.sample_rate * 0.5) # 0.5 seconds of data
samples = sdr.read_samples(num_samples)
if len(samples) == 0:
continue
# Decode the morse code
decoded_text, timing = decode_morse(samples, sdr.sample_rate)
if decoded_text.strip(): # Only add non-empty decoded text
text_buffer.append(decoded_text)
# Keep buffer size limited
if len(text_buffer) > max_buffer_lines:
text_buffer.pop(0)
# Clear screen and show results
stdscr.clear()
# Show header
header = "Morse Code Decoder (Press 'q' to quit)"