Skip to content

Devices

pysdrlib.devices

Drivers, and the devices attached to this machine

pysdrlib.devices.ls()            # driver names
pysdrlib.find()                  # [DeviceInfo]: the radios plugged in, for every driver whose library is there
pysdrlib.find(addresses=["192.168.10.2"])   # ... and ones on the network, for drivers that can reach those
sdr = pysdrlib.connect("ipc:///tmp/pysdrlib", "<driver>")   # a radio hosted by a `pysdrlib server` (this machine or another)
sdr = pysdrlib.open(pysdrlib.find()[0])          # or pysdrlib.open("<driver>", serial="...")

Drivers from outside pysdrlib

A driver needs no change to this package. Register a Device subclass in a script,

@pysdrlib.register("tcpiq")
class TcpIq(pysdrlib.Device): ...

sdr = pysdrlib.open("tcpiq", host="10.0.0.5", port=1234)      # `open` arguments go to the class's `_open`

or ship it in a package that declares an entry point, which makes it known to every program once installed:

[project.entry-points."pysdrlib.drivers"]
tcpiq = "my_package.tcpiq:TcpIq"

Entry points are only read (not imported) until a driver is used. A driver that fails to import is reported by get, and skipped by find. A name is lower case letters, digits and underscores, and can't replace a driver pysdrlib ships (unless register(..., replace=True)). PYSDRLIB_NO_PLUGINS=1 ignores entry points.

Classes:

Name Description
DeviceInfo

One attached radio. open_args: what Device.open needs to get this unit (its serial, or index)

Functions:

Name Description
register

Make a driver known by name, to ls, get, find and open. Use it as a decorator on a Device subclass, or

unregister

Forget a driver made known by register or an entry point (a shipped driver it replaced is back). False if

ls

Driver names: every package here whose __init__.py says Device = ... (adding one needs no list edited), and

get

The device package name (a driver, or "file" / "remote"): something with Device and find. Raises

device

A new, unopened device of driver name (see ls); the arguments go to its constructor.

find

The radios attached to this machine, as DeviceInfo. Only drivers whose vendor library is installed or was

connect

An opened device hosted by a pysdrlib server at address (see pysdrlib.remote): on this machine, where it is shared

open

An opened device: from a DeviceInfo (see find), a Radio (see discover), a driver name (serial picks the

DeviceInfo dataclass

DeviceInfo(driver: str, label: str, serial: Optional[str] = None, index: Optional[int] = None, open_args: dict = dict(), extra: dict = dict())

One attached radio. open_args: what Device.open needs to get this unit (its serial, or index)

Methods:

Name Description
open

A Device for this unit, opened

open

open(**open_args) -> Device

A Device for this unit, opened

Source code in src/pysdrlib/devices.py
def open(self, **open_args) -> Device:
    """A Device for this unit, opened"""
    sdr = device(self.driver)
    sdr.open(**{**self.open_args, **open_args})
    return sdr

register

register(name: str, target=None, *, replace=False)

Make a driver known by name, to ls, get, find and open. Use it as a decorator on a Device subclass, or give target: that class, or a "module:Class" string (imported only when the driver is used)

@pysdrlib.register("tcpiq")
class TcpIq(pysdrlib.Device): ...

pysdrlib.register("tcpiq", "my_package.tcpiq:TcpIq")

Raises ValueError for a name already taken (a shipped driver, or another registered) unless replace; registering the same target again is not an error. What pysdrlib.find lists for it is the class's find() classmethod, which lists nothing unless you write it: a source that can't be enumerated (a TCP stream) is opened by name, with pysdrlib.open(name, ...)

Source code in src/pysdrlib/devices.py
def register(name: str, target=None, *, replace=False):
    """Make a driver known by `name`, to `ls`, `get`, `find` and `open`. Use it as a decorator on a `Device` subclass, or
    give `target`: that class, or a "module:Class" string (imported only when the driver is used)

        @pysdrlib.register("tcpiq")
        class TcpIq(pysdrlib.Device): ...

        pysdrlib.register("tcpiq", "my_package.tcpiq:TcpIq")

    Raises ValueError for a name already taken (a shipped driver, or another registered) unless `replace`; registering the
    same target again is not an error. What `pysdrlib.find` lists for it is the class's `find()` classmethod, which lists
    nothing unless you write it: a source that can't be enumerated (a TCP stream) is opened by name, with
    `pysdrlib.open(name, ...)`"""
    if not isinstance(name, str) or not _NAME.fullmatch(name):
        raise ValueError(f"{name!r}: a driver name is lower case letters, digits and underscores, starting with a letter")
    def add(target):
        if isinstance(target, type):
            if not issubclass(target, Device):
                raise TypeError(f"{target!r} is not a pysdrlib Device subclass")
        elif not isinstance(target, str) or not target:
            raise TypeError("a driver is a Device subclass, or a 'module:Class' string")
        taken = _registered.get(name)
        if (taken is not None or name in _shipped()) and not replace:
            if taken is not None and taken.target == target:
                return target
            raise ValueError(f"driver {name!r} is already taken by {taken.source if taken else 'pysdrlib'}; "
                             "pass replace=True to take it over")
        _registered[name] = _Registered(name, target, "register()")
        return target
    return add if target is None else add(target)

unregister

unregister(name: str) -> bool

Forget a driver made known by register or an entry point (a shipped driver it replaced is back). False if there was none

Source code in src/pysdrlib/devices.py
def unregister(name: str) -> bool:
    """Forget a driver made known by `register` or an entry point (a shipped driver it replaced is back). False if
    there was none"""
    return _registered.pop(name, None) is not None

ls

ls()

Driver names: every package here whose __init__.py says Device = ... (adding one needs no list edited), and the ones registered or installed with a "pysdrlib.drivers" entry point

Source code in src/pysdrlib/devices.py
def ls():
    """Driver names: every package here whose `__init__.py` says `Device = ...` (adding one needs no list edited), and
    the ones `register`ed or installed with a "pysdrlib.drivers" entry point"""
    _read_entry_points()
    shipped = [name for name in _packages() if name not in NOT_DRIVERS]
    return sorted(set(shipped) | set(_ALIASES) | set(_registered))

get

get(name: str)

The device package name (a driver, or "file" / "remote"): something with Device and find. Raises err.NoDevice, naming the drivers there are, for one that doesn't exist (or a registered one that can't be imported)

Source code in src/pysdrlib/devices.py
def get(name: str):
    """The device package `name` (a driver, or "file" / "remote"): something with `Device` and `find`. Raises
    err.NoDevice, naming the drivers there are, for one that doesn't exist (or a registered one that can't be imported)"""
    _read_entry_points()
    if name in _registered:
        return _resolve(_registered[name])
    if name in _alias_entries:
        return _resolve(_alias_entries[name])
    if name not in _packages():
        raise err.NoDevice(f"no driver {name!r} (drivers: {', '.join(ls())})")
    return importlib.import_module(f".{name}", "pysdrlib")

device

device(name: str, *args, **kwargs) -> Device

A new, unopened device of driver name (see ls); the arguments go to its constructor. Call open() on it before use. pysdrlib.open is the shortcut that also finds and opens an attached radio

Source code in src/pysdrlib/devices.py
def device(name: str, *args, **kwargs) -> Device:
    """A new, unopened device of driver `name` (see `ls`); the arguments go to its constructor.
    Call `open()` on it before use. `pysdrlib.open` is the shortcut that also finds and opens an attached radio"""
    return get(name).Device(*args, **kwargs)

find

find(driver: Optional[str] = None, build=False, virtual=False, addresses=None, timeout=None) -> list

The radios attached to this machine, as DeviceInfo. Only drivers whose vendor library is installed or was built before are asked (pysdrlib build <driver> builds one; build=True builds the ones that are missing now). virtual: also list simulated devices. addresses: network addresses (a host or "host:port", or a list of them) to look at as well. Only drivers for radios that can be on a network use them (their find takes addresses); the rest list what is attached here, as always. Without addresses nothing is probed over a network. timeout: seconds a driver may wait for a network answer (drivers whose find takes timeout)

Source code in src/pysdrlib/devices.py
def find(driver: Optional[str] = None, build=False, virtual=False, addresses=None, timeout=None) -> list:
    """The radios attached to this machine, as DeviceInfo. Only drivers whose vendor library is installed or was
    built before are asked (`pysdrlib build <driver>` builds one; `build=True` builds the ones that are missing now).
    virtual: also list simulated devices.
    addresses: network addresses (a host or "host:port", or a list of them) to look at as well. Only drivers for radios
    that can be on a network use them (their `find` takes `addresses`); the rest list what is attached here, as always.
    Without addresses nothing is probed over a network.
    timeout: seconds a driver may wait for a network answer (drivers whose `find` takes `timeout`)"""
    if isinstance(addresses, str):
        addresses = [addresses]
    addresses = list(addresses) if addresses else None
    found = []
    for name in ([driver] if driver else [n for n in ls() if n not in _ALIASES]):   # (a class of a driver is listed by it)
        if not _library_ready(name, build):
            _log.debug("find: skipping %s (its library isn't installed or built)", name)
            continue
        try:
            finder = getattr(get(name), "find", None)
            if finder is None:
                continue
            for info in finder(**_finder_args(finder, addresses, timeout)):
                if (virtual or not info.extra.get("virtual")) and info not in found:   # a driver may list another's units too
                    found.append(info)
        except Exception as exc:   # a driver that can't be loaded or asked has nothing attached we can use
            _log.debug("find: %s: %s", name, exc)
    return found

connect

connect(address: Optional[str] = None, device: Optional[str] = None, *, claim=False, reuse=False, **kwargs) -> Device

An opened device hosted by a pysdrlib server at address (see pysdrlib.remote): on this machine, where it is shared through shared memory, or on another. It has the API of any other device.

sdr = pysdrlib.connect("tcp://radiohost:5555", "<driver>")      # a new one there: you control it
sdr = pysdrlib.connect("tcp://radiohost:5555", "<driver>-0")    # one it already hosts: you may receive from it
sdr = pysdrlib.connect("tcp://radiohost:5555", "<driver>-0", claim=True)   # ... and control it if it is free
a device type the server can open, or the id of a device it hosts (pysdrlib client ADDRESS list shows both).

Left out, the server picks any radio that fits serial, label, need and want.

claim: for a hosted device, take control of it (err.Busy if someone has it). reuse: for a type, take over a hosted device of that type nobody controls (one a client left open) before opening a new one. kwargs: the rest go to pysdrlib.remote.client.RemoteDevice (transport, timeout, wire, init_kwargs...), among them the ones that say who you are and what you need, so the server can pick a radio:

sdr = pysdrlib.connect(addr, program="pyspecan", need={"freq": 433e6, "rate": 2e6}, want={"rate": 10e6})
sdr = pysdrlib.connect(addr, "<driver>", serial="SERIAL", program="pyspecan")
sdr.granted                         # what the radio can do nearest to what you wanted

program names your program (the server shows it in list), serial/label choose a unit, need/want are dicts of freq, rate, bandwidth, channels, tx: no radio that cannot meet need is used (err.NoDevice says why each was left out), and of the rest the one nearest want is. Raises err.NoDevice, naming what the server has, for a device it neither hosts nor can open.

address None: find the servers announcing themselves on the local network (pysdrlib.remote.discover, which needs zeroconf) and use the one with the best radio for the request, by the same rules a server picks among its own:

sdr = pysdrlib.connect(need={"freq": 433e6}, want={"rate": 10e6}, program="pyspecan")   # wherever it fits best
sdr = pysdrlib.connect(device="<driver>")      # a server that has one attached
sdr.address                                     # the server it is on

A radio attached comes before one a client left open, and a server on this machine before another; a server that fails to open it is passed over for the next. discover_timeout (default 2) is how many seconds to listen for servers.

Source code in src/pysdrlib/devices.py
def connect(address: Optional[str] = None, device: Optional[str] = None, *, claim=False, reuse=False, **kwargs) -> Device:
    """An opened device hosted by a `pysdrlib server` at `address` (see `pysdrlib.remote`): on this machine, where it is shared
    through shared memory, or on another. It has the API of any other device.

        sdr = pysdrlib.connect("tcp://radiohost:5555", "<driver>")      # a new one there: you control it
        sdr = pysdrlib.connect("tcp://radiohost:5555", "<driver>-0")    # one it already hosts: you may receive from it
        sdr = pysdrlib.connect("tcp://radiohost:5555", "<driver>-0", claim=True)   # ... and control it if it is free

    device: a device type the server can open, or the id of a device it hosts (`pysdrlib client ADDRESS list` shows both).
        Left out, the server picks any radio that fits `serial`, `label`, `need` and `want`.
    claim: for a hosted device, take control of it (`err.Busy` if someone has it).
    reuse: for a type, take over a hosted device of that type nobody controls (one a client left open) before opening a new one.
    kwargs: the rest go to `pysdrlib.remote.client.RemoteDevice` (`transport`, `timeout`, `wire`, `init_kwargs`...), among
    them the ones that say who you are and what you need, so the server can pick a radio:

        sdr = pysdrlib.connect(addr, program="pyspecan", need={"freq": 433e6, "rate": 2e6}, want={"rate": 10e6})
        sdr = pysdrlib.connect(addr, "<driver>", serial="SERIAL", program="pyspecan")
        sdr.granted                         # what the radio can do nearest to what you wanted

    `program` names your program (the server shows it in `list`), `serial`/`label` choose a unit, `need`/`want` are dicts of
    `freq`, `rate`, `bandwidth`, `channels`, `tx`: no radio that cannot meet `need` is used (`err.NoDevice` says why each
    was left out), and of the rest the one nearest `want` is.
    Raises `err.NoDevice`, naming what the server has, for a device it neither hosts nor can open.

    address None: find the servers announcing themselves on the local network (`pysdrlib.remote.discover`, which needs
    zeroconf) and use the one with the best radio for the request, by the same rules a server picks among its own:

        sdr = pysdrlib.connect(need={"freq": 433e6}, want={"rate": 10e6}, program="pyspecan")   # wherever it fits best
        sdr = pysdrlib.connect(device="<driver>")      # a server that has one attached
        sdr.address                                     # the server it is on

    A radio attached comes before one a client left open, and a server on this machine before another; a server that
    fails to open it is passed over for the next. `discover_timeout` (default 2) is how many seconds to listen for servers.
    """
    try:
        from .remote import Client, RemoteDevice
    except ImportError as exc:
        raise ImportError("connecting to a server needs pyzmq: pip install pysdrlib[remote]") from exc
    if address is None:
        return _connect_anywhere(device, claim, reuse, **kwargs)
    with Client(address, kwargs.get("timeout", 5.0)) as client:
        hosted, types = client.list(), client.types()
    ids = {d["id"]: d for d in hosted}
    choosing = any(kwargs.get(k) is not None for k in ("serial", "label", "need", "want", "pick"))
    if device is None or (choosing and device not in ids):
        if device is not None and device not in types:
            raise err.NoDevice(f"{address} cannot open a device of type {device!r} (types: {', '.join(types) or 'none'})",
                               reason="no_type")
        dev = RemoteDevice(address, device, **kwargs)
        dev.open()
        return dev
    if device in ids:
        dev = RemoteDevice(address, id=device, **kwargs)
        dev.open()
        if claim:
            try:
                dev.claim()
            except Exception:
                dev.close()
                raise
        return dev
    if device not in types:
        raise err.NoDevice(f"{address} hosts no device {device!r} and cannot open one of that type "
                           f"(hosted: {', '.join(ids) or 'none'}; types: {', '.join(types) or 'none'})", reason="no_type")
    free = [d["id"] for d in hosted if d["type"] == device and not d["controlled"]]
    if reuse and free:
        return connect(address, free[0], claim=True, **kwargs)
    dev = RemoteDevice(address, device, **kwargs)
    dev.open()
    return dev

open

open(what, serial=None, **open_args) -> Device

An opened device: from a DeviceInfo (see find), a Radio (see discover), a driver name (serial picks the unit), or a target string (see pysdrlib.targets):

pysdrlib.open("<driver>@<serial>")              # attached here, by (the end of) its serial
pysdrlib.open("radiohost/<driver>-0")           # hosted by a server: attach to it
pysdrlib.open("radiohost/<driver>@<serial>", program="pyspecan")   # attached to a server: open it there

For a device on a server, the keywords go to connect (claim, reuse, program, need, timeout...); here, to Device.open

Source code in src/pysdrlib/devices.py
def open(what, serial=None, **open_args) -> Device:
    """An opened device: from a DeviceInfo (see `find`), a `Radio` (see `discover`), a driver name (`serial` picks the
    unit), or a target string (see `pysdrlib.targets`):

        pysdrlib.open("<driver>@<serial>")              # attached here, by (the end of) its serial
        pysdrlib.open("radiohost/<driver>-0")           # hosted by a server: attach to it
        pysdrlib.open("radiohost/<driver>@<serial>", program="pyspecan")   # attached to a server: open it there

    For a device on a server, the keywords go to `connect` (`claim`, `reuse`, `program`, `need`, `timeout`...); here,
    to `Device.open`"""
    from . import targets
    if isinstance(what, targets.Radio):
        what = what.target
    if isinstance(what, DeviceInfo):
        if serial is not None:
            open_args["serial"] = serial
        return what.open(**open_args)
    if isinstance(what, str) and ("/" in what or "@" in what):
        t = targets.parse_target(what)
        serial = serial if serial is not None else t.serial
        if t.server is not None:
            if serial is not None:
                open_args["serial"] = serial
            return connect(t.server, t.device, **open_args)
        what = t.device
    if serial is not None:
        open_args["serial"] = serial
    sdr = device(what)
    sdr.open(**open_args)
    return sdr

pysdrlib.targets

Finding radios, here and on servers, and naming each with one string pysdrlib.open takes

for r in pysdrlib.discover():          # attached here, and on the servers in PYSDRLIB_SERVERS
    print(r.label, r.target, r.state, r.controlled)
sdr = pysdrlib.open(r.target)

A target is [server/]device:

Target Opens
<driver> the first radio of that driver attached here
<driver>@<serial> the one with that serial (or the end of it)
radiohost/<driver>-0 the device a server hosts as <driver>-0: attach to it (receive; claim=True to control it)
radiohost:5556/<driver>@<serial> a radio attached to that server: it opens it, and you control it
radiohost/<driver> any radio of that driver the server has (or can open)
tcp://10.0.0.5/<driver>@<serial> the same with a scheme
ipc:///run/pysdrlib/c2/sim-0 over a local socket (its path ends at the last /, so an ipc target names a device)

A server is host, host:port (port 5555 when left out) or a ZeroMQ endpoint (tcp://..., ipc://...). PYSDRLIB_SERVERS lists the servers discover asks by default, separated by commas or whitespace.

Classes:

Name Description
Target

A parsed target: server (a ZeroMQ endpoint, None: this machine), device (a driver name, or the id of a device a

Radio

A radio discover found. target: what pysdrlib.open takes to open it. state: "attached" (nobody has it open:

Functions:

Name Description
endpoint

A server as a ZeroMQ endpoint: "radiohost" -> "tcp://radiohost:5555", "radiohost:5556" -> "tcp://radiohost:5556";

short

How a server is written in a target: "tcp://radiohost:5555" -> "radiohost", "tcp://host:5556" -> "host:5556"

parse_target

[server/]device[@serial] -> Target (see the module's table). A server alone ("tcp://radiohost", "radiohost/") has

format_target

The target string for a device (None: whatever the server picks) on server (None: this machine)

servers

The server endpoints in value, or in $PYSDRLIB_SERVERS when it is None: addresses separated by commas or

discover

The radios attached here and on servers, as Radios (each with the target pysdrlib.open takes):

Target dataclass

Target(server: Optional[str], device: Optional[str], serial: Optional[str] = None)

A parsed target: server (a ZeroMQ endpoint, None: this machine), device (a driver name, or the id of a device a server hosts; None: whatever the server picks) and serial

Radio dataclass

Radio(label: str, target: str, state: str, driver: str, serial: Optional[str] = None, server: Optional[str] = None, id: Optional[str] = None, controlled: Optional[bool] = None, program: Optional[str] = None, antennas: tuple = (), receiving: Optional[bool] = None, extra: dict = dict())

A radio discover found. target: what pysdrlib.open takes to open it. state: "attached" (nobody has it open: opening it makes you its controller), "hosted" (a server has it open: you attach to its stream; see controlled) or "openable" (a kind of device the server can open that isn't a radio it lists: simulated, network, files...). controlled: whether a client controls a hosted one (None otherwise), and program which. receiving: whether a hosted one is streaming (None otherwise). antennas: what is known of the receive chains ([{"port", "name", "antenna"}]: the antenna's description, or None)

endpoint

endpoint(server: str) -> str

A server as a ZeroMQ endpoint: "radiohost" -> "tcp://radiohost:5555", "radiohost:5556" -> "tcp://radiohost:5556"; an endpoint (tcp://, ipc://...) is kept, with the default port added to a tcp:// one without. Raises ValueError for anything else: a tcp server is host[:port] (an IPv6 host in brackets), an ipc one a path

Source code in src/pysdrlib/targets.py
def endpoint(server: str) -> str:
    """A server as a ZeroMQ endpoint: "radiohost" -> "tcp://radiohost:5555", "radiohost:5556" -> "tcp://radiohost:5556";
    an endpoint (tcp://, ipc://...) is kept, with the default port added to a tcp:// one without. Raises ValueError
    for anything else: a tcp server is host[:port] (an IPv6 host in brackets), an ipc one a path"""
    text = str(server).strip()
    server = text[:-1] if text.endswith("/") and not text.endswith("://") else text
    if not server:
        raise ValueError("an empty server address")
    if "://" not in server:
        server = "tcp://" + server
    scheme, rest = server.split("://", 1)
    if scheme not in _SCHEMES:
        raise ValueError(f"server {text!r}: the scheme is one of {', '.join(_SCHEMES)}, not {scheme!r}")
    if scheme != "tcp":
        if not rest.strip("/"):
            raise ValueError(f"server {text!r} has no path")
        return server
    m = _HOST.match(rest)
    if not m:
        raise ValueError(f"server {text!r}: a tcp server is host or host:port")
    if m["port"] is not None and not 0 < int(m["port"]) < 65536:
        raise ValueError(f"server {text!r}: port {m['port']} is out of range")
    return server if m["port"] is not None else f"{server}:{DEFAULT_PORT}"

short

short(server: str) -> str

How a server is written in a target: "tcp://radiohost:5555" -> "radiohost", "tcp://host:5556" -> "host:5556" (other endpoints as they are)

Source code in src/pysdrlib/targets.py
def short(server: str) -> str:
    """How a server is written in a target: "tcp://radiohost:5555" -> "radiohost", "tcp://host:5556" -> "host:5556"
    (other endpoints as they are)"""
    server = endpoint(server)
    if server.startswith("tcp://"):
        rest = server[len("tcp://"):]
        return rest[:-len(f":{DEFAULT_PORT}")] if rest.endswith(f":{DEFAULT_PORT}") else rest
    return server

parse_target

parse_target(text: str) -> Target

[server/]device[@serial] -> Target (see the module's table). A server alone ("tcp://radiohost", "radiohost/") has no device: the server picks

Source code in src/pysdrlib/targets.py
def parse_target(text: str) -> Target:
    """`[server/]device[@serial]` -> Target (see the module's table). A server alone ("tcp://radiohost", "radiohost/") has
    no device: the server picks"""
    text = str(text).strip()
    if not text:
        raise ValueError("an empty target")
    scheme_only = "://" in text and "/" not in text.split("://", 1)[1]
    if scheme_only:
        server, device = text, ""
    elif "/" in text:
        server, device = text.rsplit("/", 1)
    else:
        server, device = None, text
    serial = None
    if "@" in device:
        device, serial = device.split("@", 1)
        serial = serial or None
    if server is not None:
        server = endpoint(server)
    if server is None and not device:
        raise ValueError(f"target {text!r} names no device")
    return Target(server, device or None, serial)

format_target

format_target(server: Optional[str], device: Optional[str], serial: Optional[str] = None) -> str

The target string for a device (None: whatever the server picks) on server (None: this machine)

Source code in src/pysdrlib/targets.py
def format_target(server: Optional[str], device: Optional[str], serial: Optional[str] = None) -> str:
    """The target string for a device (None: whatever the server picks) on `server` (None: this machine)"""
    name = (device or "") + (f"@{serial}" if serial else "")
    return name if server is None else f"{short(server)}/{name}"

servers

servers(value: Optional[str] = None) -> list

The server endpoints in value, or in $PYSDRLIB_SERVERS when it is None: addresses separated by commas or whitespace

Source code in src/pysdrlib/targets.py
def servers(value: Optional[str] = None) -> list:
    """The server endpoints in `value`, or in $PYSDRLIB_SERVERS when it is None: addresses separated by commas or
    whitespace"""
    if value is None:
        value = os.environ.get(SERVERS_ENV, "")
    return [endpoint(s) for s in re.split(r"[,\s]+", value) if s]

discover

discover(servers=None, local=True, zeroconf=False, timeout=2.0, virtual=False, errors=None) -> list

The radios attached here and on servers, as Radios (each with the target pysdrlib.open takes):

for r in pysdrlib.discover(servers=["radiohost", "10.0.0.5:5556"]):
    print(r.label, r.target, r.state, r.controlled, r.antennas)

servers: addresses (see endpoint), or a string of them; None: $PYSDRLIB_SERVERS. Asked at once, each given timeout seconds; one that doesn't answer is left out (and, when errors is a list, (server, exception) is added to it). local: list the radios attached here (pysdrlib.find; virtual adds simulated ones). zeroconf: also the servers announcing themselves on the local network (needs zeroconf)

Source code in src/pysdrlib/targets.py
def discover(servers=None, local=True, zeroconf=False, timeout=2.0, virtual=False, errors=None) -> list:
    """The radios attached here and on servers, as `Radio`s (each with the `target` `pysdrlib.open` takes):

        for r in pysdrlib.discover(servers=["radiohost", "10.0.0.5:5556"]):
            print(r.label, r.target, r.state, r.controlled, r.antennas)

    servers: addresses (see `endpoint`), or a string of them; None: $PYSDRLIB_SERVERS. Asked at once, each given
    `timeout` seconds; one that doesn't answer is left out (and, when `errors` is a list, (server, exception) is
    added to it). local: list the radios attached here (`pysdrlib.find`; `virtual` adds simulated ones).
    zeroconf: also the servers announcing themselves on the local network (needs zeroconf)"""
    if servers is None or isinstance(servers, str):
        addresses = _servers(servers)
    else:
        addresses = [endpoint(s) for s in servers]
    if zeroconf:
        from .remote import discovery
        for s in discovery.discover(timeout):
            addresses.append(endpoint(s["address"]))
    addresses = list(dict.fromkeys(addresses))   # once each, in order
    found = _local(virtual) if local else []
    if not addresses:
        return found
    try:
        import zmq  # noqa: F401
    except ImportError as exc:
        raise ImportError("asking servers needs pyzmq: pip install pysdrlib[remote]") from exc
    with concurrent.futures.ThreadPoolExecutor(max_workers=min(16, len(addresses))) as pool:
        jobs = [(s, pool.submit(_remote, s, timeout)) for s in addresses]
        for server, job in jobs:
            try:
                found.extend(job.result())
            except Exception as exc:
                _log.info("discover: %s: %s: %s", server, type(exc).__name__, exc)
                if errors is not None:
                    errors.append((server, exc))
    return found