-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathodin.py
More file actions
1863 lines (1693 loc) · 68.1 KB
/
odin.py
File metadata and controls
1863 lines (1693 loc) · 68.1 KB
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
#!python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
#
# Distributed under the terms of the BSD 3-clause license.
#
# The full license is in the LICENSE file, distributed with this software.
# ----------------------------------------------------------------------------
"""Record data from synchronized USRPs in Digital RF format."""
from __future__ import absolute_import, division, print_function
import argparse
import math
import os
import re
import sys
import time
from ast import literal_eval
from datetime import datetime, timedelta
from fractions import Fraction
from itertools import chain, cycle, islice, repeat
from subprocess import call
from textwrap import dedent, fill, TextWrapper
import digital_rf as drf
import gr_digital_rf as gr_drf
import numpy as np
import pytz
from gnuradio import blocks
from gnuradio import filter as grfilter
from gnuradio import gr, uhd
import shutil
import freq_stepper
import pdb
def equiripple_lpf(cutoff=0.9, transition_width=0.2, attenuation=80, pass_ripple=None):
"""Get taps for an equiripple low-pass filter.
All frequencies given must be normalized in the range [0, 1], with 1
corresponding to the Nyquist frequency (Fs/2).
Parameters
----------
cutoff : float
Normalized cutoff frequency (beginning of transition band).
transition_width : float
Normalized width (in frequency) of transition region from pass band to
stop band.
attenuation : float
Attenuation of the stop band in dB.
pass_ripple : float | None
Maximum ripple in the pass band in dB. If None, the attenuation value
is used.
Returns
-------
taps : array_like
Type I (even order) FIR low-pass filter taps meeting the given
requirements.
"""
if pass_ripple is None:
pass_ripple = attenuation
if cutoff <= 0:
errstr = "Cutoff ({0}) must be strictly greater than zero."
raise ValueError(errstr.format(cutoff))
if transition_width <= 0:
errstr = "Transition width ({0}) must be strictly greater than zero."
raise ValueError(errstr.format(transition_width))
if cutoff + transition_width >= 1:
errstr = (
"Cutoff ({0}) + transition width ({1}) must be strictly less than"
" one, but it is {2}."
).format(cutoff, transition_width, cutoff + transition_width)
raise ValueError(errstr)
# pm_remez arguments
bands = [0, cutoff, cutoff + transition_width, 1]
ampl = [1, 1, 0, 0]
error_weight = [10 ** ((pass_ripple - attenuation) / 20.0), 1]
# get estimate for the filter order (Oppenheim + Schafer 2nd ed, 7.104)
M = ((attenuation + pass_ripple) / 2.0 - 13) / 2.324 / (np.pi * transition_width)
# round up to nearest even-order (Type I) filter
M = int(np.ceil(M / 2.0)) * 2
for _attempts in range(20):
# get taps for order M
try:
taps = np.asarray(
grfilter.pm_remez(
order=M, bands=bands, ampl=ampl, error_weight=error_weight
)
)
except RuntimeError:
M = M + 2
continue
# calculate frequency response and get error from ideal
nfft = 16 * len(taps)
h = np.fft.fft(taps, nfft)
w = np.fft.fftfreq(nfft, 0.5)
passband = h[(np.abs(w) >= bands[0]) & (np.abs(w) <= bands[1])]
stopband = h[(np.abs(w) >= bands[2]) & (np.abs(w) <= bands[3])]
act_ripple = -20 * np.log10(np.max(np.abs(ampl[0] - np.abs(passband))))
act_atten = -20 * np.log10(np.max(np.abs(ampl[2] - np.abs(stopband))))
if act_ripple >= pass_ripple and act_atten >= attenuation:
break
else:
M = M + 2
else:
errstr = (
"Could not calculate equiripple filter that meets requirements"
"after {0} attempts (final order {1})."
)
raise RuntimeError(errstr.format(_attempts, M))
return taps
class Thor(object):
"""Record data from synchronized USRPs in DigitalRF format."""
def __init__(self, datadir, **kwargs):
options = dict(
verbose=True,
# mainboard group (num: len of mboards)
mboards=[],
subdevs=["A:A"],
clock_rates=[None],
clock_sources=[""],
time_sources=[""],
# receiver group (apply to all)
samplerate=1e6,
dev_args=["recv_buff_size=100000000", "num_recv_frames=512"],
stream_args=[],
tune_args=[],
time_sync=True,
wait_for_lock=True,
stop_on_dropped=False,
realtime=False,
test_settings=True,
# receiver ch. group (num: matching channels from mboards/subdevs)
centerfreqs=[100e6],
lo_offsets=[0],
lo_sources=[""],
lo_exports=[None],
dc_offsets=[False],
iq_balances=[None],
gains=[0],
bandwidths=[0],
antennas=[""],
# output channel group (num: len of channel_names)
channel_names=["ch0"],
channels=[None],
ch_samplerates=[None],
ch_centerfreqs=[False],
ch_scalings=[1.0],
ch_nsubchannels=[1],
ch_lpf_cutoffs=[0.9],
ch_lpf_transition_widths=[0.2],
ch_lpf_attenuations=[80.0],
ch_lpf_pass_ripples=[None],
ch_out_types=[None],
# digital_rf group (apply to all)
file_cadence_ms=1000,
subdir_cadence_s=3600,
metadata={},
uuid=None,
)
options.update(kwargs)
op = self._parse_options(datadir=datadir, **options)
self.op = op
# test usrp device settings, release device when done
if op.test_settings:
if op.verbose:
print("Initialization: testing device settings.")
self._usrp_setup()
# finalize options (for settings that depend on USRP setup)
self._finalize_options()
@staticmethod
def _parse_options(**kwargs):
"""Put all keyword options in a namespace and normalize them."""
op = argparse.Namespace(**kwargs)
# check that subdevice specifications are unique per-mainboard
for sd in op.subdevs:
sds = sd.split()
if len(set(sds)) != len(sds):
errstr = (
'Invalid subdevice specification: "{0}". '
"Each subdevice specification for a given mainboard must "
"be unique."
)
raise ValueError(errstr.format(sd))
# get USRP cpu_format based on output type and decimation requirements
processing_required = (
any(sr is not None for sr in op.ch_samplerates)
or any(cf is not False for cf in op.ch_centerfreqs)
or any(s != 1 for s in op.ch_scalings)
or any(nsch != 1 for nsch in op.ch_nsubchannels)
)
if (
all(ot is None or ot == "sc16" for ot in op.ch_out_types)
and not processing_required
):
# with only sc16 output and no processing, can use sc16 as cpu
# format and disable conversion
op.cpu_format = "sc16"
op.ch_out_specs = [
dict(
convert=None,
convert_kwargs=None,
dtype=np.dtype([(str("r"), np.int16), (str("i"), np.int16)]),
name="sc16",
)
]
else:
op.cpu_format = "fc32"
# get full specification for output types
supported_out_types = {
"sc8": dict(
convert="float_to_char",
convert_kwargs=dict(vlen=2, scale=float(2 ** 7 - 1)),
dtype=np.dtype([(str("r"), np.int8), (str("i"), np.int8)]),
name="sc8",
),
"sc16": dict(
convert="float_to_short",
convert_kwargs=dict(vlen=2, scale=float(2 ** 15 - 1)),
dtype=np.dtype([(str("r"), np.int16), (str("i"), np.int16)]),
name="sc16",
),
"sc32": dict(
convert="float_to_int",
convert_kwargs=dict(vlen=2, scale=float(2 ** 31 - 1)),
dtype=np.dtype([(str("r"), np.int32), (str("i"), np.int32)]),
name="sc32",
),
"fc32": dict(
convert=None,
convert_kwargs=None,
dtype=np.dtype("complex64"),
name="fc32",
),
}
supported_out_types[None] = supported_out_types["fc32"]
type_dicts = []
for ot in op.ch_out_types:
try:
type_dict = supported_out_types[ot]
except KeyError:
errstr = (
"Output type {0} is not supported. Must be one of {1}."
).format(ot, list(supported_out_types.keys()))
raise ValueError(errstr)
else:
type_dicts.append(type_dict)
op.ch_out_specs = type_dicts
# replace out_types to fill in None values with type name
op.ch_out_types = [os["name"] for os in op.ch_out_specs]
# repeat mainboard arguments as necessary
op.nmboards = len(op.mboards) if len(op.mboards) > 0 else 1
for mb_arg in ("subdevs", "clock_rates", "clock_sources", "time_sources"):
val = getattr(op, mb_arg)
mbval = list(islice(cycle(val), 0, op.nmboards))
setattr(op, mb_arg, mbval)
# get number of receiver channels by total number of subdevices over
# all mainboards
op.mboards_bychan = []
op.subdevs_bychan = []
op.mboardnum_bychan = []
mboards = op.mboards if op.mboards else ["default"]
for mbnum, (mb, sd) in enumerate(zip(mboards, op.subdevs)):
sds = sd.split()
mbs = list(repeat(mb, len(sds)))
mbnums = list(repeat(mbnum, len(sds)))
op.mboards_bychan.extend(mbs)
op.subdevs_bychan.extend(sds)
op.mboardnum_bychan.extend(mbnums)
# repeat receiver channel arguments as necessary
op.nrchs = len(op.subdevs_bychan)
for rch_arg in (
"antennas",
"bandwidths",
"centerfreqs",
"dc_offsets",
"iq_balances",
"lo_offsets",
"lo_sources",
"lo_exports",
"gains",
):
val = getattr(op, rch_arg)
rval = list(islice(cycle(val), 0, op.nrchs))
setattr(op, rch_arg, rval)
# repeat output channel arguments as necessary
op.nochs = len(op.channel_names)
for och_arg in (
"channels",
"ch_centerfreqs",
"ch_lpf_attenuations",
"ch_lpf_cutoffs",
"ch_lpf_pass_ripples",
"ch_lpf_transition_widths",
"ch_nsubchannels",
"ch_out_specs",
"ch_out_types",
"ch_samplerates",
"ch_scalings",
):
val = getattr(op, och_arg)
rval = list(islice(cycle(val), 0, op.nochs))
setattr(op, och_arg, rval)
# fill in unspecified (None) channels values
rchannels = set(range(op.nrchs))
ochannels = set(c for c in op.channels if c is not None)
if not ochannels.issubset(rchannels):
errstr = (
"Invalid channel specification. Output channel uses"
" non-existent receiver channel: {0}."
)
raise ValueError(errstr.format(list(ochannels - rchannels)))
avail = sorted(rchannels - ochannels)
try:
op.channels = [c if c is not None else avail.pop(0) for c in op.channels]
except IndexError:
errstr = (
"No remaining receiver channels left to assign to unspecified"
" (None) output channel. You probably need to explicitly"
" specify the receiver channels to output."
)
raise ValueError(errstr)
unused_rchs = set(range(op.nrchs)) - set(op.channels)
if unused_rchs:
errstr = (
"Receiver channels {0} are unused in the output. Either"
" remove them from the mainboard/subdevice specification or"
" correct the output channel specification."
)
raise ValueError(errstr.format(unused_rchs))
# copy desired centerfreq from receiver to output channel if requested
op.ch_centerfreqs = [
op.centerfreqs[rch] if f in (None, True) else f
for f, rch in zip(op.ch_centerfreqs, op.channels)
]
# create device_addr string to identify the requested device(s)
op.mboard_strs = []
for n, mb in enumerate(op.mboards):
if re.match(r"[^0-9]+=.+", mb):
idtype, mb = mb.split("=")
elif re.match(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", mb):
idtype = "addr"
elif (
re.match(r"usrp[123]", mb)
or re.match(r"b2[01]0", mb)
or re.match(r"x3[01]0", mb)
):
idtype = "type"
elif re.match(r"[0-9A-Fa-f]{1,}", mb):
idtype = "serial"
else:
idtype = "name"
if len(op.mboards) == 1:
# do not use identifier numbering if only using one mainboard
s = "{type}={mb}".format(type=idtype, mb=mb.strip())
else:
s = "{type}{n}={mb}".format(type=idtype, n=n, mb=mb.strip())
op.mboard_strs.append(s)
if op.verbose:
opstr = (
dedent(
"""\
Main boards: {mboard_strs}
Subdevices: {subdevs}
Clock rates: {clock_rates}
Clock sources: {clock_sources}
Time sources: {time_sources}
Sample rate: {samplerate}
Device arguments: {dev_args}
Stream arguments: {stream_args}
Tune arguments: {tune_args}
Antenna: {antennas}
Bandwidth: {bandwidths}
Frequency: {centerfreqs}
LO frequency offset: {lo_offsets}
LO source: {lo_sources}
LO export: {lo_exports}
Gain: {gains}
DC offset: {dc_offsets}
IQ balance: {iq_balances}
Output channels: {channels}
Output channel names: {channel_names}
Output sample rate: {ch_samplerates}
Output frequency: {ch_centerfreqs}
Output scaling: {ch_scalings}
Output subchannels: {ch_nsubchannels}
Output type: {ch_out_types}
Data dir: {datadir}
Metadata: {metadata}
UUID: {uuid}
"""
)
.strip()
.format(**op.__dict__)
)
print(opstr)
return op
def _usrp_setup(self):
"""Create, set up, and return USRP source object."""
op = self.op
# create usrp source block
op.otw_format = "sc16"
u = uhd.usrp_source(
device_addr=",".join(chain(op.mboard_strs, op.dev_args)),
stream_args=uhd.stream_args(
cpu_format=op.cpu_format,
otw_format=op.otw_format,
channels=list(range(op.nrchs)),
args=",".join(op.stream_args),
),
)
# set mainboard options
for mb_num in range(op.nmboards):
u.set_subdev_spec(op.subdevs[mb_num], mb_num)
# set master clock rate
clock_rate = op.clock_rates[mb_num]
if clock_rate is not None:
u.set_clock_rate(clock_rate, mb_num)
# set clock source
clock_source = op.clock_sources[mb_num]
if not clock_source and op.wait_for_lock:
clock_source = "external"
if clock_source:
try:
u.set_clock_source(clock_source, mb_num)
except RuntimeError:
errstr = (
"Setting mainboard {0} clock_source to '{1}' failed."
" Must be one of {2}. If setting is valid, check that"
" the source (REF) is operational."
).format(mb_num, clock_source, u.get_clock_sources(mb_num))
raise ValueError(errstr)
# set time source
time_source = op.time_sources[mb_num]
if not time_source and op.time_sync:
time_source = "external"
if time_source:
try:
u.set_time_source(time_source, mb_num)
except RuntimeError:
errstr = (
"Setting mainboard {0} time_source to '{1}' failed."
" Must be one of {2}. If setting is valid, check that"
" the source (PPS) is operational."
).format(mb_num, time_source, u.get_time_sources(mb_num))
raise ValueError(errstr)
# check for ref lock
mbnums_with_ref = [
mb_num
for mb_num in range(op.nmboards)
if "ref_locked" in u.get_mboard_sensor_names(mb_num)
]
if op.wait_for_lock and mbnums_with_ref:
if op.verbose:
sys.stdout.write("Waiting for reference lock...")
sys.stdout.flush()
timeout = 0
if op.wait_for_lock is True:
timeout_thresh = 30
else:
timeout_thresh = op.wait_for_lock
while not all(
u.get_mboard_sensor("ref_locked", mb_num).to_bool()
for mb_num in mbnums_with_ref
):
if op.verbose:
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(1)
timeout += 1
if timeout > timeout_thresh:
if op.verbose:
sys.stdout.write("failed\n")
sys.stdout.flush()
unlocked_mbs = [
mb_num
for mb_num in mbnums_with_ref
if u.get_mboard_sensor("ref_locked", mb_num).to_bool()
]
errstr = (
"Failed to lock to 10 MHz reference on mainboards {0}."
" To skip waiting for lock, set `wait_for_lock` to"
" False (pass --nolock on the command line)."
).format(unlocked_mbs)
raise RuntimeError(errstr)
if op.verbose:
sys.stdout.write("locked\n")
sys.stdout.flush()
# set global options
# sample rate (set after clock rate so it can be calculated correctly)
u.set_samp_rate(float(op.samplerate))
# read back actual mainboard options
# (clock rate can be affected by setting sample rate)
for mb_num in range(op.nmboards):
op.clock_rates[mb_num] = u.get_clock_rate(mb_num)
op.clock_sources[mb_num] = u.get_clock_source(mb_num)
op.time_sources[mb_num] = u.get_time_source(mb_num)
# read back actual sample rate value
samplerate = u.get_samp_rate()
# calculate longdouble precision/rational sample rate
# (integer division of clock rate)
cr = op.clock_rates[0]
srdec = int(round(cr / samplerate))
samplerate_ld = np.longdouble(cr) / srdec
op.samplerate = samplerate_ld
op.samplerate_frac = Fraction(cr).limit_denominator() / srdec
# set per-channel options
# set command time so settings are synced
COMMAND_DELAY = 0.2
gpstime = datetime.utcfromtimestamp(usrp.get_mboard_sensor("gps_time"))
gpstime_secs = (pytz.utc.localize(gpstime) - drf.util.epoch).total_seconds()
cmd_time_secs = gpstime_secs + COMMAND_DELAY
usrp.set_command_time(
uhd.time_spec(float(cmd_time_secs)),
uhd.ALL_MBOARDS,
)
for ch_num in range(op.nrchs):
# local oscillator sharing settings
lo_source = op.lo_sources[ch_num]
if lo_source:
try:
u.set_lo_source(lo_source, uhd.ALL_LOS, ch_num)
except RuntimeError:
errstr = (
"Unknown LO source option: '{0}'. Must be one of {1},"
" or it may not be possible to set the LO source on"
" this daughterboard."
).format(lo_source, u.get_lo_sources(uhd.ALL_LOS, ch_num))
raise ValueError(errstr)
lo_export = op.lo_exports[ch_num]
if lo_export is not None:
if not lo_source:
errstr = (
"Channel {0}: must set an LO source in order to set"
" LO export."
).format(ch_num)
raise ValueError(errstr)
u.set_lo_export_enabled(lo_export, uhd.ALL_LOS, ch_num)
# center frequency and tuning offset
tune_res = u.set_center_freq(
uhd.tune_request(
op.centerfreqs[ch_num],
op.lo_offsets[ch_num],
args=uhd.device_addr(",".join(op.tune_args)),
),
ch_num,
)
# store actual values from tune result
op.centerfreqs[ch_num] = tune_res.actual_rf_freq - tune_res.actual_dsp_freq
op.lo_offsets[ch_num] = tune_res.actual_dsp_freq
# dc offset
dc_offset = op.dc_offsets[ch_num]
if dc_offset is True:
u.set_auto_dc_offset(True, ch_num)
elif dc_offset is False:
u.set_auto_dc_offset(False, ch_num)
elif dc_offset is not None:
u.set_auto_dc_offset(False, ch_num)
u.set_dc_offset(dc_offset, ch_num)
# iq balance
iq_balance = op.iq_balances[ch_num]
if iq_balance is True:
u.set_auto_iq_balance(True, ch_num)
elif iq_balance is False:
u.set_auto_iq_balance(False, ch_num)
elif iq_balance is not None:
u.set_auto_iq_balance(False, ch_num)
u.set_iq_balance(iq_balance, ch_num)
# gain
u.set_gain(op.gains[ch_num], ch_num)
# bandwidth
bw = op.bandwidths[ch_num]
if bw:
u.set_bandwidth(bw, ch_num)
# antenna
ant = op.antennas[ch_num]
if ant:
try:
u.set_antenna(ant, ch_num)
except RuntimeError:
errstr = (
"Unknown RX antenna option: '{0}'. Must be one of {1}."
).format(ant, u.get_antennas(ch_num))
raise ValueError(errstr)
# commands are done, clear time
u.clear_command_time(uhd.ALL_MBOARDS)
time.sleep(COMMAND_DELAY)
# read back actual channel settings
for ch_num in range(op.nrchs):
if op.lo_sources[ch_num]:
op.lo_sources[ch_num] = u.get_lo_source(uhd.ALL_LOS, ch_num)
if op.lo_exports[ch_num] is not None:
op.lo_exports[ch_num] = u.get_lo_export_enabled(uhd.ALL_LOS, ch_num)
op.gains[ch_num] = u.get_gain(ch_num)
op.bandwidths[ch_num] = u.get_bandwidth(chan=ch_num)
op.antennas[ch_num] = u.get_antenna(chan=ch_num)
op.usrpinfo.append(dict(u.get_usrp_info(chan=ch_num)))
if op.verbose:
print("Using the following devices:")
chinfostrs = [
"Motherboard: {mb_id} ({mb_addr}) | Daughterboard: {db_name}",
"Subdev: {sub} | Antenna: {ant} | Gain: {gain} | Rate: {sr}",
"Frequency: {freq:.3f} ({lo_off:+.3f}) | Bandwidth: {bw}",
]
if any(op.lo_sources) or any(op.lo_exports):
chinfostrs.append("LO source: {lo_source} | LO export: {lo_export}")
chinfo = "\n".join([" " + l for l in chinfostrs])
for ch_num in range(op.nrchs):
header = "---- receiver channel {0} ".format(ch_num)
header += "-" * (78 - len(header))
print(header)
usrpinfo = op.usrpinfo[ch_num]
info = {}
info["mb_id"] = usrpinfo["mboard_id"]
mba = op.mboards_bychan[ch_num]
if mba == "default":
mba = usrpinfo["mboard_serial"]
info["mb_addr"] = mba
info["db_name"] = usrpinfo["rx_subdev_name"]
info["sub"] = op.subdevs_bychan[ch_num]
info["ant"] = op.antennas[ch_num]
info["bw"] = op.bandwidths[ch_num]
info["freq"] = op.centerfreqs[ch_num]
info["gain"] = op.gains[ch_num]
info["lo_off"] = op.lo_offsets[ch_num]
info["lo_source"] = op.lo_sources[ch_num]
info["lo_export"] = op.lo_exports[ch_num]
info["sr"] = op.samplerate
print(chinfo.format(**info))
print("-" * 78)
return u
def _finalize_options(self):
op = self.op
op.ch_samplerates_frac = []
op.resampling_ratios = []
op.resampling_filter_taps = []
op.resampling_filter_delays = []
op.channelizer_filter_taps = []
op.channelizer_filter_delays = []
for ko, (osr, nsc) in enumerate(zip(op.ch_samplerates, op.ch_nsubchannels)):
# get output sample rate fraction
# (op.samplerate_frac final value is set in _usrp_setup
# so can't get output sample rate until after that is done)
if osr is None:
ch_samplerate_frac = op.samplerate_frac
else:
ch_samplerate_frac = Fraction(osr).limit_denominator()
op.ch_samplerates_frac.append(ch_samplerate_frac)
# get resampling ratio
ratio = ch_samplerate_frac / op.samplerate_frac
op.resampling_ratios.append(ratio)
# get resampling low-pass filter taps
if ratio == 1:
op.resampling_filter_taps.append(np.zeros(0))
op.resampling_filter_delays.append(0)
else:
# filter taps need to be designed for the highest rate
# (i.e. after interpolation but before decimation)
taps = equiripple_lpf(
cutoff=float(op.ch_lpf_cutoffs[ko]) / ratio.denominator,
transition_width=(
float(op.ch_lpf_transition_widths[ko]) / ratio.denominator
),
attenuation=op.ch_lpf_attenuations[ko],
pass_ripple=op.ch_lpf_pass_ripples[ko],
)
# for unit gain in passband, need to multiply taps by
# interpolation rate
taps = ratio.numerator * taps
op.resampling_filter_taps.append(taps)
# calculate filter delay in same way as pfb_arb_resampler
# (overall taps are applied at interpolated rate, but delay is
# still in terms of input rate, i.e. the taps per filter
# after being split into the polyphase filter bank)
taps_per_filter = int(np.ceil(float(len(taps)) / ratio.numerator))
op.resampling_filter_delays.append(Fraction(taps_per_filter - 1, 2))
# get channelizer low-pass filter taps
if nsc > 1:
taps = equiripple_lpf(
cutoff=(op.ch_lpf_cutoffs[ko] / nsc),
transition_width=(op.ch_lpf_transition_widths[ko] / nsc),
attenuation=op.ch_lpf_attenuations[ko],
pass_ripple=op.ch_lpf_pass_ripples[ko],
)
op.channelizer_filter_taps.append(taps)
op.channelizer_filter_delays.append(Fraction(len(taps) - 1, 2))
else:
op.channelizer_filter_taps.append(np.zeros(0))
op.channelizer_filter_delays.append(0)
def run(self, starttime=None, endtime=None, duration=None, period=10):
op = self.op
# window in seconds that we allow for setup time so that we don't
# issue a start command that's in the past when the flowgraph starts
SETUP_TIME = 10
# print current time and NTP status
if op.verbose and sys.platform.startswith("linux"):
try:
call(("timedatectl", "status"))
except OSError:
# no timedatectl command, ignore
pass
# parse time arguments
st = drf.util.parse_identifier_to_time(starttime)
if st is not None:
# find next suitable start time by cycle repeat period
now = datetime.utcnow()
now = now.replace(tzinfo=pytz.utc)
soon = now + timedelta(seconds=SETUP_TIME)
diff = max(soon - st, timedelta(0)).total_seconds()
periods_until_next = (diff - 1) // period + 1
st = st + timedelta(seconds=periods_until_next * period)
if op.verbose:
ststr = st.strftime("%a %b %d %H:%M:%S %Y")
stts = (st - drf.util.epoch).total_seconds()
print("Start time: {0} ({1})".format(ststr, stts))
et = drf.util.parse_identifier_to_time(endtime, ref_datetime=st)
if et is not None:
if op.verbose:
etstr = et.strftime("%a %b %d %H:%M:%S %Y")
etts = (et - drf.util.epoch).total_seconds()
print("End time: {0} ({1})".format(etstr, etts))
if (
et
< (pytz.utc.localize(datetime.utcnow()) + timedelta(seconds=SETUP_TIME))
) or (st is not None and et <= st):
raise ValueError("End time is before launch time!")
if op.realtime:
r = gr.enable_realtime_scheduling()
if op.verbose:
if r == gr.RT_OK:
print("Realtime scheduling enabled")
else:
print("Note: failed to enable realtime scheduling")
# create data directory so ringbuffer code can be started while waiting
# to launch
if not os.path.isdir(op.datadir):
os.makedirs(op.datadir)
# Copy freq_list into the data directory
if op.freq_list_fname:
for ch in op.channel_names:
chdir = os.path.join(op.datadir, ch)
try:
os.makedirs(chdir)
except:
None
try:
shutil.copy2(
op.freq_list_fname,
os.path.join(chdir, 'freq_list.txt')
)
except:
None
# wait for the start time if it is not past
while (st is not None) and (
(st - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=SETUP_TIME)
):
ttl = int((st - pytz.utc.localize(datetime.utcnow())).total_seconds())
if (ttl % 10) == 0:
print("Standby {0} s remaining...".format(ttl))
sys.stdout.flush()
time.sleep(1)
# get UHD USRP source
u = self._usrp_setup()
# finalize options (for settings that depend on USRP setup)
self._finalize_options()
if any(
info["mboard_id"] in ("B200", "B210", "B200mini", "B205mini")
for info in op.usrpinfo
):
# force creation of the RX streamer ahead of time with a start/stop
# (after setting time/clock sources, before setting the
# device time)
# this fixes timing with the B210
u.start()
# need to wait >0.1 s (constant in usrp_source_impl.c) for start
# to actually take effect, so sleep, (0.5 s seems more reliable)
time.sleep(0.5)
u.stop()
time.sleep(0.2)
# set launch time
# (at least 2 seconds out so USRP start time can be set properly and
# there is time to set up flowgraph)
if st is not None:
lt = st
else:
now = pytz.utc.localize(datetime.utcnow())
# launch on integer second by default for convenience (ceil + 2)
lt = now.replace(microsecond=0) + timedelta(seconds=3)
ltts = (lt - drf.util.epoch).total_seconds()
# adjust launch time forward so it falls on an exact sample since epoch
lt_rsamples = int(np.ceil(ltts * op.samplerate))
ltts = lt_rsamples / op.samplerate
lt = drf.util.sample_to_datetime(lt_rsamples, op.samplerate)
if op.verbose:
ltstr = lt.strftime("%a %b %d %H:%M:%S.%f %Y")
msg = "Launch time: {0} ({1})\nSample index: {2}"
print(msg.format(ltstr, repr(ltts), lt_rsamples))
# command launch time
ct_td = lt - drf.util.epoch
ct_secs = ct_td.total_seconds() // 1.0
ct_frac = ct_td.microseconds / 1000000.0
u.set_start_time(uhd.time_spec(ct_secs) + uhd.time_spec(ct_frac))
# populate flowgraph one channel at a time
fg = gr.top_block()
for ko in range(op.nochs):
# receiver channel number corresponding to this output channel
kr = op.channels[ko]
# mainboard number corresponding to this receiver's channel
mbnum = op.mboardnum_bychan[kr]
# output settings that get modified depending on processing
ch_samplerate_frac = op.ch_samplerates_frac[ko]
ch_centerfreq = op.ch_centerfreqs[ko]
start_sample_adjust = 0
# make resampling filter blocks if necessary
rs_ratio = op.resampling_ratios[ko]
scaling = op.ch_scalings[ko]
if rs_ratio != 1:
rs_taps = op.resampling_filter_taps[ko]
# integrate scaling into filter taps
rs_taps *= scaling
conv_scaling = 1.0
# frequency shift filter taps to band-pass if necessary
if ch_centerfreq is not False:
f_shift = ch_centerfreq - op.centerfreqs[kr]
phase_inc = 2 * np.pi * f_shift / op.samplerate
rotator = np.exp(phase_inc * 1j * np.arange(len(rs_taps)))
rs_taps = (rs_taps * rotator).astype("complex64")
# create band-pass filter (complex taps)
# don't use rational_resampler because its delay is wrong
resampler = grfilter.pfb_arb_resampler_ccc(
rate=float(rs_ratio),
taps=rs_taps.tolist(),
# since resampling is rational, we know we only need a
# number of filters equal to the interpolation factor
filter_size=rs_ratio.numerator,
)
else:
# create low-pass filter (float taps)
# don't use rational_resampler because its delay is wrong
resampler = grfilter.pfb_arb_resampler_ccf(
rate=float(rs_ratio),
taps=rs_taps.tolist(),
# since resampling is rational, we know we only need a
# number of filters equal to the interpolation factor
filter_size=rs_ratio.numerator,
)
# declare sample delay for the filter block so that tags are
# propagated to the correct sample
resampler.declare_sample_delay(int(op.resampling_filter_delays[ko]))
# adjust start sample to account for filter delay so first
# sample going to output is shifted to an earlier time
# (adjustment is in terms of filter output samples, so need to
# take the input filter delay and account for the output rate)
start_sample_adjust = int(
(start_sample_adjust - op.resampling_filter_delays[ko]) * rs_ratio
)
else:
conv_scaling = scaling
resampler = None
# make frequency shift block if necessary
if ch_centerfreq is not False:
f_shift = ch_centerfreq - op.centerfreqs[kr]
phase_inc = -2 * np.pi * f_shift / ch_samplerate_frac
rotator = blocks.rotator_cc(phase_inc)
else:
ch_centerfreq = op.centerfreqs[kr]
rotator = None
# make channelizer if necessary
nsc = op.ch_nsubchannels[ko]
if nsc > 1:
sc_taps = op.channelizer_filter_taps[ko]
# build a hierarchical block for the channelizer so output
# is a vector of channels as expected by digital_rf
channelizer = gr.hier_block2(
"lpf",
gr.io_signature(1, 1, gr.sizeof_gr_complex),
gr.io_signature(1, 1, nsc * gr.sizeof_gr_complex),
)
s2ss = blocks.stream_to_streams(gr.sizeof_gr_complex, nsc)
filt = grfilter.pfb_channelizer_ccf(
numchans=nsc, taps=sc_taps, oversample_rate=1.0
)
s2v = blocks.streams_to_vector(gr.sizeof_gr_complex, nsc)
channelizer.connect(channelizer, s2ss)
for ksc in range(nsc):
channelizer.connect((s2ss, ksc), (filt, ksc), (s2v, ksc))
channelizer.connect(s2v, channelizer)
# declare sample delay for the filter block so that tags are
# propagated to the correct sample
# (for channelized, delay is applied for each filter in the
# polyphase bank, so this needs to be the output sample delay)
filt.declare_sample_delay(int(op.channelizer_filter_delays[ko] / nsc))
# adjust start sample to account for filter delay so first
# sample going to output is shifted to an earlier time
# (adjustment is in terms of filter output samples, so need to
# take the input filter delay and account for the output rate)
start_sample_adjust = int(
(start_sample_adjust - op.channelizer_filter_delays[ko]) / nsc
)
# modify output settings accordingly
ch_centerfreq = ch_centerfreq + np.fft.fftfreq(
nsc, 1 / float(ch_samplerate_frac)
)
ch_samplerate_frac = ch_samplerate_frac / nsc
else:
channelizer = None
# make conversion block if necessary
ot_dict = op.ch_out_specs[ko]
converter = ot_dict["convert"]
if converter is not None: