def read(handle, rx_length): """This function reads a response from the SHA204 device. One iteration in the response-ready polling loop takes 1 ms plus the time for one loop iteration.""" poll_interval = 1 # approx. 1 ms timeout = 1000 # approx. 1000 ms count = 0 data_in = None res = 1 while timeout > 0: (count, data_in) = aa_i2c_read(handle, I2C_ADDRESS, AA_I2C_NO_FLAGS, rx_length) if count > 0: # success break if count < 0: print "error: %s\n" % (aa_status_string(count)) return count if count == 0: aa_sleep_ms(poll_interval) timeout -= poll_interval continue if (count != rx_length): print "error: read %d bytes (expected %d)\n" % (count, rx_length) res = -1 break # Dump the data to the screen log_read(data_in, count) return res
def hw_i2c_read(self, length): myException = Exception() with self.activityLock : if self.handle == None : myException.message = "hw_i2c_read failure: attempting to read from null handle\n" raise myException # Call the appropriate I2C hardware interface to read data # (read with normal start and stop conditions) if self.HW_INTERFACE == config.AARDVARK: (count, data_in) = aardvark_py.aa_i2c_read(self.handle, self.DEVICE_I2C_ADDR, aardvark_py.AA_I2C_NO_FLAGS, length) if (count < 0): print "error: %s" % aa_status_string(count) return(count, data_in) elif self.HW_INTERFACE == config.FTDI: flags = ftdi.I2C_TRANSFER_OPTIONS_START_BIT|ftdi.I2C_TRANSFER_OPTIONS_STOP_BIT|ftdi.I2C_TRANSFER_OPTIONS_NACK_LAST_BYTE (count, data_in) = ftdi.ftdi_i2c_read(self.handle, self.DEVICE_I2C_ADDR, flags, length) return(count, data_in) elif self.HW_INTERFACE == config.USB_TO_ANY: myException.message = 'USB_TO_ANY hardware interface hw_interface_init not implemented\n' raise myException elif self.HW_INTERFACE == config.USB_EP: myException.message = 'hw_i2c_read USB_EP hardware interface hw_interface_init not implemented\n' raise myException else: myException.message = 'Invalid hardware interface selected in config.py\n' raise myException
def read(self, addr, length): """Reads an array of bytes from the addressed I2C device. Keyword arguments: addr -- I2C Slave Address (0x00 - 0x7F) length -- Number of bytes to receive """ (count, data) = api.aa_i2c_read(self._handle, addr, \ api.AA_I2C_NO_FLAGS, length) _check_result(count) return data.tostring()
def read_register(self, sensor, register, length=1): sad = self._sensortable[sensor] # todo check write status first aa.aa_i2c_write(self._handle, sad, aa.AA_I2C_NO_STOP, array('B', [register])) # write address (count, data_in) = aa.aa_i2c_read(self._handle, sad, aa.AA_I2C_NO_FLAGS, length) # read data if count != length: raise BusException( 'No response from I2C slave at address 0x%x for sensor %s' % (sad, sensor)) return data_in
def read_raw_command(command, Aardvark_in_use, logging = False): """ Function to read a <RAW> command from a slave device. @param[in] command: The command with the read information (string). @param[in] Aardvark_in_use: The Aaardvark to use to read the data (aardvark_py.aardvark). @param[in] logging: Is the data read going to be logged. If so, return the data (bool). @return (string) The data to be logged if logging parameter is True. """ # check if the command is valid if pySCPI_config.is_valid_raw(command): # it is valid so break the command into parts data_list = command.split(' ') # extract the length to read data_len = int(data_list[2][:-1]) # extract the address to read from raw_addr = int(data_list[1][:-1],16) # define the destination array data = array('B', [1]*data_len) # read the data read_data = aardvark_py.aa_i2c_read(Aardvark_in_use, raw_addr, aardvark_py.AA_I2C_NO_FLAGS, data) # convert date to a string data_string = ' '.join(['%02X' % x for x in list(read_data[1])]) # print the result print 'Raw Read:\t\t[' + data_string + '] from address ' + \ data_list[1][:-1] # if the data is to be logged retun the data in a string format if logging: return data_string
def read(self, address, offset, length): res = None while (not res): #zero byte write to set the read pointer aa_py.aa_i2c_write(self.aa, address, aa_py.AA_I2C_NO_FLAGS, array('B', [offset & 0xff]) ) (count, res) = aa_py.aa_i2c_read(self.aa, address, aa_py.AA_I2C_NO_FLAGS, length) if (count < 0): print "error: %s" % aa_py.aa_status_string(count) res = None elif (count == 0): print "error: no bytes read" print " are you sure you have the right slave address?" res = -999999999 elif (count != length): print "error: read %d bytes (expected %d)" % (count, length) res = -999999999 return res
def log_aardvark(directives, filename, gui): """ Write to the slave device using the Aardvark and print to the gui and save the data to a csv log file. @param[in] directives: Instructions to direct the sending of data (pySCPI_config.write_directives) @param[in] filename: The absolute directory of the file to write log to (string). @param[in] gui: Instance of the gui that this function is called by (pySCPI_gui.main_gui). @return int(0): Failed to use Aardvark. """ # unpack the write directives addr = directives.addr commands = directives.command_list Delay = directives.delay_time Ascii_delay = directives.ascii_time logging_p = directives.logging_p # configure the progress bar to be the correct length gui.progress.config(maximum = logging_p*10) # increment the progress bar every 100 ms gui.progress.start(100) # set up the csv writing output csv_output = open(filename, 'wb') output_writer = csv.writer(csv_output, delimiter = '\t') # create the header for the csv file csv_line = create_csv_header(commands, gui) # write the header output_writer.writerow(csv_line) # configure Aardvark if available Aardvark_in_use = configure_aardvark() # Check to see if an Aardvark was actually found if Aardvark_in_use != None: # start the loop timer start_time = time.time() # loop until the thread is asked to exit while not gui.terminator.kill_event.isSet(): # define variables for the row csv_row = [] dec_addr = addr first_timestamp = '' # iterate through commands and add them to the aardvark file command_count = 0 # commands that start with # are deemed comments for command in commands: # skip comments that start with # if command.startswith('#'): command_count += 1 continue # end if gui.highlight_line(command_count) # determine if the command is a configuration command if pySCPI_config.is_config(command): # configure the system based on the config command dec_addr = update_aardvark(command, dec_addr, Aardvark_in_use) else: # Prepare the data for transmission if pySCPI_config.is_raw_write(command): # it is a raw write command to send that send_raw_command(command, Aardvark_in_use) elif pySCPI_config.is_raw_read(command): # it is a rew read command so read the data and # add it to the csv row csv_row.append(read_raw_command(command, Aardvark_in_use, logging = True)) else: # it is a normal command send_scpi_command(command, Aardvark_in_use, dec_addr) # end if # end if if 'TEL?' in command: # the command is telemetry so log that # is it an ascii command if command.endswith('ascii'): # perform as ascii dealy aardvark_py.aa_sleep_ms(Ascii_delay) else: # perform a regular intermessage delay aardvark_py.aa_sleep_ms(Delay) # end if # define array to read data into data = array('B', [1]*pySCPI_formatting.read_length(command, gui)) # read from the slave device read_data = aardvark_py.aa_i2c_read(Aardvark_in_use, dec_addr, aardvark_py.AA_I2C_NO_FLAGS, data) # print data pySCPI_formatting.print_read(command, list(read_data[1]), gui) # log data pySCPI_formatting.log_read(command, list(read_data[1]), csv_row, gui) # end if # print a blank line print '' # intermessage delay aardvark_py.aa_sleep_ms(Delay) # check to see if logging needs to stop if gui.terminator.kill_event.isSet(): # End if a stop has been issued break # end if command_count += 1 # end while # get the earliest timestamp from the row first_timestamp = csv_row[0] # check to see if it is actually a timestamp if type(first_timestamp) == float: # it is a timestamp so convert it to a byte array of # the elapsed time in hundredths of a second timestamp_list = [ord(x) for x in '[1:' + str(int(first_timestamp*100)) + ']'] # convert the byte list to an ascii time timestamp_string = pySCPI_formatting.get_ascii_time(timestamp_list) # insert this timestamp at the beginning of the row csv_row.insert(0,timestamp_string) else: # the first entry is not a timestamp so leave it blank csv_row.insert(0,'-') # end if # write the row to the log file output_writer.writerow(csv_row) # unhighlight the last row gui.highlight_line() # pace the loop to the correct logging period while (time.time() - start_time) < logging_p: # sleep to prevent resource hogging time.sleep(0.1) # check to see if logging should end if gui.terminator.kill_event.isSet(): # it should so exit break # end if # end while start_time = time.time() # check to see if we can clear the gui for the next period if not gui.terminator.root_destroyed: # clear the output display on the GUI gui.output_clear() # end if gui.progress.config(value = 0) # end while gui.progress.stop() # close the csv file csv_output.close() # unhighlight the last row gui.highlight_line() # close the aardvark aardvark_py.aa_close(Aardvark_in_use) print 'Aardvark logging finished' else: # no aardvark connection was established return 0
def write_aardvark(directives, gui): """ Write to the slave device using the Aardvark and print its results to the GUI. @param[in] directives: Instructions to direct the sending of data (pySCPI_config.write_directives) @param[in] gui: Instance of the gui that this function is called by (pySCPI_gui.main_gui). @return int(0): Failed to use Aardvark. None Otherwise. """ # local copy of the write directives dec_addr = directives.addr commands = directives.command_list Delay = directives.delay_time Ascii_delay = directives.ascii_time # configure the progress bar gui.progress.config(maximum = len([c for c in commands if not c.startswith('#')])) # configure Aardvark if available Aardvark_in_use = configure_aardvark() # Check to see if an Aardvark was actually found if Aardvark_in_use != None: # iterate through commands and add them to the aardvark file command_count = 0 for command in commands: # ignore comment lines that start with a # if command.startswith('#'): command_count +=1 continue # end if # find the line of execution and highlight it gui.highlight_line(command_count) # determine if the command is a configuration command if pySCPI_config.is_config(command): # configure the system based on the config command dec_addr = update_aardvark(command, dec_addr, Aardvark_in_use) else: # Prepare the data for transmission if pySCPI_config.is_raw_write(command): # it is a raw write command to send that send_raw_command(command, Aardvark_in_use) elif pySCPI_config.is_raw_read(command): # it is a rew read command so read the data read_raw_command(command, Aardvark_in_use) else: # it is a normal command send_scpi_command(command, Aardvark_in_use, dec_addr) # end if # end if if 'TEL?' in command: # an I2C read has been requested # delay before reading the data if command.endswith('ascii'): # sleep a different amount if ascii was requested aardvark_py.aa_sleep_ms(Ascii_delay) else: aardvark_py.aa_sleep_ms(Delay) # end if # define array to read data into data = array('B', [1]*pySCPI_formatting.read_length(command, gui)) # read from the slave device read_data = aardvark_py.aa_i2c_read(Aardvark_in_use, dec_addr, aardvark_py.AA_I2C_NO_FLAGS, data) # print the recieved data pySCPI_formatting.print_read(command, list(read_data[1]), gui) # end if # end if # print an empty line print '' # intermessage delay aardvark_py.aa_sleep_ms(Delay) if gui.terminator.kill_event.isSet(): # this thread has been asked to terminate break # end # increment the progress bar gui.progress.step() # increment the command counter command_count += 1 # end for # unhighlight the last row gui.highlight_line() # close the AArdvark device aardvark_py.aa_close(Aardvark_in_use) print 'Aardvark communications finished' else: return 0
def read_SCPI(self, command, address, return_format): """ Function to send a SCPI command to the slave device @param[in] command: the command to send (string) @param[in] address: the decimal address to write to (int) @param[out] result: the variable to store the data in """ # dictionary of acceptible data formats and their lengths acceptible_formats = {'int':2, 'long':4, 'long long':8, 'uint':2, 'double':8, 'float':4, 'char':1, 'schar':1, 'hex':1, 'name':self.name_size, 'ascii':self.ascii_size, 'string':self.ascii_size} # length of preamle preamble_length = self.wflag_size + self.time_size + self.chksum_size # define the read legth as 0 read_length = 0 # continuation flag perform_read = True # determin the correct read length if type(return_format) == list: # retun type is a list of items so it has a preamble read_length += preamble_length # add up all of the lengths of the list items for item in return_format: # ensure each format specifier is acceptible if item in acceptible_formats: read_length += acceptible_formats[item] else: # error self.message = '***'+ item + \ " is an unacceptible format ***" perform_read = False break # end if # end for elif return_format in acceptible_formats: # return type is an acceptible format # add preamble to data length if required if return_format == 'ascii': read_length = acceptible_formats['ascii'] else: read_length = preamble_length + acceptible_formats[return_format] # end if else: # format is not acceptible self.message = '***'+ return_format + " is an unacceptible format ***" perform_read = False # end if if perform_read: self.send_SCPI(command, address) # define array to read data into data = array('B', [1]*read_length) # read from the slave device read_data = aardvark_py.aa_i2c_read(self.port, int(address, 16), aardvark_py.AA_I2C_NO_FLAGS, data) # convert data to alist raw_data = list(read_data[1]) # check the write flag if raw_data[0] == 0: # the write flag indicates a failed transmission return None # end if # pause aardvark_py.aa_sleep_ms(100) # extract the data from the returned raw data if type(return_format) == list: # there are multiple items in the return list return_list = [] # remove the preamble data = raw_data[preamble_length:] for item in return_format: # extract each item individually and append to list return_list = return_list + \ [_extract_data(data[0:acceptible_formats[item]], item)] # shorten data list to what remains data = data[acceptible_formats[item]:] # end for return return_list else: # extract the sole peice of data if return_format != 'ascii': data = raw_data[preamble_length:] # end if return _extract_data(data, return_format) #end if # end if # if you make it this far there was a problem with the format strings return None