Ejemplo n.º 1
0
    def init(self):
        if self.task_state == "":
            self.task = TaskHandle()
            DAQmxCreateTask(b"", byref(self.task))
            DAQmxCreateCITwoEdgeSepChan(
                self.task,
                "{}/{}".format(self.device_name, self.counter_chan).encode(),
                b"",
                float64(self.min_val),
                float64(self.max_val),
                DAQmx_Val_Seconds,
                self.first_edge_type,
                self.second_edge_type,
                b"",
            )
            if self.source_terminal:
                tmp_data = c_char_p(self.source_terminal.encode())
                DAQmxSetCITwoEdgeSepFirstTerm(
                    self.task,
                    "{}/{}".format(self.device_name,
                                   self.counter_chan).encode(),
                    tmp_data,
                )

            if self.destination_terminal:
                tmp_data = c_char_p(self.destination_terminal.encode())
                DAQmxSetCITwoEdgeSepSecondTerm(
                    self.task,
                    "{}/{}".format(self.device_name,
                                   self.counter_chan).encode(),
                    tmp_data,
                )
            self.task_state = "init"
Ejemplo n.º 2
0
 def init(self):
     if self.task_state == "":
         self.task = TaskHandle()
         DAQmxCreateTask(b"", byref(self.task))
         DAQmxCreateDOChan(self.task, self.task_string, b"",
                           DAQmx_Val_ChanPerLine)
         self.task_state = "init"
Ejemplo n.º 3
0
 def init(self):
     if self.task_state == "":
         self.task = TaskHandle()
         DAQmxCreateTask(b"", byref(self.task))
         DAQmxCreateDIChan(self.task, self.task_string, b"", DAQmx_Val_ChanPerLine)
         self.task_state = "init"
     if self.task_state in ["init", "stopped"]:
         self.start()
Ejemplo n.º 4
0
    def init(self):
        if self.task_state == "":
            self.task = TaskHandle()
            DAQmxCreateTask(b"", byref(self.task))
            DAQmxCreateCITwoEdgeSepChan(self.task, "{}/{}".format(self.device_name, self.counter_chan).encode(), b"",
                                        float64(self.min_val), float64(self.max_val), DAQmx_Val_Seconds,
                                        self.first_edge_type,
                                        self.second_edge_type, b"")
            if self.source_terminal:
                tmp_data = c_char_p(self.source_terminal.encode())
                DAQmxSetCITwoEdgeSepFirstTerm(self.task, "{}/{}".format(self.device_name, self.counter_chan).encode(),
                                              tmp_data)
                if self.validate_terminals:
                    tmp_data = c_char_p("".encode())
                    DAQmxGetCITwoEdgeSepFirstTerm(self.task,
                                                  "{}/{}".format(self.device_name, self.counter_chan).encode(),
                                                  tmp_data,
                                                  uInt32(16))
                    if self.destination_terminal not in tmp_data.value.decode('utf-8'):
                        raise InstrumentError(
                            "Destination terminal is set to {}, should be /{}/{}".format(tmp_data.value.decode('utf-8'),
                                                                                         self.device_name,
                                                                                         self.destination_terminal))

            if self.destination_terminal:
                tmp_data = c_char_p(self.destination_terminal.encode())
                DAQmxSetCITwoEdgeSepSecondTerm(self.task, "{}/{}".format(self.device_name, self.counter_chan).encode(),
                                               tmp_data)
                if self.validate_terminals:
                    tmp_data = c_char_p("".encode())
                    DAQmxGetCITwoEdgeSepSecondTerm(self.task,
                                                   "{}/{}".format(self.device_name, self.counter_chan).encode(),
                                                   tmp_data,
                                                   uInt32(16))
                    if self.destination_terminal not in tmp_data.value.decode('utf-8'):
                        raise InstrumentError(
                            "Destination terminal is set to {}, should be /{}/{}".format(tmp_data.value.decode('utf-8'),
                                                                                         self.device_name,
                                                                                         self.destination_terminal))
            self.task_state = "init"
Ejemplo n.º 5
0
    def serve(self):

        while True:
            now = datetime.datetime.now()
            print('sampling frequency          : {}'.format(self.samplingFreq))
            print('samples per channel         : {}'.format(
                self.numSampsPerChan))
            print('maximum number of segment   : {}'.format(
                self.maxSegmentNum))
            print('number of channels          : {}'.format(self.channelNum))

            dt = 1.0 / self.samplingFreq

            taskHandle = TaskHandle()

            try:
                # DAQmx Configure Code
                DAQmxCreateTask("", byref(taskHandle))

                def createChannel(devID, channelIDs):
                    try:
                        DAQmx_Val_dict = {
                            'DIFF': DAQmx_Val_Diff,
                            'RSE': DAQmx_Val_RSE,
                            'NRSE': DAQmx_Val_NRSE
                        }
                        device_and_channelsL = [
                            "Dev" + str(devID) + "/ai" + str(channelID)
                            for channelID in channelIDs
                        ]
                        device_and_channels = ", ".join(device_and_channelsL)
                        DAQmxCreateAIVoltageChan(
                            taskHandle, device_and_channels, "",
                            DAQmx_Val_dict[self.terminal_config], -10.0, 10.0,
                            DAQmx_Val_Volts, None)

                        print(
                            "at DAQmxCreateAIVoltageChan, created succesfully with channelNum = "
                            + str(self.channelNum) + ".")
                        return 1
                    except DAQError as err:
                        print("at DAQmxCreateAIVoltageChan, DAQmx Error: %s" %
                              err)
                        self.logFile.write(
                            "at DAQmxCreateAIVoltageChan, DAQmx Error: %s" %
                            err)
                        self.logFile.flush()
                        return 0

                for devID in [1, 2, 3, 4, 0]:
                    if createChannel(devID, self.channelIDs):
                        break

                # param: taskHandle
                # param: source (const char[])
                # param: samplingFreq : sapmling frequency (Hz)
                # param: activeEdge
                # param: sampleMode (int32) : DAQmx_Val_FiniteSamps
                #        or DAQmx_Val_ContSamps or DAQmx_Val_HWTimedSinglePoint
                # param: numSampsPerChan (int) : number of samples per channel
                DAQmxCfgSampClkTiming(
                    taskHandle,
                    "",
                    self.samplingFreq,
                    DAQmx_Val_Rising,
                    DAQmx_Val_ContSamps,
                    # DAQmx_Val_FiniteSamps,
                    self.numSampsPerChan * self.channelNum)
                # elf.numSampsPerChan)
                '''
                convRateFactor = 5
                new_convRate = float64(self.samplingFreq * self.channelNum * convRateFactor)
                DAQmxSetAIConvRate(taskHandle, new_convRate)
                convRate = float64()
                DAQmxGetAIConvRate(taskHandle, byref(convRate))
                # print('convRate =', convRate)
                '''

                # DAQmx Start Code
                DAQmxStartTask(taskHandle)
                # DAQmxSetReadOverWrite(taskHandle, DAQmx_Val_OverwriteUnreadSamps)

                for timestep in tqdm.tqdm(range(1, self.maxSegmentNum + 1)):
                    data = np.zeros((self.numSampsPerChan * self.channelNum, ),
                                    dtype=np.float64)
                    now = self.read_data(taskHandle, data)
                    # print('data.shape =', data.shape)

                    sampleNum = data.shape[0] // self.channelNum
                    if self.channelNum == 2:
                        eeg_data = data[:sampleNum]
                        ch2_data = data[sampleNum:]
                    else:
                        eeg_data = data[:sampleNum]

                    dataToClient = ''
                    for sampleID in range(sampleNum):
                        current_time = self.updateTimeStamp(now, sampleID, dt)
                        ftime = current_time.strftime('%H:%M:%S.')
                        ftime += '%06d' % current_time.microsecond

                        dataToClient += ftime + '\t' + str(eeg_data[sampleID])
                        if self.channelNum == 2:
                            dataToClient += '\t' + str(
                                ch2_data[sampleID]) + '\n'
                        else:
                            dataToClient += '\n'

                    # dataToClient = dataToClient.rstrip()
                    # print('in server, dataToClient.shape =', dataToClient.shape)
                    # print('in server, dataToClient =', dataToClient)
                    self.client.process(dataToClient)

                    # record log
                    presentTime = timeFormatting.presentTimeEscaped()
                    if self.recordWaves:
                        self.logFile.write(presentTime + ', ' +
                                           str(eeg_data.shape[0]) + ', ' +
                                           str(eeg_data) + '\n')
                    else:
                        self.logFile.write(presentTime + ', ' +
                                           str(eeg_data.shape[0]) + '\n')
                    self.logFile.flush()

            except DAQError as err:
                print("DAQmx Error: %s" % err)
                self.logFile.write("DAQmx Error: %s" % err)
                self.logFile.flush()

            finally:
                if taskHandle:
                    DAQmxStopTask(taskHandle)
                    DAQmxClearTask(taskHandle)