def getChannels(self): """ returns 2 lists of all valid bank names for the given channel returns 'b0r1', 'b0engage' style names """ prefix_bank_A = "b" + str(self.channel * 2) prefix_bank_B = "b" + str((self.channel * 2) + 1) with niswitch.Session(self.device, topology=self.topology) as session_matrix: channel_names = [] for i in range(1, 99999): try: channel_names.append(session_matrix.get_channel_name(i)) except niswitch.errors.Error as e: break b0 = [ col for col in channel_names if col.startswith(prefix_bank_A) ] b1 = [ row for row in channel_names if row.startswith(prefix_bank_B) ] log.debug(b0) log.debug(b1) return (b0, b1)
def test_continuous_software_scanning(session): with niswitch.Session('', '2532/1-Wire 4x128 Matrix', True, False) as session: scan_list = 'r0->c0; r1->c1' session.scan_list = scan_list assert session.scan_list == scan_list session.route_scan_advanced_output( niswitch.ScanAdvancedOutput.FRONTCONNECTOR, niswitch.ScanAdvancedOutput.NONE) session.route_trigger_input(niswitch.TriggerInput.FRONTCONNECTOR, niswitch.TriggerInput.TTL0) session.configure_scan_list(scan_list, niswitch.ScanMode.BREAK_BEFORE_MAKE) session.configure_scan_trigger(niswitch.TriggerInput.SOFTWARE_TRIG, niswitch.ScanAdvancedOutput.NONE) session.set_continuous_scan(True) session.commit() with session.initiate(): assert session.is_scanning is True session.send_software_trigger() try: session.wait_for_scan_complete() assert False except niswitch.Error as e: assert e.code == -1074126826 # Error : Max time exceeded.
def example(resource_name, topology, simulate, relay, action): # if we are simulating resource name must be blank resource_name = '' if simulate else resource_name with niswitch.Session(resource_name=resource_name, topology=topology, simulate=simulate) as session: session.relay_control(relay_name=relay, relay_action=niswitch.RelayAction[action]) print('Relay ', relay, ' has had the action ', action, ' performed.')
def session_2532(): with daqmx_sim_db_lock: simulated_session = niswitch.Session('', '2532/1-Wire 4x128 Matrix', True, False) yield simulated_session with daqmx_sim_db_lock: simulated_session.close()
def test_error_message(): try: # We pass in an invalid model name to force going to error_message with niswitch.Session('', 'Invalid Topology', True, True): assert False except niswitch.Error as e: assert e.code == -1074118654 assert e.description.find('Invalid resource name.') != -1
def connect(self, row, col): """ if connection already there leave, otherwise make it. """ with niswitch.Session(self.device, topology=self.topology) as session_matrix: if (not session_matrix.can_connect(channel1=row, channel2=col) == niswitch.PathCapability.PATH_EXISTS): log.debug("connecting %s->%s" % (row, col)) session_matrix.connect(channel1=row, channel2=col)
def setResistance(self, resistance_ohms): """ Set the resistance """ self.clearWholeChannel() with niswitch.Session(self.device, topology=self.topology) as ni_session: for a, b in self.get_banks_to_close_by_name(resistance_ohms): log.debug('closing %s %s' % (a, b)) ni_session.connect(a, b)
def disconnect(self, row, col): """ analagous to connect() if connection not there leave, otherwise disconnect. """ with niswitch.Session(self.device, topology=self.topology) as session_matrix: if (session_matrix.can_connect( channel1=row, channel2=col) == niswitch.PathCapability.PATH_EXISTS): log.debug("disconnecting %s->%s" % (row, col)) session_matrix.disconnect(channel1=row, channel2=col)
def example(resource_name, channel1, channel2, topology, simulate): # if we are simulating resource name must be blank resource_name = '' if simulate else resource_name with niswitch.Session(resource_name=resource_name, topology=topology, simulate=simulate) as session: session.connect(channel1=channel1, channel2=channel2) print('Channel ', channel1, ' and ', channel2, ' are now connected.') session.disconnect(channel1=channel1, channel2=channel2) print('Channel ', channel1, ' and ', channel2, ' are now disconnected.')
def getConnections(self, row_slice=(0, None), col_slice=(0, None)): """ returns a pandas DataFrame (it's a matrix w/ names) of the current status of all possible connections. Matrix is populate with niswitch.PathCapability.value so one can do a comparison like: niswitch.PathCapability.PATH_EXISTS.value == getConnections()['c1']['r1'] to search through only a subset one can use row_slice and col_slice it's a bit tricky to get right. on my 8x64 matrix getConnections(row_slice=(2,3)) will yield c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ... c60 c61 c62 c63 r2 1 1 1 1 1 1 1 1 2 1 ... 1 1 1 1 where as getConnections(row_slice=(2,3),col_slice=(60,None)) yields c60 c61 c62 c63 r2 1 1 1 1 of course you can always just get the whole thing and slice after: # print(getConnections()[:'r0']) >>> c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ... c60 c61 c62 c63 r0 1 1 1 1 2 1 1 1 1 1 ... 1 1 1 1 for c in sm.getConnections()[:'r0'].iteritems(): print(c) # print(getConnections()['c62']) """ # create an empty numpy matrix with the expected size mat = np.zeros(shape=(len(self.rows[row_slice[0]:row_slice[1]]), len(self.cols[col_slice[0]:col_slice[1]])), dtype='int32') # convert it to a pandas DataFrame connections = pd.DataFrame( mat, columns=self.cols[col_slice[0]:col_slice[1]], index=self.rows[row_slice[0]:row_slice[1]], dtype=object) # get the current state of everything requested with niswitch.Session(self.device, topology=self.topology) as session_matrix: for r in self.rows[row_slice[0]:row_slice[1]]: for c in self.cols[col_slice[0]:col_slice[1]]: state = session_matrix.can_connect(r, c) connections[c][r] = state.value return connections
def __init__(self, options): # connections stores the connected ports for each chan/antenna # combination. During connect call connection is checked for an # appropriate key. If there is no such key the next channel of the # current port switch is used. # To get a working setup self.connections = {} device = get_modinst_device("NI-SWITCH", options.get("name", "")) # pylint: disable=import-outside-toplevel # disable import warning. We do not want to make niswitch a mandatory # package for users who do not use this class import niswitch self.session = niswitch.Session(device.device_name) self.port = options.get("port", "comA")
def clearCol(self, col): """ clear all connections on col. example input for col is 'c60' """ # e.g. 'c1' -> 1 col_as_val = int(''.join(filter(str.isdigit, col))) col_connections = self.getConnections(col_slice=(col_as_val, col_as_val + 1)) for row in self.rows: if niswitch.PathCapability.PATH_EXISTS.value == col_connections[ col][row]: with niswitch.Session( self.device, topology=self.topology) as session_matrix: log.debug("disconnecting %s->%s" % (row, col)) session_matrix.disconnect(channel1=row, channel2=col)
def initialize_sessions(tsm: SMContext): """ open sessions for all switch instrument channels that are defined in the pinmap associated with the tsm context Args: tsm (SMContext): TestStand semiconductor module context """ switch_name = "" instrument_names, channel_group_ids = get_all_instruments_names(tsm) for name, channel_id in zip(instrument_names, channel_group_ids): if name != switch_name: switch_name = name topology = name_to_topology(name) handle = niswitch.Session(name, topology) set_sessions(tsm, name, handle, channel_id)
def clearRow(self, row): """ clear all connections on row. example input for row is 'r1' """ # e.g. 'r1' -> 1, 'r11' -> 11 row_as_val = int(''.join(filter(str.isdigit, row))) row_connections = self.getConnections(row_slice=(row_as_val, row_as_val + 1)) for col in self.cols: if niswitch.PathCapability.PATH_EXISTS.value == row_connections[ col][row]: with niswitch.Session( self.device, topology=self.topology) as session_matrix: log.debug("disconnecting %s->%s" % (row, col)) session_matrix.disconnect(channel1=row, channel2=col)
def getChannels(self): """ returns 2 lists of all valid (columns, rows) returns 'r1', 'c1' style names """ with niswitch.Session(self.device, topology=self.topology) as session_matrix: channel_names = [] for i in range(1, 99999): try: channel_names.append(session_matrix.get_channel_name(i)) except niswitch.errors.Error as e: break columns = [col for col in channel_names if col.startswith('c')] rows = [row for row in channel_names if row.startswith('r')] return (columns, rows)
def example(resource_name, topology, simulate, device, channel, relay): # if we are simulating resource name must be blank resource_name = '' if simulate else resource_name with niswitch.Session(resource_name=resource_name, topology=topology, simulate=simulate) as session: if device: print('Device Info:') row_format = '{:<18}' * (2) print( row_format.format('Device Name: ', session.io_resource_descriptor)) print(row_format.format('Device Model: ', session.instrument_model)) print( row_format.format('Driver Revision: ', session.specific_driver_revision)) print(row_format.format('Channel count: ', session.channel_count)) print(row_format.format('Relay count: ', session.number_of_relays)) if channel: print('Channel Info:') row_format = '{:6}' + ' ' * 12 + '{:<15}{:<22}{:6}' print( row_format.format('Number', 'Name', 'Is Configuration', 'Is Source')) for i in range(1, session.channel_count + 1): channel_name = session.get_channel_name(index=i) channel = session.channels[channel_name] print( row_format.format(i, channel_name, str(channel.is_configuration_channel), str(channel.is_source_channel))) if relay: print('Relay Info:') row_format = '{:6}' + ' ' * 12 + '{:<15}{:<22}{:6}' print(row_format.format('Number', 'Name', 'Position', 'Count')) for i in range(1, session.number_of_relays + 1): relay_name = session.get_relay_name(index=i) print( row_format.format( i, relay_name, session.get_relay_position(relay_name=relay_name), session.get_relay_count(relay_name=relay_name)))
def clearWholeChannel(self): """ check all possible connections and disconnect if needed """ with niswitch.Session(self.device, topology=self.topology) as ni_session: def checkAndDisconnect(a, b): state = ni_session.can_connect(a, b) if niswitch.PathCapability.PATH_EXISTS.value == state.value: log.debug('disconnecting: %s %s' % (a, b)) ni_session.disconnect(a, b) for n in self.bank_a[1:]: checkAndDisconnect(self.bank_a[0], n) for n in self.bank_b[1:]: checkAndDisconnect(self.bank_b[0], n) checkAndDisconnect(self.bank_a[0], self.bank_b[0])
def test_enum_attribute(): with niswitch.Session('', '2532/1-Wire 4x128 Matrix', True, False) as session: assert session.scan_mode == niswitch.ScanMode.BREAK_BEFORE_MAKE
def __initialize_new_session(self): # Open session to device try: if self._session is not None: self._session.close() if self._new_device is True: selected_topology = "Configured Topology" else: selected_topology = self.topology_value.GetStringSelection() self._session = niswitch.Session( resource_name=self.device_value.GetStringSelection(), topology=selected_topology, reset_device=True) # noqa: E501 # Add total channels on device to combo-box channels = self._session.channel_count self.channel_1_value.Clear() self.channel_2_value.Clear() for channel in range(channels): self.channel_1_value.Append( self._session.get_channel_name(channel + 1)) # noqa: E501 self.channel_2_value.Append( self._session.get_channel_name(channel + 1)) # noqa: E501 # Add total relays on device to combo-box relays = self._session.channel_count self.relay_name_value.Clear() for relay in range(relays): self.relay_name_value.Append( self._session.get_relay_name(relay + 1)) # noqa: E501 if self._new_device is True: # Read all topologies from file topology_list = [] for name, member in niswitch_topologies.__members__.items(): topology_list.append(member.value) # Read device model from driver device_model_list = self._session.instrument_model.split("-") if len(device_model_list) > 1: device_model = device_model_list[1] else: device_model = "Not Found" # Populate the combo-box with device topologies from the topology_list # noqa: E501 self.topology_value.Clear() self.topology_value.Append("Configured Topology") for key in topology_list: match = key.find(device_model) if match != -1: self.topology_value.Append(key) self.topology_value.SetSelection(0) # Set selection to first item in the lists self.relay_name_value.SetSelection(0) self.channel_1_value.SetSelection(0) self.channel_2_value.SetSelection(0) self._new_device = False self.__update_status() # Catch error except niswitch.Error as e: self._session = None self._error = True self.status.SetLabel(str(e)) self.status.Wrap(350)
def session(): with niswitch.Session('', '2737/2-Wire 4x64 Matrix', True, True) as simulated_session: yield simulated_session
def disconnect_all(self): with niswitch.Session(self.device, topology=self.topology) as session_matrix: log.debug("disconnecting all") session_matrix.disconnect_all()
def reset(self): # reset switch matrix with niswitch.Session(self.device, topology=self.topology, reset_device=True) as session_matrix: log.debug("resetting niswitch")
#!/usr/bin/python import argparse import niswitch parser = argparse.ArgumentParser( description='Performs relay control with NI-SWITCH relays.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--name', default='PXI1Slot2', help='Resource name of a National Instruments Switch.') parser.add_argument('-r', '--relay', default='k0', type=str, help='Relay Name.') parser.add_argument('-a', '--action', default='OPEN_RELAY', choices=niswitch.RelayAction.__members__.keys(), type=str.upper, help='Relay Action.') args = parser.parse_args() with niswitch.Session(args.name) as session: session.relay_control(args.relay, niswitch.RelayAction[args.action]) print('Relay ', args.relay, ' has had the action ', args.action, ' performed.')