1#!/usr/local/bin/python3.8
2#
3# Copyright 2015-2016 Ettus Research LLC
4# Copyright 2018 Ettus Research, a National Instruments Company
5#
6# SPDX-License-Identifier: GPL-3.0-or-later
7#
8""" Run uhd_find_devices and parse the output. """
9
10import re
11import subprocess
12
13def get_usrp_list(device_filter=None, env=None):
14    """ Returns a list of dicts that contain USRP info """
15    try:
16        cmd = ['uhd_find_devices']
17        if device_filter is not None:
18            cmd += ['--args', device_filter]
19        output = subprocess.check_output(cmd, env=env, universal_newlines=True)
20    except subprocess.CalledProcessError:
21        return []
22    split_re = "\n*-+\n-- .*\n-+\n"
23    uhd_strings = re.split(split_re, output)
24    result = []
25    for uhd_string in uhd_strings:
26        if not re.match("Device Address", uhd_string):
27            continue
28        this_result = {k: v for k, v in re.findall("    ([a-z]+): (.*)", uhd_string)}
29        if this_result.get('reachable') == "No":
30            continue
31        args_string = ""
32        try:
33            args_string = "type={},serial={}".format(this_result['type'], this_result['serial'])
34        except KeyError:
35            continue
36        this_result['args'] = args_string
37        result.append(this_result)
38    return result
39
40def get_num_chans(device_args=None, env=None):
41    """ Returns a dictionary that contains the number of TX and RX channels """
42    # First, get the tree
43    try:
44        cmd = ['uhd_usrp_probe', '--tree']
45        if device_args is not None:
46            cmd += ['--args', device_args]
47        output = subprocess.check_output(cmd, env=env, universal_newlines=True)
48    except subprocess.CalledProcessError:
49        return {}
50
51    # Now look through the tree for frontend names
52    rx_channels = 0
53    tx_channels = 0
54    for line in output.splitlines():
55        if re.match('.*/[rt]x_frontends/[0-9AB]+/name$',line):
56            # Get the frontend name
57            try:
58                cmd = ['uhd_usrp_probe']
59                if device_args is not None:
60                    cmd += ['--args', device_args]
61                cmd += ['--string', line]
62                output = subprocess.check_output(cmd, env=env, universal_newlines=True)
63                # Ignore unknown frontends
64                if (output.find("Unknown") == -1):
65                    # Increment respective count
66                    if re.match('.*/rx_frontends/[0-9AB]+/name$', line):
67                        rx_channels += 1
68                    else:
69                        tx_channels += 1
70            except subprocess.CalledProcessError:
71                pass
72
73    # Finally, return the counts
74    return {'tx': tx_channels, 'rx': rx_channels}
75
76if __name__ == "__main__":
77    print(get_usrp_list())
78    print(get_usrp_list('type=x300'))
79