def find_contexts(config, map):
    ctxs = iio.scan_contexts()
    if not ctxs:
        print("\nNo libiio contexts found")
        return False
    ctxs_plus_hw = []
    for uri in ctxs:
        info = ctxs[uri]
        type = uri.split(":")[0]
        devices = info.split("(")[1].split(")")[0]

        if config.getoption("--scan-verbose"):
            string = "\nContext: {}".format(uri)
            string += "\n\tType: {}".format(type)
            string += "\n\tInfo: {}".format(info)
            string += "\n\tDevices: {}".format(devices)
            print(string)

        ctx_plus_hw = {
            "uri": uri,
            "type": type,
            "devices": devices,
            "hw": lookup_hw_from_map(iio.Context(uri), map),
        }
        ctxs_plus_hw.append(ctx_plus_hw)
    else:
        if config.getoption("--scan-verbose"):
            print("\nNo libiio contexts found")

    return ctxs_plus_hw
 def __init__(self):
     """Initialize the ADXL345 accelerometer using iio python library
     """
     self._Acceleration_xyz = []
     self.data_x = [0] * 5   
     self.data_y = [0] * 5 
     self.data_z = [0] * 5
     self.Path = '/proc/device-tree/aliases/adxl345'
     try:
         # Check BB-I2C2-ADXL34X whether install successfully
         # if not reinstall it
         if not os.path.exists(self.Path):
             InstallDTBO('BB-I2C2-ADXL34X')
             while not os.path.exists(self.Path):
                 time.sleep(0.1) 
         #  Reinstall adxl345_xxx module to support hot plug                   
         ReinstallModule('adxl345_i2c')    
         # Scan the adxl345 by using IIO python library        
         self.contexts = iio.scan_contexts()
         self.ctx = iio.Context("local:") 
         self.dev = self.ctx.find_device("adxl345")
         # Initialize the data of adxl345 for SlidingAverage function
         self._Acceleration_xyz.append(self.dev.find_channel("accel_x", False))
         self._Acceleration_xyz.append(self.dev.find_channel("accel_y", False))
         self._Acceleration_xyz.append(self.dev.find_channel("accel_z", False))
         for i in range(5):
             self.data_x[i] = int(self._Acceleration_xyz[0].attrs["raw"].value)
             self.data_y[i] = int(self._Acceleration_xyz[1].attrs["raw"].value)
             self.data_z[i] = int(self._Acceleration_xyz[2].attrs["raw"].value)                
     except IOError as err:
         print("File Error:"+str(err))
         print("maybe you should reinstall the driver of adxl345")       
Exemple #3
0
    def __init__(self, *args: Union[str, iio.Context],
                 **kwargs: Union[str, iio.Context]) -> None:

        # Handle Older API and Newer APIs
        uri_ctx = self.__handle_init_args(args, kwargs)

        # Handle context
        if isinstance(uri_ctx, iio.Context):
            self._ctx = uri_ctx
            self.uri = ""
        elif uri_ctx:
            self.uri = uri_ctx
            context_manager.__init__(self, uri_ctx, self._device_name)
        else:
            required_devices = [
                self._rx_data_device_name, self._control_device_name
            ]
            contexts = iio.scan_contexts()
            self._ctx = None
            for c in contexts:
                ctx = iio.Context(c)
                devs = [dev.name for dev in ctx.devices]
                if all(dev in devs for dev in required_devices):
                    self._ctx = iio.Context(c)
                    break
            if not self._ctx:
                raise Exception("No context could be found for class")

        # Set up devices
        if self._control_device_name:
            self._ctrl = self._ctx.find_device(self._control_device_name)
            if not self._ctrl:
                raise Exception(
                    f"No device found with name {self._control_device_name}")
Exemple #4
0
def _create_context():
    if len(sys.argv) == 3 and sys.argv[1] == "--uri":
        uri = sys.argv[2]
    else:
        contexts = iio.scan_contexts()
        if len(contexts) > 1:
            print("Multiple contexts found. Please select one using --uri:")
            for uri, description in contexts.items():
                print("\t%s: %s" % (uri, description))
        sys.exit(0)

    return iio.Context(uri)
 def __init__(self):
     """
     Will pick the first available iio context. \
     Note: this assumes that the first context \
     is a Pluto Device.
     """
     contexts = iio.scan_contexts()
     if len(contexts.keys()) > 0:
         uri = str(next(enumerate(contexts))[1])
         PlutoSdr.__init__(self, uri=uri)
     else:
         raise Exception("Could not find any Pluto Devices")
Exemple #6
0
def check_pluto():
    # Try USB contexts first
    contexts = iio.scan_contexts()
    for c in contexts:
        if "PlutoSDR" in contexts[c]:
            return True
    # Try auto discover
    try:
        iio.Context("ip:pluto.local")
        return True
    except Exception as e:
        print(e)
        return False
Exemple #7
0
    def _auto(self):
        contexts = iio.scan_contexts()
        if len(contexts) == 0:
            raise Exception("No IIO context found.\n")
        if len(contexts) == 1:
            uri, _ = contexts.popitem()
            self.ctx = iio.Context(_context=uri)
        else:
            print("Multiple contexts found. Please select one using --uri!")
            for uri, _ in contexts.items():
                print(uri)
            sys.exit(0)

        return self
Exemple #8
0
def getSdr():
    """
    Gets PlutoSdr object from pluto.pluto_sdr module
    
    returns: type=pluto.pluto_sdr.PlutoSdr
    """
    global _sdr
    if _sdr is None:
        ctxs = iio.scan_contexts()
        if len(ctxs.keys()) > 0:
            _sdr = PlutoSdrWrapper()
        else:
            _sdr = SimPlutoSdr(P=30, alpha=0.3, desiredBandwidth=1.0)

    return _sdr
Exemple #9
0
def scan_all():
    boards = []
    # Find USB/LOCAL
    ctxs = iio.scan_contexts()
    for ctx in ctxs:
        c = iio.Context(ctx)
        name = check_board_other(c)
        if name:
            boards.append(board(name, c.name))
    # FIND IP
    bs = ip_scan_auto()
    #bs = ip_scan("192.168.86")
    if bs not in boards:
        boards = boards + bs
    return boards
Exemple #10
0
def create_context(scan_for_context, arg_uri, arg_ip):
    """
    Method for creating the corresponding context.

    parameters:
        scan_for_context: type=bool
            Scan for available contexts and if only one is available use it.
        arg_uri: type=string
            The URI on which the program should look for a Context.
        arg_ip: type=string
            The IP on which the program should look for a Network Context.

    returns: type:iio.Context
        The resulted context.
    """
    ctx = None

    try:
        if scan_for_context:
            contexts = iio.scan_contexts()
            if len(contexts) == 0:
                sys.stderr.write('No IIO context found.')
                exit(1)
            elif len(contexts) == 1:
                uri, _ = contexts.popitem()
                ctx = iio.Context(_context=uri)
            else:
                print('Multiple contexts found. Please select one using --uri!')

                for uri, _ in contexts:
                    print(uri)
        elif arg_uri != '':
            ctx = iio.Context(_context=arg_uri)
        elif arg_ip != '':
            ctx = iio.NetworkContext(arg_ip)
        else:
            ctx = iio.Context()
    except FileNotFoundError:
        sys.stderr.write('Unable to create IIO context')
        exit(1)

    return ctx
Exemple #11
0
 def __init__(self, uri="", device_name=""):
     self.uri = uri
     try:
         if self.uri == '':
             # Try USB contexts first
             if device_name != '':
                 contexts = iio.scan_contexts()
                 for c in contexts:
                     if device_name in contexts[c]:
                         self.ctx = iio.Context(c)
                         break
             # Try auto discover
             if not self.ctx and self.uri_auto != '':
                 self.ctx = iio.Context(self.uri_auto)
             if not self.ctx:
                 raise
         else:
             self.ctx = iio.Context(self.uri)
     except BaseException:
         raise Exception("No device found")
Exemple #12
0
def scan_all(skip_usb=False):
    boards = []

    # FIND IP
    bs = ip_scan_auto()
    # bs = ip_scan("192.168.86")

    if bs not in boards:
        boards = boards + bs

    # Find USB/LOCAL
    if not skip_usb:
        ctxs = iio.scan_contexts()
        for ctx in ctxs:
            c = iio.Context(ctx)
            name = check_board_other(c)
            if name:
                if c.name == "local":
                    boards.append(board(name, "local:"))
                else:
                    boards.append(board(name, ctx))
    return boards
Exemple #13
0
 def __init__(self):
     """Initialize the ADC of PocketBeagle using iio python library
     """
     self.AIN = []
     #Scan the ADC of PocketBeagle by using IIO python library
     self.contexts = iio.scan_contexts()
     self.ctx = iio.Context("local:")
     for dev in self.ctx.devices:
         if 'adc.0.auto' in dev.name:
             self.name = dev.name
     self.dev = self.ctx.find_device(self.name)
     if not self.dev:
         print("maybe you should reinstall the driver of ADC")
         return
     #Integrate all channels to self.AIN
     self.AIN.append(self.dev.find_channel("voltage0", False))
     self.AIN.append(self.dev.find_channel("voltage1", False))
     self.AIN.append(self.dev.find_channel("voltage2", False))
     self.AIN.append(self.dev.find_channel("voltage3", False))
     self.AIN.append(self.dev.find_channel("voltage4", False))
     self.AIN.append(self.dev.find_channel("voltage5", False))
     self.AIN.append(self.dev.find_channel("voltage6", False))
     self.AIN.append(self.dev.find_channel("voltage7", False))
Exemple #14
0
 def __init__(self):
     """Initialize the HCSR04 using iio python library
     """
     self.Path = '/proc/device-tree/hcsr04_1057@20'
     try:
         # Config P1_31 to GPIO mode
         ConfigGPIO('P1_31')
         # Check BB-GPIO-HCSR04 whether install successfully
         # if not reinstall it
         if not os.path.exists(self.Path):
             InstallDTBO('BB-GPIO-P9813')
             while not os.path.exists(self.Path):
                 time.sleep(0.1)
         # Scan the adxl345 by using IIO python library
         self.contexts = iio.scan_contexts()
         self.ctx = iio.Context("local:")
         self.dev = self.ctx.find_device("hcsr04_1057@20")
         if not self.dev:
             print("maybe you should reinstall the driver of hcsr")
             return
     except IOError as err:
         print("File Error:" + str(err))
         print("maybe you should reinstall the driver of hcsr04")
Exemple #15
0
    def __init__(self, uri=None, rx_lo=1000000000, tx_lo=1000000000, \
      sample_rate=5000000, rx_rf_bandwidth=3000000, tx_rf_bandwidth=3000000, \
      rx_hardwaregain=30, tx_hardwaregain=-10, gain_control_mode='slow_attack'):
        self.uri = uri

        # Initialize context
        self.ctx = None
        try:
            if uri:
                self.ctx = iio.Context(self.uri)
            else:
                contexts = iio.scan_contexts()
                for uri in contexts:
                    if 'PlutoSDR' in contexts[uri]:
                        self.ctx = iio.Context(uri)
                if self.ctx == None:
                    raise Exception()
        except:
            print("No PlutoSDR device found")
            sys.exit(0)

        self.ctrl = self.ctx.find_device("ad9361-phy")
        self.txdac = self.ctx.find_device("cf-ad9361-dds-core-lpc")
        self.rxadc = self.ctx.find_device("cf-ad9361-lpc")

        self.rx_lo = rx_lo
        self.tx_lo = tx_lo
        # self.sample_rate = sample_rate
        self.rx_rf_bandwidth = rx_rf_bandwidth
        self.tx_rf_bandwidth = tx_rf_bandwidth

        self.gain_control_mode = gain_control_mode
        self.rx_hardwaregain = rx_hardwaregain
        self.tx_hardwaregain = tx_hardwaregain

        self.rxbuf = None
Exemple #16
0
def main():
    """Dump iio devices, list all iio attributes."""
    print("Library version: %u.%u (git tag: %s)" % iio.version)

    if len(argv) == 3 and argv[1] == "--uri":
        uri = argv[2]
    else:
        contexts = iio.scan_contexts()
        if len(contexts) > 1:
            print("Multiple contexts found. Please select one using --uri:")
            for index, each in enumerate(contexts):
                print("\t%d: %s [%s]" % (index, contexts[each], each))
            return

        uri = next(iter(contexts), None)

    ctx = iio.Context(uri)

    if uri is not None:
        print('Using auto-detected IIO context at URI "%s"' % uri)

    print("IIO context created: " + ctx.name)
    print("Backend version: %u.%u (git tag: %s)" % ctx.version)
    print("Backend description string: " + ctx.description)

    if len(ctx.attrs) > 0:
        print("IIO context has %u attributes:" % len(ctx.attrs))
    for attr, value in ctx.attrs.items():
        print("\t" + attr + ": " + value)

    print("IIO context has %u devices:" % len(ctx.devices))

    for dev in ctx.devices:
        print("\t" + dev.id + ": " + dev.name)

        if dev is iio.Trigger:
            print("Found trigger! Rate: %u Hz" % dev.frequency)

        print("\t\t%u channels found:" % len(dev.channels))

        for chn in dev.channels:
            print(
                "\t\t\t%s: %s (%s)" %
                (chn.id, chn.name or "", "output" if chn.output else "input"))

            if len(chn.attrs) != 0:
                print("\t\t\t%u channel-specific attributes found:" %
                      len(chn.attrs))

            for attr in chn.attrs:
                try:
                    print("\t\t\t\t" + attr + ", value: " +
                          chn.attrs[attr].value)
                except OSError as err:
                    print("Unable to read " + attr + ": " + err.strerror)

        if len(dev.attrs) != 0:
            print("\t\t%u device-specific attributes found:" % len(dev.attrs))

        for attr in dev.attrs:
            try:
                print("\t\t\t" + attr + ", value: " + dev.attrs[attr].value)
            except OSError as err:
                print("Unable to read " + attr + ": " + err.strerror)

        if len(dev.debug_attrs) != 0:
            print("\t\t%u debug attributes found:" % len(dev.debug_attrs))

        for attr in dev.debug_attrs:
            try:
                print("\t\t\t" + attr + ", value: " +
                      dev.debug_attrs[attr].value)
            except OSError as err:
                print("Unable to read " + attr + ": " + err.strerror)
Exemple #17
0
# https://ez.analog.com/thread/97117-using-iiopy-with-m2k
# https://mirrors.dotsrc.org/fosdem/2018/AW1.120/plutosdr.webm
# https://wiki.analog.com/resources/tools-software/linux-software/fmcomms2_plugin
import iio, struct, time
import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
ctxs = iio.scan_contexts()
uri = next(iter(ctxs), None)
ctx = iio.Context(uri)
dev = ctx.find_device('cf-ad9361-lpc')
phy = ctx.find_device('ad9361-phy')
phy.channels[0].attrs['frequency'].value = str(int(1575.42e6))
dev.channels[0].enabled = True
dev.channels[1].enabled = True
buf = iio.Buffer(dev, 4096, cyclic=False)
ys = []
for i in range(1024):
    buf.refill()
    ys.append(buf.read())
d = np.frombuffer(np.array([inner for outer in ys for inner in outer]),
                  dtype=np.int16)
q = d[::2] + 1j * d[1::2]
f, t, z = scipy.signal.stft(q[0:32 * 4096])
plt.imshow(np.abs(z))
plt.show()

print(iio.version)

ctxs = iio.scan_contexts()
Exemple #18
0
def main():
	print('Library version: %u.%u (git tag: %s)' % iio.version)

	if len(argv) == 3 and argv[1] == '--uri':
		uri = argv[2]
	else:
		contexts = iio.scan_contexts()
		if len(contexts) > 1:
			print('Multiple contexts found. Please select one using --uri:')
			for index, each in enumerate(contexts):
				print('\t%d: %s [%s]' % (index, contexts[each], each))
			return

		uri = next(iter(contexts), None)

	ctx = iio.Context(uri)

	if uri is not None:
		print('Using auto-detected IIO context at URI \"%s\"' % uri)

	print('IIO context created: ' + ctx.name)
	print('Backend version: %u.%u (git tag: %s)' % ctx.version)
	print('Backend description string: ' + ctx.description)

	if len(ctx.attrs) > 0:
		print('IIO context has %u attributes:' % len(ctx.attrs))
	for attr, value in ctx.attrs.items():
		print('\t' + attr + ': ' + value)

	print('IIO context has %u devices:' % len(ctx.devices))

	for dev in ctx.devices:
		print('\t' + dev.id + ': ' + dev.name)

		if dev is iio.Trigger:
			print('Found trigger! Rate: %u Hz' % dev.frequency)

		print('\t\t%u channels found:' % len(dev.channels))

		for chn in dev.channels:
			print('\t\t\t%s: %s (%s)' % (chn.id, chn.name or "", 'output' if chn.output else 'input'))

			if len(chn.attrs) != 0:
				print('\t\t\t%u channel-specific attributes found:' % len(chn.attrs))

			for attr in chn.attrs:
				try:
					print('\t\t\t\t' + attr + ', value: ' + chn.attrs[attr].value)
				except OSError as e:
					print('Unable to read ' + attr + ': ' + e.strerror)

		if len(dev.attrs) != 0:
			print('\t\t%u device-specific attributes found:' % len(dev.attrs))

		for attr in dev.attrs:
			try:
				print('\t\t\t' + attr + ', value: ' + dev.attrs[attr].value)
			except OSError as e:
				print('Unable to read ' + attr + ': ' + e.strerror)

		if len(dev.debug_attrs) != 0:
			print('\t\t%u debug attributes found:' % len(dev.debug_attrs))

		for attr in dev.debug_attrs:
			try:
				print('\t\t\t' + attr + ', value: ' + dev.debug_attrs[attr].value)
			except OSError as e:
				print('Unable to read ' + attr + ': ' + e.strerror)
Exemple #19
0
rospack = rospkg.RosPack()
sys.path.append(rospack.get_path('led_control') + '/src')
from leds import MatrixLeds

RAD_TO_DEG = 57.29578
M_PI = 3.14159265358979323846
G_GAIN = 0.070  # [deg/s/LSB]  If you change the dps for gyro, you need to update this value accordingly
AA = 0.40  # Complementary filter constant

gyroXangle = 0.0
gyroYangle = 0.0
gyroZangle = 0.0
CFangleX = 0.0
CFangleY = 0.0

contexts = iio.scan_contexts()
uri = next(iter(contexts), None)
ctx = iio.Context(uri)

leds = MatrixLeds()
imu = ctx.devices[0]

a = datetime.datetime.now()

while True:

    #Read the accelerometer,gyroscope and magnetometer values
    ACCx = float((c for c in imu.channels
                  if c.id == "accel_x").next().attrs['raw'].value)
    ACCy = float((c for c in imu.channels
                  if c.id == "accel_y").next().attrs['raw'].value)