def _set_short_at(self, offset, value): max_offset = sizeof(self) - 2 if offset < 0 or offset > max_offset: raise ValueError addr = addressof(self) + offset value_string = struct.pack('<H', value) memmove(addr, value_string, 2)
def getPPyObjectPtr(pyobj): if not pyobj: return 0 return _ctypes.addressof(pyobj.contents)
def start_scan(self): # Set filename self.file_name = window.rec_settings.FolderLabel.text() + '/' + window.rec_settings.NamePrefixLabel.text() + \ datetime.datetime.now().strftime("_%Y_%m_%d_%H%M%S") + \ '.wav' try: # Start the scan ul.a_in_scan( self.board_num, self.low_chan, self.high_chan, self.ul_buffer_count, self.rate, self.ai_range, self.memhandle, self.scan_options) self.status = Status.IDLE # Wait for the scan to start fully while(self.status == Status.IDLE): self.status, _, _ = ul.get_status( self.board_num, FunctionType.AIFUNCTION) # Create a file for storing the data # PYSOUNDFILE MODULE temp_file = SoundFile(self.file_name, 'w+', self.rate, 1, 'PCM_16') # with SoundFile(self.file_name, 'w', self.rate, 1, 'PCM_16') as f: # print('abro', self.file_name) # WAVE MODULE # with wave.open('wavemod' + self.file_name, 'w') as f: # f.setnchannels(1) # f.setsampwidth(2) # f.setframerate(self.rate) # Start the write loop prev_count = 0 prev_index = 0 write_ch_num = self.low_chan while self.status != Status.IDLE: # Get the latest counts self.status, curr_count, _ = ul.get_status( self.board_num, FunctionType.AIFUNCTION) new_data_count = curr_count - prev_count # Check for a buffer overrun before copying the data, so # that no attempts are made to copy more than a full buffer # of data if new_data_count > self.ul_buffer_count: # Print an error and stop writing # QtGui.QMessageBox.information(self, "Error", "A buffer overrun occurred") ul.stop_background(self.board_num, FunctionType.AIFUNCTION) print("A buffer overrun occurred") # cambiar por critical message break # VER COMO REEMPLAZAR # Check if a chunk is available if new_data_count > self.write_chunk_size: self.wrote_chunk = True # Copy the current data to a new array # Check if the data wraps around the end of the UL # buffer. Multiple copy operations will be required. if prev_index + self.write_chunk_size > self.ul_buffer_count - 1: first_chunk_size = self.ul_buffer_count - prev_index second_chunk_size = ( self.write_chunk_size - first_chunk_size) # Copy the first chunk of data to the write_chunk_array ul.win_buf_to_array( self.memhandle, self.write_chunk_array, prev_index, first_chunk_size) # Create a pointer to the location in # write_chunk_array where we want to copy the # remaining data second_chunk_pointer = cast( addressof(self.write_chunk_array) + first_chunk_size * sizeof(c_ushort), POINTER(c_ushort)) # Copy the second chunk of data to the # write_chunk_array ul.win_buf_to_array( self.memhandle, second_chunk_pointer, 0, second_chunk_size) else: # Copy the data to the write_chunk_array ul.win_buf_to_array( self.memhandle, self.write_chunk_array, prev_index, self.write_chunk_size) # Check for a buffer overrun just after copying the data # from the UL buffer. This will ensure that the data was # not overwritten in the UL buffer before the copy was # completed. This should be done before writing to the # file, so that corrupt data does not end up in it. self.status, curr_count, _ = ul.get_status( self.board_num, FunctionType.AIFUNCTION) # Opcion 1: original ( valores altos ) if curr_count - prev_count > self.ul_buffer_count: # Print an error and stop writing ul.stop_background(self.board_num, FunctionType.AIFUNCTION) print("BUFFER OVERRUN") QtGui.QMessageBox.critical(self, "Warning", "A buffer overrun occurred") break # VER COMO HACER PARA EVITAR QUE CIERRE EL PROGRAMA: for i in range(self.write_chunk_size): # opcion 1 self.chunk_ls.append(self.write_chunk_array[i]-32768) # opcion 4 self.chunk_np = np.asarray(self.chunk_ls, dtype=np.int16) # resampled_chunk = samplerate.resample(self.chunk_np, 44100. / # float(self.rate), 'sinc_best') # resampled_chunk = resampy.resample(self.chunk_np, self.rate, 44100) temp_file.write(self.chunk_np) # self.chunk_signal.emit(self.chunk_ls) # self.file_ls.extend(self.chunk_ls) self.chunk_ls = [] else: self.wrote_chunk = False if self.wrote_chunk: self.chunk_signal.emit(self.chunk_np) # Increment prev_count by the chunk size prev_count += self.write_chunk_size # Increment prev_index by the chunk size prev_index += self.write_chunk_size # Wrap prev_index to the size of the UL buffer prev_index %= self.ul_buffer_count if prev_count % self.points_to_write == 0: # self.file_signal.emit(self.file_np) # self.write_wav_file(self.file_ls temp_file.close() self.file_name = window.rec_settings.FolderLabel.text() + '/' + window.rec_settings.NamePrefixLabel.text() + \ datetime.datetime.now().strftime("_%Y_%m_%d_%H%M%S") + \ '.wav' temp_file = SoundFile(self.file_name, 'w', self.rate, 1, 'PCM_16') else: # Wait a short amount of time for more data to be # acquired. time.sleep(0.1) except ULError as e: print('except') # QtGui.QMessageBox.critical(window, 'Error', 'Please restart program') self.print_ul_error(e) # VER FUNCION Y ADAPATAR A PYQT finally: # Free the buffer in a finally block to prevent errors from causing # a memory leak. temp_file.close() ul.stop_background(self.board_num, FunctionType.AIFUNCTION) ul.win_buf_free(self.memhandle) self.finished_signal.emit()
def _enum_handles(self, process_id=None): """Enumerates handle information. Enumerates handle info on the start of the kernel capture. Returns a dictionary of handle's information including the handle id, access mask, and the process which owns the handle. """ buff_size = MAX_BUFFER_SIZE size = c_ulong() # allocate the initial buffer buff = malloc(buff_size) handles = {} while True: status = zw_query_system_information( SYSTEM_HANDLE_INFORMATION_CLASS, buff, buff_size, byref(size)) if status == STATUS_INFO_LENGTH_MISMATCH: # the buffer is too small # increment the buffer size and try again buff_size += MAX_BUFFER_SIZE elif status == STATUS_SUCCESS: # cast the buffer to `SYSTEM_HANDLE_INFORMATION` struct # which contains an array of `SYSTEM_HANDLE` structures sys_handle_info = cast(buff, POINTER(SYSTEM_HANDLE_INFORMATION)) sys_handle_info = sys_handle_info.contents handle_count = sys_handle_info.number_of_handles # resize the array size to the # actual number of file handles sys_handles = (SYSTEM_HANDLE * buff_size).from_address( addressof(sys_handle_info.handles)) for i in range(handle_count): sys_handle = sys_handles[i] pid = sys_handle.process_id handle = sys_handle.handle obj = sys_handle.object obj_type_index = sys_handle.object_type_number access_mask = sys_handle.access_mask if process_id and process_id == pid: handles[obj] = ddict(pid=process_id, handle=handle, obj=obj, access_mask=access_mask, obj_type_index=obj_type_index) elif process_id is None: handles[obj] = ddict(pid=pid, handle=handle, obj=obj, access_mask=access_mask, obj_type_index=obj_type_index) break else: raise HandleEnumError(status) # reallocate the buffer buff = realloc(buff, buff_size) # free the buffer memory free(buff) return handles
def _enum_handles(self, process_id=None): """Enumerates handle information. Enumerates handle info on the start of the kernel capture. Returns a dictionary of handle's information including the handle id, access mask, and the process which owns the handle. """ buff_size = MAX_BUFFER_SIZE size = c_ulong() # allocate the initial buffer buff = malloc(buff_size) handles = {} while True: status = zw_query_system_information(SYSTEM_HANDLE_INFORMATION_CLASS, buff, buff_size, byref(size)) if status == STATUS_INFO_LENGTH_MISMATCH: # the buffer is too small # increment the buffer size and try again buff_size += MAX_BUFFER_SIZE elif status == STATUS_SUCCESS: # cast the buffer to `SYSTEM_HANDLE_INFORMATION` struct # which contains an array of `SYSTEM_HANDLE` structures sys_handle_info = cast(buff, POINTER(SYSTEM_HANDLE_INFORMATION)) sys_handle_info = sys_handle_info.contents handle_count = sys_handle_info.number_of_handles # resize the array size to the # actual number of file handles sys_handles = (SYSTEM_HANDLE * buff_size).from_address(addressof(sys_handle_info.handles)) for i in range(handle_count): sys_handle = sys_handles[i] pid = sys_handle.process_id handle = sys_handle.handle obj = sys_handle.object obj_type_index = sys_handle.object_type_number access_mask = sys_handle.access_mask if process_id and process_id == pid: handles[obj] = ddict(pid=process_id, handle=handle, obj=obj, access_mask=access_mask, obj_type_index=obj_type_index) elif process_id is None: handles[obj] = ddict(pid=pid, handle=handle, obj=obj, access_mask=access_mask, obj_type_index=obj_type_index) break else: raise HandleEnumError(status) # reallocate the buffer buff = realloc(buff, buff_size) # free the buffer memory free(buff) return handles
def run_example(): board_num = 0 rate = 100 file_name = 'scan_data.csv' # The size of the UL buffer to create, in seconds buffer_size_seconds = 2 # The number of buffers to write. After this number of UL buffers are # written to file, the example will be stopped. num_buffers_to_write = 5 if use_device_detection: ul.ignore_instacal() if not util.config_first_detected_device(board_num): print("Could not find device.") return ai_props = AnalogInputProps(board_num) if (ai_props.num_ai_chans < 1 or not ScanOptions.SCALEDATA in ai_props.supported_scan_options): util.print_unsupported_example(board_num) return low_chan = 0 high_chan = min(3, ai_props.num_ai_chans - 1) num_chans = high_chan - low_chan + 1 # Create a circular buffer that can hold buffer_size_seconds worth of # data, or at least 10 points (this may need to be adjusted to prevent # a buffer overrun) points_per_channel = max(rate * buffer_size_seconds, 10) # Some hardware requires that the total_count is an integer multiple # of the packet size. For this case, calculate a points_per_channel # that is equal to or just above the points_per_channel selected # which matches that requirement. if ai_props.continuous_requires_packet_size_multiple: packet_size = ai_props.packet_size remainder = points_per_channel % packet_size if remainder != 0: points_per_channel += packet_size - remainder ul_buffer_count = points_per_channel * num_chans # Write the UL buffer to the file num_buffers_to_write times. points_to_write = ul_buffer_count * num_buffers_to_write # When handling the buffer, we will read 1/10 of the buffer at a time write_chunk_size = int(ul_buffer_count / 10) ai_range = ai_props.available_ranges[0] scan_options = (ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS | ScanOptions.SCALEDATA) memhandle = ul.scaled_win_buf_alloc(ul_buffer_count) # Allocate an array of doubles temporary storage of the data write_chunk_array = (c_double * write_chunk_size)() # Check if the buffer was successfully allocated if not memhandle: print("Failed to allocate memory.") return try: # Start the scan ul.a_in_scan( board_num, low_chan, high_chan, ul_buffer_count, rate, ai_range, memhandle, scan_options) status = Status.IDLE # Wait for the scan to start fully while(status == Status.IDLE): status, _, _ = ul.get_status( board_num, FunctionType.AIFUNCTION) # Create a file for storing the data with open(file_name, 'w') as f: print('Writing data to ' + file_name, end='') # Write a header to the file for chan_num in range(low_chan, high_chan + 1): f.write('Channel ' + str(chan_num) + ',') f.write(u'\n') # Start the write loop prev_count = 0 prev_index = 0 write_ch_num = low_chan while status != Status.IDLE: # Get the latest counts status, curr_count, _ = ul.get_status( board_num, FunctionType.AIFUNCTION) new_data_count = curr_count - prev_count # Check for a buffer overrun before copying the data, so # that no attempts are made to copy more than a full buffer # of data if new_data_count > ul_buffer_count: # Print an error and stop writing ul.stop_background(board_num, FunctionType.AIFUNCTION) print("A buffer overrun occurred") break # Check if a chunk is available if new_data_count > write_chunk_size: wrote_chunk = True # Copy the current data to a new array # Check if the data wraps around the end of the UL # buffer. Multiple copy operations will be required. if prev_index + write_chunk_size > ul_buffer_count - 1: first_chunk_size = ul_buffer_count - prev_index second_chunk_size = ( write_chunk_size - first_chunk_size) # Copy the first chunk of data to the # write_chunk_array ul.scaled_win_buf_to_array( memhandle, write_chunk_array, prev_index, first_chunk_size) # Create a pointer to the location in # write_chunk_array where we want to copy the # remaining data second_chunk_pointer = cast( addressof(write_chunk_array) + first_chunk_size * sizeof(c_double), POINTER(c_double)) # Copy the second chunk of data to the # write_chunk_array ul.scaled_win_buf_to_array( memhandle, second_chunk_pointer, 0, second_chunk_size) else: # Copy the data to the write_chunk_array ul.scaled_win_buf_to_array( memhandle, write_chunk_array, prev_index, write_chunk_size) # Check for a buffer overrun just after copying the data # from the UL buffer. This will ensure that the data was # not overwritten in the UL buffer before the copy was # completed. This should be done before writing to the # file, so that corrupt data does not end up in it. status, curr_count, _ = ul.get_status( board_num, FunctionType.AIFUNCTION) if curr_count - prev_count > ul_buffer_count: # Print an error and stop writing ul.stop_background(board_num, FunctionType.AIFUNCTION) print("A buffer overrun occurred") break for i in range(write_chunk_size): f.write(str(write_chunk_array[i]) + ',') write_ch_num += 1 if write_ch_num == high_chan + 1: write_ch_num = low_chan f.write(u'\n') else: wrote_chunk = False if wrote_chunk: # Increment prev_count by the chunk size prev_count += write_chunk_size # Increment prev_index by the chunk size prev_index += write_chunk_size # Wrap prev_index to the size of the UL buffer prev_index %= ul_buffer_count if prev_count >= points_to_write: break print('.', end='') else: # Wait a short amount of time for more data to be # acquired. time.sleep(0.1) ul.stop_background(board_num, FunctionType.AIFUNCTION) except ULError as e: util.print_ul_error(e) finally: print('Done') # Free the buffer in a finally block to prevent errors from causing # a memory leak. ul.win_buf_free(memhandle) if use_device_detection: ul.release_daq_device(board_num)
def _readBG(self, file_name): # file_name = 'C:\\Users\\PVGroup\\Desktop\\frgmapper\\Data\\20190913\\test.data' # totalCount = len(self.channels['Number']) * self.__countsPerChannel # memhandle = ul.win_buf_alloc_64(totalCount) # ctypesArray = ctypes.cast(memhandle, ctypes.POINTER(ctypes.c_ulonglong)) # The size of the UL buffer to create, in seconds buffer_size_seconds = 2 # The number of buffers to write. After this number of UL buffers are # written to file, the example will be stopped. num_buffers_to_write = 2 low_chan = 0 high_chan = 1 num_chans = high_chan - low_chan + 1 # Create a circular buffer that can hold buffer_size_seconds worth of # data, or at least 10 points (this may need to be adjusted to prevent # a buffer overrun) points_per_channel = max(self.__rate * buffer_size_seconds, 10) # Some hardware requires that the total_count is an integer multiple # of the packet size. For this case, calculate a points_per_channel # that is equal to or just above the points_per_channel selected # which matches that requirement. # if ai_props.continuous_requires_packet_size_multiple: # packet_size = ai_props.packet_size # remainder = points_per_channel % packet_size # if remainder != 0: # points_per_channel += packet_size - remainder ul_buffer_count = points_per_channel * num_chans # Write the UL buffer to the file num_buffers_to_write times. points_to_write = ul_buffer_count * num_buffers_to_write # When handling the buffer, we will read 1/10 of the buffer at a time write_chunk_size = int(ul_buffer_count / 100) if self.useExtClock: scan_options = ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS | ScanOptions.SCALEDATA | ScanOptions.EXTCLOCK else: scan_options = ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS | ScanOptions.SCALEDATA memhandle = ul.scaled_win_buf_alloc(ul_buffer_count) # Allocate an array of doubles temporary storage of the data write_chunk_array = (c_double * write_chunk_size)() # Check if the buffer was successfully allocated if not memhandle: print("Failed to allocate memory.") return try: # Start the scan ul.daq_in_scan(board_num=self.board_num, chan_list=self.channels['Number'], chan_type_list=self.channels['Type'], gain_list=self.channels['Gain'], chan_count=len(self.channels['Number']), rate=self.__rate, pretrig_count=0, total_count=ul_buffer_count, memhandle=memhandle, options=scan_options) status = Status.IDLE # Wait for the scan to start fully while (status == Status.IDLE): status, _, _ = ul.get_status(board_num, FunctionType.DAQIFUNCTION) # Create a file for storing the data with open(file_name, 'w') as f: # print('Writing data to ' + file_name, end='') # Write a header to the file # for chan_num in range(low_chan, high_chan + 1): # f.write('Channel ' + str(chan_num) + ',') # f.write(u'\n') # Start the write loop prev_count = 0 prev_index = 0 write_ch_num = low_chan keepReading = True while status != Status.IDLE and keepReading: # Get the latest counts status, curr_count, _ = ul.get_status( board_num, FunctionType.DAQIFUNCTION) new_data_count = curr_count - prev_count # Check for a buffer overrun before copying the data, so # that no attempts are made to copy more than a full buffer # of data if new_data_count > ul_buffer_count: # Print an error and stop writing ul.stop_background(board_num, FunctionType.DAQIFUNCTION) print("A buffer overrun occurred") break # Check if a chunk is available if new_data_count > write_chunk_size: wrote_chunk = True # Copy the current data to a new array # Check if the data wraps around the end of the UL # buffer. Multiple copy operations will be required. if prev_index + write_chunk_size > ul_buffer_count - 1: first_chunk_size = ul_buffer_count - prev_index second_chunk_size = (write_chunk_size - first_chunk_size) # Copy the first chunk of data to the # write_chunk_array ul.scaled_win_buf_to_array(memhandle, write_chunk_array, prev_index, first_chunk_size) # Create a pointer to the location in # write_chunk_array where we want to copy the # remaining data second_chunk_pointer = cast( addressof(write_chunk_array) + first_chunk_size * sizeof(c_double), POINTER(c_double)) # Copy the second chunk of data to the # write_chunk_array ul.scaled_win_buf_to_array(memhandle, second_chunk_pointer, 0, second_chunk_size) else: # Copy the data to the write_chunk_array ul.scaled_win_buf_to_array(memhandle, write_chunk_array, prev_index, write_chunk_size) # Check for a buffer overrun just after copying the data # from the UL buffer. This will ensure that the data was # not overwritten in the UL buffer before the copy was # completed. This should be done before writing to the # file, so that corrupt data does not end up in it. status, curr_count, _ = ul.get_status( board_num, FunctionType.DAQIFUNCTION) if curr_count - prev_count > ul_buffer_count: # Print an error and stop writing ul.stop_background(board_num, FunctionType.DAQIFUNCTION) print("A buffer overrun occurred") break for i in range(write_chunk_size): f.write(str(write_chunk_array[i])) write_ch_num += 1 if write_ch_num == high_chan + 1: write_ch_num = low_chan f.write(u'\n') else: f.write(',') else: wrote_chunk = False if wrote_chunk: # Increment prev_count by the chunk size prev_count += write_chunk_size # Increment prev_index by the chunk size prev_index += write_chunk_size # Wrap prev_index to the size of the UL buffer prev_index %= ul_buffer_count if not self.acquiringBG: #make sure to wait until after writing to check if we should stop to avoid truncation keepReading = False # if prev_count >= points_to_write: # break # f.write('-----\n') # print('.', end='') else: # Wait a short amount of time for more data to be # acquired. time.sleep(0.01) ul.stop_background(board_num, FunctionType.DAQIFUNCTION) except ULError as e: pass finally: # print('Done') # Free the buffer in a finally block to prevent errors from causing # a memory leak. ul.win_buf_free(memhandle)