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}")
def __init__(self, uri=PLUTO_ID): # access to internal devices try: self.ctx = iio.Context(uri) except OSError: self.ctx = None print('exception: no iio device context found at', uri) return logging.debug('found context for pluto device') self.name = 'plutosdr' self.phy = self.ctx.find_device('ad9361-phy') # individual TRx controls self.phy_rx = self.phy.find_channel('voltage0', is_output=False) self.phy_tx = self.phy.find_channel('voltage0', is_output=True) # access to data channels for Rx self.adc = self.ctx.find_device('cf-ad9361-lpc') # access to data channels for Tx self.dac = self.ctx.find_device('cf-ad9361-dds-core-lpc') self.tx_channels = [self.dac.find_channel('voltage0', True)] self.tx_channels.append(self.dac.find_channel('voltage1', True)) # also access to the internal 2 tone generator self.dds = pluto_dds.Dds(self.dac) # tx buffer, created in writeTx and retained for continuous output self._tx_buff = None self.tx_state = self.TX_OFF
def __init__(self): self._ctx = iio.Context() if(self._ctx): self._bmp280_kd = Bmp280_kd(self._ctx) self._htu21d_kd = Htu21d_kd(self._ctx) raise RuntimeError("No iio context found")
def iio_dev_interface(self, attrtype, dev_name, chan_name, inout, attr, val, tol): sdr = iio.Context(self.uri) attr_tl = attrtype.lower() if attr_tl == "context": ats = sdr.attrs ats[attr].Value = str(val) rval = float(sdr.attrs[attr].Value) elif attr_tl == "debug": raise Exception("Not supported") elif attr_tl == "device": dev = sdr.find_device(dev_name) assert dev, "Device Not Found" dev.attrs[attr].Value = str(val) rval = float(dev.attrs[attr].Value) elif attr_tl == "channel": dev = sdr.find_device(dev_name) assert dev, "Device Not Found" chan = dev.find_channel(chan_name, inout) assert chan, "Channel Not Found" chan.attrs[attr].Value = str(val) rval = float(chan.attrs[attr].Value) else: raise Exception("Device type unknown " + str(attrtype)) del sdr if not isinstance(val, str): if abs(val - rval) > tol: print("Failed to set: " + attr) print("Set: " + str(val)) print("Got: " + str(rval)) return abs(val - rval) return val == str(rval)
def get_all_devices(): ctx = iio.Context() devices = [] if len(ctx.devices) == 0: return app.response_class(response=json.dumps("No devices detected"), status=404, mimetype='application/json') for device in ctx.devices: dev = Dev() dev.name = device.name for channel in device.channels: chan = Channel() chan.id = channel.id for attr, _ in channel.attrs.items(): try: attribute = Attribute() setattr(attribute, channel.attrs[attr].name, channel.attrs[attr].value) chan.attrs.append(attribute) except OSError as err: print("ERROR: " + err.strerror + " (-" + str(err.errno) + ")") return app.response_class(response=json.dumps( "Error reading channel attributes"), status=404, mimetype='application/json') dev.channels.append(chan) devices.append(dev) data = json.dumps(devices, default=lambda o: o.__dict__, indent=4) response = app.response_class(response=data, status=200, mimetype='application/json') return response
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")
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): """ Configure IIOAcmeCape. Create IIO context, detect attached probes. Args: None Returns: bool: True if operation is successful, False otherwise. """ # Connecting to ACME try: self._trace.trace(1, "Connecting to %s..." % self._ip) self._iioctx = iio.Context("ip:" + self._ip) except OSError: self._trace.trace(1, "Connection timed out!") return False except: self._trace.trace(2, traceback.format_exc()) return False if self._verbose_level >= 2: self._show_iio_context_attributes() # There is not yet an attribute in the IIO device to indicate in which # ACME Cape slot the IIO device is attached. Hence, need to first find # the populated ACME Cape slot(s), and then save this info. try: self._find_probes() except: self._trace.trace(2, traceback.format_exc()) return False return True
def test_board_available(): ctx = iio.Context("ip:"+board_config.board_ip) found = 0 for dev in ctx.devices: if dev.name in board_config.devices: found = found + 1 if found!=len(board_config.devices): assert False
def test_iio_devices_appear(): time.sleep(30) # Give time for iiod to start ctx = iio.Context("ip:"+board_config.board_ip) found = 0 for dev in ctx.devices: if dev.name in board_config.devices: found = found + 1 if found!=len(board_config.devices): assert False
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
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")
def __init__(self): # create local IIO context self.iio_ctx = iio.Context() # access physical devices self.dev_a = self.iio_ctx.find_device("ad9361-phy") self.dev_b = self.iio_ctx.find_device("ad9361-phy-B") self.devs = (self.dev_a, self.dev_b) self.data = None
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, bandwidth, samp_rate, cntr_freq, buff_size): self.bandwidth = bandwidth self.samp_rate = samp_rate self.cntr_freq = cntr_freq self.buff_size = buff_size # create local IIO context self.context = iio.Context() # configure the AD9361 devices self._configure_ad9361_phy(bandwidth, samp_rate, cntr_freq) self._create_buffer(buff_size)
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
def __init__(self, config, influx_client): self.name = config['name'] self.logger = logger.getChild(self.name) self.logger.info('Creating IIOSubmitter object') self.context = iio.Context(config['uri']) self.devices = {} self.idb = influx_client for device in config['devices']: d = self.match_device(device['match']) if d: self.devices[device['name']] = d self.logger.info(f'Loaded devices {",".join(self.devices.keys())}')
def test_attribute_changes(context_desc): ctx = None for ctx_desc in context_desc: if ctx_desc["hw"] in hardware: ctx = iio.Context(ctx_desc["uri"]) if not ctx: pytest.skip("No valid hardware found") drivers_to_ignore = "xadc" # Set initial state ctx.find_device("ad9361-phy").find_channel( "RX_LO").attrs["frequency"].value = "1000000000" ctx.find_device("ad9361-phy").find_channel( "TX_LO").attrs["frequency"].value = "1000000000" # Collect state of all attributes state1 = get_states(ctx, drivers_to_ignore) # Change LOs ctx.find_device("ad9361-phy").find_channel( "RX_LO").attrs["frequency"].value = "2000000000" ctx.find_device("ad9361-phy").find_channel( "TX_LO").attrs["frequency"].value = "2000000000" # Collect state of all attributes after change state2 = get_states(ctx, drivers_to_ignore) # Set up comparison expected_to_change = [ "ad9361-phy_out_altvoltage0_frequency", "ad9361-phy_out_altvoltage1_frequency", ] allowed_to_change = [ "ad7291_in_temp0_mean_raw", "ad7291_in_temp0_raw", "ad9361-phy_in_temp0_input", "ad9361-phy_in_voltage0_hardwaregain", "ad9361-phy_in_voltage1_hardwaregain", "ad9361-phy_in_voltage2_raw", "ad9361-phy_in_voltage0_rssi", "ad9361-phy_in_voltage1_rssi", "ad9361-phy_in_voltage0_hardwaregain_available", "ad9361-phy_in_voltage1_hardwaregain_available", ] for k in range(6): allowed_to_change.append("ad7291_in_voltage{}_raw".format(k)) compare_states(state1, state2, expected_to_change, allowed_to_change)
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
def check_iio_devices(self): """ Verify all IIO drivers appear on system as expected. Exception is raised otherwise """ log.info("Checking uri: " + self.uri) ctx = iio.Context(self.uri) devs = [d.name for d in ctx.devices] missing_devs = [] for dev in self.iio_device_names: log.info("Checking for: " + str(dev)) if dev not in devs: missing_devs.append(dev) if len(missing_devs) != 0: raise Exception("Device(s) not found " + str(missing_devs))
def connect_device(): global phy, txdac, rxadc try: ctx = iio.Context('ip:192.168.2.1') except: return ERROR phy = ctx.find_device("ad9361-phy") # Register control txdac = ctx.find_device( "cf-ad9361-dds-core-lpc") # TX/DAC Core in HDL for DMA (plus DDS) rxadc = ctx.find_device("cf-ad9361-lpc") # RX/ADC Core in HDL for DMA return phy, txdac, rxadc, ctx
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
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
class analog_in(): channels = {0: 'vaux8', 1: 'vaux0', 2: 'vaux1', 3: 'vaux9'} ctx = iio.Context() dev = ctx.devices[0] # resistor divider resdiv = 4.99 / (30.0 + 4.99) def __init__(self, channel): if channel in range(4): channel = self.channels[channel] self.chn = self.dev.find_channel(channel) self.scale = self.chn.attrs['scale'].value def read(self): raw = self.chn.attrs['raw'].value return (int(raw) * float(self.scale) / 1000 / self.resdiv)
def test_generic_rx_with_ctx_pv(iio_uri): class MyAD9361(adi.rx_tx.rx_tx_def): _complex_data = True _control_device_name = "ad9361-phy" _rx_data_device_name = "cf-ad9361-lpc" _tx_data_device_name = "cf-ad9361-dds-core-lpc" def __post_init__(self): pass ctx = iio.Context(iio_uri) dev = MyAD9361(uri_ctx=ctx) dev.rx() assert dev._rxadc assert dev._txdac assert dev._ctrl
def __init__(self, target=None, iio_context=None, use_base_iio_context=False, probe_names=None): if iio_import_failed: raise HostError( 'Could not import "iio": {}'.format(iio_import_error)) super(BaylibreAcmeInstrument, self).__init__(target) if isinstance(probe_names, basestring): probe_names = [probe_names] self.iio_context = (iio_context if not use_base_iio_context else iio.Context(iio_context)) self.check_version() if probe_names is not None: if len(probe_names) != len(set(probe_names)): msg = 'Probe names should be unique: {}' raise ValueError(msg.format(probe_names)) if len(probe_names) != len(self.iio_context.devices): msg = ('There should be as many probe_names ({}) ' 'as detected probes ({}).') raise ValueError( msg.format(len(probe_names), len(self.iio_context.devices))) probes = [IIOINA226Instrument(d) for d in self.iio_context.devices] self.probes = (dict(zip(probe_names, probes)) if probe_names else {p.iio_device.id: p for p in probes}) self.active_probes = set() for probe in self.probes: for measure in ['voltage', 'power', 'current']: self.add_channel(site=probe, measure=measure) self.add_channel('timestamp', 'time_us') self.data = pd.DataFrame()
def _contexts(request): """ Contexts fixture which provides a list of dictionaries of found boards """ if request.config.getoption("--adi-hw-map"): path = pathlib.Path(__file__).parent.absolute() filename = os.path.join(path, "resources", "adi_hardware_map.yml") elif request.config.getoption("--custom-hw-map"): filename = request.config.getoption("--custom-hw-map") else: filename = None map = import_hw_map(filename) if filename else None uri = request.config.getoption("--uri") if uri: try: ctx = iio.Context(uri) except TimeoutError: raise Exception("URI {} has no reachable context".format(uri)) devices = [] for dev in ctx.devices: name = dev.name if name: devices.append(name) devices = ",".join(devices) hw = request.config.getoption("--hw") or lookup_hw_from_map(ctx, map) if "uri" in ctx.attrs: uri_type = ctx.attrs["uri"].split(":")[0] else: uri_type = uri.split(":")[0] ctx_plus_hw = { "uri": uri, "type": uri_type, "devices": devices, "hw": hw, } if request.config.getoption("--scan-verbose"): print("\nHardware found at specified uri:", ctx_plus_hw["hw"]) return [ctx_plus_hw] return find_contexts(request.config, map)
def main(): ctx = iio.Context() print 'Library version: %u.%u (git tag: %s)' % iio.version print 'IIO context created: ' + ctx.name print 'Backend version: %u.%u (git tag: %s)' % ctx.version print 'Backend description string: ' + ctx.description 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: print '\t\t\t\t' + attr + ', value: ' + chn.attrs[attr].value if len(dev.attrs) != 0: print '\t\t%u device-specific attributes found:' % len(dev.attrs) for attr in dev.attrs: print '\t\t\t' + attr + ', value: ' + dev.attrs[attr].value if len(dev.debug_attrs) != 0: print '\t\t%u debug attributes found:' % len(dev.debug_attrs) for attr in dev.debug_attrs: print '\t\t\t' + attr + ', value: ' + dev.debug_attrs[attr].value
def test_ad7291(context_desc, voltage_raw, low, high): ctx = None for ctx_desc in context_desc: if ctx_desc["hw"] in hardware: ctx = iio.Context(ctx_desc["uri"]) if not ctx: pytest.skip("No valid hardware found") ad7291 = ctx.find_device("ad7291") for channel in ad7291.channels: c_name = "out" if channel.output else "in" c_name += "_" + str(channel.id) if c_name == voltage_raw: for attr in channel.attrs: if attr == "raw": try: print(channel.attrs[attr].value) assert low <= int(channel.attrs[attr].value) <= high except OSError: continue
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