Ejemplo n.º 1
0
 def read(self):
     self.init()
     data_arr = numpy.zeros(self.io_length, uInt8)
     samples_per_chan = int32()
     num_bytes_per_sample = int32()
     DAQmxReadDigitalLines(self.task,
                           1,  # Samples per channel
                           2.0,  # Timeout
                           DAQmx_Val_GroupByScanNumber,  # Interleaved
                           data_arr,
                           len(data_arr),
                           byref(samples_per_chan),
                           byref(num_bytes_per_sample),
                           None)
     return data_arr
Ejemplo n.º 2
0
 def read(self):
     read = int32()
     self.ReadAnalogF64(self._samps_per_chan_to_acquire, -1,
                        DAQmx_Val_GroupByChannel, self._data,
                        self._data.size, byref(read), None)
     self.StopTask()
     return np.mean(self._data, axis=1)
Ejemplo n.º 3
0
    def read_data(self, taskHandle, data):
        """ read data points
        # Params
        - taskHandle (taskHandle type)
        - numSampsPerChan (int) : number of samples per channel
        - timeout (float) : time out in sec
        - fillMode: DAQmx_Val_GroupByChannel or DAQmx_Val_GroupByScanNumber
        - data (np.ndarray): array for writing out output
        - arraySizeInSamps : the size of the readArray array
        - byref(int32()) : the number of samples that were succesfully read out
        - reserved
        """
        try:
            DAQmxReadAnalogF64(taskHandle, self.numSampsPerChan, self.timeout,
                               DAQmx_Val_GroupByChannel, data,
                               self.numSampsPerChan * self.channelNum,
                               byref(int32()), None)

        except:
            import sys
            traceback = sys.exc_info()[2]
            pdb.post_mortem(traceback)

        current_time = datetime.datetime.now()
        return current_time
Ejemplo n.º 4
0
    def __init__(self,
                 device,
                 adqTime,
                 adqFreq,
                 list_channels,
                 rang_channels,
                 mode='FiniteSamps',
                 trigger=None,
                 terminalConfig='diff'):
        """This will configure the DAQ and Task for the specified configuration"""
        self.device = device
        self.adqTime = adqTime  # In seconds
        self.adqFreq = adqFreq
        self.list_channels = list_channels
        self.rang_channels = rang_channels
        self.mode = mode
        self.N_samples = int(adqTime * adqFreq)
        self.N_channels = len(list_channels)
        if terminalConfig is 'diff':
            self.terminalConfig = DAQmx_Val_Diff
        elif terminalConfig is 'SE':
            self.terminalConfig = DAQmx_Val_RSE
        else:
            raise Error(
                'Terminal configuration "{}" not known'.format(terminalConfig))
        print('I will adquire {} samples for each {} channels'.format(
            self.N_samples, self.N_channels))
        # DAQmx Configure Code
        # We create a Task instance
        self.ai = Task()
        # Prepare the type of variable that it returns using the library ctypes that work with C-functions
        self.read = int32()
        # The vector data will contain the output of the DAQ card in a single vector with the data from different channels
        # in a single 1-D vector with the data concatenated
        self.data = np.zeros((self.N_samples * self.N_channels, ),
                             dtype=np.float64)
        #self.ai = Task()
        # This prepares the string that is needed for the ``CreateAIVoltageChan`` depending on the number of channels to
        # read
        for channel, Vrange in zip(self.list_channels, self.rang_channels):
            str_channels = r"{}/ai{:d}".format(self.device, channel)
            #print(r"{}/ai{:d}".format(self.device,channel) )
            self.ai.CreateAIVoltageChan(str_channels, "", self.terminalConfig,
                                        -1.0 * Vrange, Vrange, DAQmx_Val_Volts,
                                        None)

        if mode is 'FiniteSamps':
            self.ai.CfgSampClkTiming("", self.adqFreq, DAQmx_Val_Rising,
                                     DAQmx_Val_FiniteSamps, self.N_samples)
        elif mode is 'ContSamps':
            self.ai.CfgSampClkTiming("", self.adqFreq, DAQmx_Val_Rising,
                                     DAQmx_Val_ContSamps, self.N_samples)
        else:
            raise Error('Mode not known')
        if trigger is None:
            pass
        else:
            self.ai.CfgAnlgEdgeStartTrig(
                r"{}/ai{:d}".format(self.device, trigger[0]),
                DAQmx_Val_RisingSlope, trigger[1])
Ejemplo n.º 5
0
 def read(self):
     n = self.sampleNumber
     data = numpy.zeros((n, self.numberOfChannel), dtype=numpy.float64)
     read = int32()
     self.ReadAnalogF64(n, 10.0, PyDAQmx.DAQmx_Val_GroupByScanNumber, data,
                        n * self.numberOfChannel, byref(read), None)
     return data
Ejemplo n.º 6
0
    def write(self, data):
        """
        The task should be in stopped state when calling write, it automatically starts the task through the
        DAQmxWriteDigitalLines call. When write is finished it is back in a stopped state
        :param data:
        :return:
        """
        self.init()
        try:
            if len(data) % self.io_length:
                raise ValueError("data must be a length divisible by {}".format(self.io_length))
        except TypeError as e:
            raise ValueError("data must be in an list divisible by {}".format(self.io_length)) from e
        if len(data) == self.io_length:
            # Sample clock only works for more than one sample so duplicate the sample
            data = list(data)
            data.extend(data)

        DAQmxCfgSampClkTiming(self.task, None, float64(self.frequency), DAQmx_Val_Rising, DAQmx_Val_FiniteSamps,
                              uInt64(int(len(data) // self.io_length)))

        try:
            data_arr = numpy.zeros((len(data)), uInt8)
            data_arr[:] = data

            written = int32()
            DAQmxWriteDigitalLines(self.task, int(len(data) // self.io_length), 1, -1,
                                   DAQmx_Val_GroupByScanNumber, data_arr, written, None)
            self.task_state = "running"
            DAQmxWaitUntilTaskDone(self.task, -1)
            if written.value != len(data) // self.io_length:
                raise InstrumentError("Values not written correctly")
        finally:
            self.stop()
Ejemplo n.º 7
0
    def write(self, data):
        """
        Data must be an iterable like a list of 1s and 0s
        Data is grouped by scan number. Each element in the array will write to each line in the digital output until
        exhausted and then will start from the beginning for the next sample. Sample rate is as set in creating the IO
        task.
        """
        self.init()
        try:
            if len(data) % self.io_length:
                raise ValueError("data must be a length divisible by {}".format(self.io_length))
            data_arr = numpy.zeros(len(data), uInt8)
            data_arr[:] = data
        except TypeError:
            if self.io_length != 1:
                raise ValueError("data must be a list of length divisible by {}".format(self.io_length))
            data_arr = numpy.zeros(1, uInt8)
            data_arr[:] = [data]

        written = int32()
        DAQmxWriteDigitalLines(self.task,
                               len(data_arr) // self.io_length,  # Samples per channel
                               1,  # Autostart task
                               2.0,  # Timeout
                               DAQmx_Val_GroupByScanNumber,  # Interleaved
                               data_arr, written, None)
Ejemplo n.º 8
0
    def read(self,name = None):
        if name is None:
            name = self.physicalChannel[0]
        taskHandle = self.taskHandles[name]                    
        DAQmxStartTask(taskHandle)
        data = numpy.zeros((1,), dtype=numpy.float64)
#        data = AI_data_type()
        read = int32()
        DAQmxReadAnalogF64(taskHandle,1,10.0,DAQmx_Val_GroupByChannel,data,1,byref(read),None)
        DAQmxStopTask(taskHandle)
        return data[0]
    def read(self, val, name=None):
        ''' Start an analog read task for a previously configured physical channel. '''
        if name is None:
            name = self.physical_channel[0]
        task_handle = self.task_handles[name]
        #DAQmxStartTask(task_handle)

        data = np.zeros((1, ), dtype=np.float64)
        read = int32()
        DAQmxReadAnalogF64(task_handle, 1, 10.0, DAQmx_Val_GroupByChannel,
                           data, 1, byref(read), None)
        return data[0]
Ejemplo n.º 10
0
 def read(self, name=None):
     if name is None:
         name = self.physicalChannel[0]
     taskHandle = self.taskHandles[name]
     DAQmxStartTask(taskHandle)
     data = numpy.zeros((1, ), dtype=numpy.float64)
     #        data = AI_data_type()
     read = int32()
     DAQmxReadAnalogF64(taskHandle, 1, 10.0, DAQmx_Val_GroupByChannel, data,
                        1, byref(read), None)
     DAQmxStopTask(taskHandle)
     return data[0]
    def read_counter(self, name, num_samples=1, timeout_sec=1800):
        ''' Read out the digital counters. 
            A timeout of -1 means infinite wait
        '''

        if name is None:
            name = self.physical_channel[0]
        task_handle = self.task_handles[name]

        data = np.zeros((num_samples, ), dtype=np.uint32)
        read_samples = int32()
        try:
            DAQmxReadCounterU32(task_handle, num_samples, timeout_sec, data,
                                num_samples, byref(read_samples), None)
        except:
            print('Num samples expected: {}, actual: {}'.format(
                num_samples, read_samples.value))
            sys.stderr(traceback.format_exc())

        return data
Ejemplo n.º 12
0
    def readEnvData(self):
        print("started readEnvData \n"
              )  # commenting this out stops the program from working. why?
        dataForTable = zeros(
            self.numOfChannels + 1, dtype=float64
        )  # this will hold the data to update the table with. (+1 to include the time channel)
        # setup NI card-related parameters
        dataNI = zeros(
            (self.numOfNIChannels, ), dtype=float64
        )  # this will hold the data gathered in a single measurement. -1 because we don't record the time.
        timeOut = 10  # 10s timeout limit?
        read = int32()  # the type of data read is 32int?
        session = requests.Session()
        session.trust_env = False
        while self.isRunning == True:
            # retrieve the data from the MSC box (which is saved after the data from the NI card)
            # setup MCS box-related parameters
            res = session.get(
                'http://tritium-remotemcs/cgi-bin/volt.cgi'
            )  # we also get something if we replace "volt" with "temp", but I don't get the values there
            content = str(
                res.content,
                "windows-1252")  # get the whole HTML code for that page
            content = content[
                419:]  # delete some bullshit before the first value
            content = content.replace(
                "</td><td>", ","
            )  # separate the values with commas instead of with bullshit
            content = content.replace(
                "</td></tr></table><br><table border=1><colgroup width=200 span=4></colgroup><tr><td><b>channel 5</b>,<b>channel 6</b>,<b>channel 7</b>,<b>channel 8</b></td></tr><tr><td>",
                ",")  # remove bullshit
            content = content[:-22]  # get rid of some last bullshit
            content = content.split(",")
            dataMCS = [int(i, 16) for i in content
                       ]  # convert the data from hexadecimal to decimal format
            # (note that there are 8 values here but we only save the first 4 cause we don't know what the other 4 are for)            # retrieve data from NI card's channels.
            # see http://zone.ni.com/reference/en-XX/help/370471AE-01/daqmxcfunc/daqmxreadanalogf64/
            try:
                DAQmxReadAnalogF64(self.taskHandle, 1, timeOut, 0, dataNI,
                                   self.numOfNIChannels, byref(read), None)
            except DAQError as err:
                self.printError(
                    "execution of DAQmxReadAnalogF64 failed. Maybe THe-Monitor is running? If so \"Pause\" it and try again."
                )
                self.pauseMeasurement()
            else:  # this is only executed if no DAQError was raised during execution of the code in the "try:" block
                # self.checkForWarnings(dataNI) # check if some of the values are suspicious and should be reported
                timestamp = round(time())  # the time in units of s
                # save the flow data
                self.previousHeFlowMeterValue = self.currentHeFlowMeterValue
                self.previousN2FlowMeterValue = self.currentN2FlowMeterValue
                self.currentHeFlowMeterValue = dataNI[
                    self.HE_FLOW_METER_CHANNEL_INDEX]
                self.currentN2FlowMeterValue = dataNI[
                    self.N2_FLOW_METER_CHANNEL_INDEX]
                self.currentDataTimeStamp = timestamp

                # get MKS flow data#
                #resultMKSflow = self.clientMKSflow.read_input_registers(0x0001, 2)
                #i1MKSflow = resultMKSflow.registers[0]
                #i2MKSflow = resultMKSflow.registers[1]
                #dataMKSflow = struct.unpack('l',struct.pack('<HH',i1MKSflow,i2MKSflow))[0]/10000
                dataMKSflow = 0
                # merge the data from the NI card and from the MCS box
                data = []
                for blah in dataNI:
                    data.append(blah)
                for j in range(self.numOfMCSChannels):
                    data.append(dataMCS[j])
                data.append(dataMKSflow)
                # data = append(dataNI,dataMCS)
                # data = append(data,dataMKSflow)
                dataForTable[0] = timestamp
                for j in range(self.numOfChannels):
                    dataForTable[j + 1] = data[
                        j]  # +1 to skip [0] which holds the time channel
                dataPrecisionFormat = "{0:." + str(self.DATA_PRECISION) + "f}"
                writeMeIntoFile = str(timestamp) + "\t" + "\t".join([
                    dataPrecisionFormat.format(data[j])
                    for j in range(self.numOfChannels)
                ]) + "\n"
                # writeMeIntoFile = str(timestamp)+"\t" + "\t".join([str(data[j]) for j in range(self.numOfNIChannels-1+self.numOfMCSChannels)]) +"\n"
                #   (note that we save up to DATA_PRECISION=4 digits after the decimal point instead of 6 like in the original program)
                self.comDataRecording.signalNewData.emit(
                    dataForTable, writeMeIntoFile
                )  # emit a signal in order to trigger updatePyEnvFileAndGUI
                # (see http://stackoverflow.com/questions/7127075/what-exactly-the-pythons-file-flush-is-doing )
                sleep(
                    self.MEASUREMENT_PERIOD_s - 0.1
                )  # read at a higher rate than the card's to make sure the buffer is cleared
Ejemplo n.º 13
0
 def read(self):
     n = self.sampleNumber
     data = numpy.zeros((n,self.numberOfChannel), dtype=numpy.float64)
     read = int32()
     self.ReadAnalogF64(n,10.0,PyDAQmx.DAQmx_Val_GroupByScanNumber,data,n*self.numberOfChannel,byref(read),None)
     return data