def strip_quotes(input_str): lib.debug_print("strip_quotes") lib.debug_print(input_str) if input_str.startswith('"') and input_str.endswith('"'): input_str = input_str[1:-1] return input_str
def upload_file(self, file_path, addr=None): #uploads a file from the host to the client project directory on the remote machines try: if addr: self.ssh.connect(addr, username=self.username, password=self.password) sftp = self.ssh.open_sftp() client_path = '%s/%s' % (self.client_dir, file_path) sftp.put(file_path, client_path) debug_print("%s: transferred - %s" % (addr, file_path)) self.ssh.close() sftp.close() else: for ip in self.ip_list: self.ssh.connect(ip, username=self.username, password=self.password) sftp = self.ssh.open_sftp() client_path = '%s/%s' % (self.client_dir, file_path) sftp.put(file_path, client_path) debug_print("%s: transferred - %s" % (ip, file_path)) self.ssh.close() sftp.close() except Exception as e: print('Error in upload_file: ' + str(e))
def CycleReadADC_quick(self, sel_list): debug_print('CycleReadADC (quickly (without chip select and release))') """ Technique based on page 21, Figure 19 of the ADS1256 datasheet t_11 = 4*tau_CLKIN for RREG, WREG, and ret_data = 521 ns t_11 = 24*tau_CLKIN for SYNC = 3.13 us """ data = np.zeros( len(sel_list), dtype='int32') #create an array to hold the sample vars #self.ChipSelect() self.SetInputMux_quick(sel_list[0][0], sel_list[0][1]) for i in range(1, len(sel_list)): self.WaitDRDY() self.SetInputMux_quick(sel_list[i][0], sel_list[i][1]) self.__delayMicroseconds(1) self.SyncAndWakeup_quick() self.__delayMicroseconds(1) data[i - 1] = self.ReadADC_quick() self.WaitDRDY() data[i] = self.ReadADC_quick() self.ChipRelease() return data
def SyncAndWakeup_quick(self): debug_print('sync+wakeup (quickly (no chip select or release))') #self.ChipSelect() self.__SendBytes(bytearray((self.CMD_SYNC, ))) self.__delayMicroseconds(4) self.__SendBytes(bytearray((self.CMD_WAKEUP, )))
def WriteReg(self, start_register, data): """ Writes data to the register, implements: WREG: Write to Register Description: Write to the registers starting with the register specified as part of the command. The number of registers that will be written is one plus the value of the second byte in the command. 1st Command Byte: 0101 rrrr where rrrr is the address to the first register to be written. 2nd Command Byte: 0000 nnnn where nnnn is the number of bytes-1 to be written TODO: Implement multiple register write """ debug_print("WriteReg") self.ChipSelect() byte1 = self.CMD_WREG | start_register # Tell the ADS chip which register to start writing at byte2 = 0x00 # Tell the ADS chip how many additional registers to write byte3 = data # Send the data self.__SendBytes(bytearray((byte1, byte2, byte3))) self.ChipRelease()
def ReadReg(self, start_reg, num_to_read): """" Read the provided register, implements: RREG: Read from Registers Description: Output the data from up to 11 registers starting with the register address specified as part of the command. The number of registers read will be one plus the second byte of the command. If the count exceeds the remaining registers, the addresses will wrap back to the beginning. 1st Command Byte: 0001 rrrr where rrrr is the address of the first register to read. 2nd Command Byte: 0000 nnnn where nnnn is the number of bytes to read -1. See the Timing Characteristics for the required delay between the end of the RREG command and the beginning of shifting data on DOUT: t6. """ debug_print("ReadReg") self.ChipSelect() self.__SendBytes( bytearray((self.CMD_RREG | start_reg, 0x00 | num_to_read - 1))) self.DataDelay() read = self.__SendBytes(bytearray(num_to_read * (0x00, ))) self.ChipRelease() return read
def Boot(self): debug_print('Boot') self.ChipSelect() result = self.__SendBytes( bytearray([self.WRITE_MASK | self.REG_CTRL_REG2] + [0x90])) self.ChipRelease() return (result)
def ReadRegisters(self): """ Read all the registers from the LPS chip and displays them on the screen :returns: bytes read from the SPI transfer """ debug_print("ReadRegisters") byte1 = self.READ_MASK | self.REG_INTERRUPT_CFG byte2 = self.DUMMY_BYTE self.ChipSelect() result = self.__SendBytes(bytearray([byte1] + 41 * [byte2])) self.ChipRelease() index = 0x0A skip_registers = [0x0A, 0x0E, 0x13] + list(range(0x1B, 0x25)) + list( range(0x2D, 0x33)) for reg in result: if index not in skip_registers: print(' ' + format(index, '02X') + ': ' + format(reg, '08b') + ' = ' + format(reg, '02x'), end='') if index == 0x0B: print(' <----INTERRUPT_CFG') elif index == 0x0F: print(' <--WHO_AM_I') elif index == 0x10: print(' <----CTRL_REG1') elif index == 0x28: print(' <--PRESS_OUT_XL') elif index == 0x29: print(' <--PRESS_OUT_L') elif index == 0x2A: print(' <--PRESS_OUT_H') elif index == 0x2B: print(' <--TEMP_OUT_L') elif index == 0x2C: print(' <--TEMP_OUT_H') else: print('') index += 1 print(index) return result
def SetGPIOoutputs(self, D0, D1, D2, D3): """ Set the states of the ADS1256's GPIO pins """ debug_print('set GPIO outputs') IObits = D3 * 0x8 + D2 * 0x4 + D1 * 0x2 + D0 * 0x1 self.WriteReg(self.REG_IO, IObits)
def SyncAndWakeup(self): debug_print('sync+wakeup') self.ChipSelect() self.__SendBytes(bytearray((self.CMD_SYNC, ))) self.__delayMicroseconds(4) self.__SendBytes(bytearray((self.CMD_WAKEUP, ))) self.ChipRelease() self.__delayMicroseconds(4)
def authorize_user(user_id): """ Adds user_id to login_session to be used by user_is_authorized_to_update_item for authorization checks :param user_id: user id :return: None """ lib.debug_print("authorizing user") lib.debug_print(user_id) login_session["authorized_user_id"] = user_id
def SetInputMux_quick(self, possel, negsel): debug_print( 'setting mux position (quickly (no chip select or release))') #self.ChipSelect() byte1 = self.CMD_WREG | 0x01 byte2 = 0x00 byte3 = (possel << 4) | (negsel << 0) self.__SendBytes(bytearray((byte1, byte2, byte3)))
def getADCsample(self, a_pos, a_neg): """ Gets a sample from the ADC NOTE: this is configured to switch devices that all use the common ground """ debug_print('getADCSample') # This is very slow - chip select and release on all three steps self.SetInputMux(a_pos, a_neg) self.SyncAndWakeup() return self.ReadADC()
def __SendBytes(self, myBytearray): temp = '' for c in myBytearray: temp += '\\x%02x' % c debug_print('Sending bytes: ' + temp) result = wp.wiringPiSPIDataRW(self.SPI_CHANNEL, bytes(myBytearray)) temp = '' for c in result[1]: temp += '\\x%02x' % c debug_print('Result: ' + temp) return result[1]
def SendDACBValue(self, newValue): "Send DAC B a new value between 0 and 2^16-1" debug_print('Send DAC B: ' + str(int(newValue)).rjust(16)) self.__ChipSelect( ) #only needed if not using CE0 or CE1, but doesn't hurt otherwise byte1 = ((self.LOAD_DACB | self.BUFFERSELECT_B) >> 16) & 0xFF byte2 = (int(newValue) >> 8) & 0xFF byte3 = (int(newValue)) & 0xFF self.__SendBytes(bytearray((byte1, byte2, byte3))) self.__ChipRelease( ) #only needed if not using CE0 or CE1, but doesn't hurt otherwise
def SetInputMux(self, possel, negsel): debug_print('setting mux position') self.ChipSelect() byte1 = self.CMD_WREG | 0x01 byte2 = 0x00 byte3 = (possel << 4) | (negsel << 0) self.__SendBytes(bytearray((byte1, byte2, byte3))) self.ChipRelease()
def ReadTemp(self): debug_print('ReadTemp') self.ChipSelect() result = self.__SendBytes( bytearray([self.READ_MASK | self.REG_TEMP_OUT_L] + 2 * [self.DUMMY_BYTE])) self.ChipRelease() temp_c = (256 * float(result[2]) + float(result[1])) / 100 temp_f = 9 * temp_c / 5 + 32 debug_print('temperature in celcius: ' + str(temp_c) + ', temperature in farenheit: ' + str(temp_f)) return (temp_c)
def ReadID(self): """ Read the ID from the ADS chip :returns: numeric identifier of the ADS chip """ debug_print('ReadID') self.WaitDRDY() idInBytes = self.ReadReg(self.REG_STATUS, 1) myid = idInBytes[0] >> 4 debug_print("myid = " + str(myid)) return (myid)
def PowerDownDACB(self): "Powers down DAC B to high impedance" debug_print('Powering down DAC B') self.__ChipSelect( ) #only needed if not using CE0 or CE1, but doesn't hurt otherwise byte1 = (( (self.LOAD_DACB | self.BUFFERSELECT_B | self.PD1 | self.PD0) >> 16) & 0xFF) byte2 = (0 & 0xFF) byte3 = (0 & 0xFF) self.__SendBytes(bytearray((byte1, byte2, byte3))) self.__ChipRelease( ) #only needed if not using CE0 or CE1, but doesn't hurt otherwise
def user_is_authorized_to_update_item(user_id_to_check): """ Function checks if user in current session is allowed to update an item associated with a user_id_to_check :param user_id_to_check: id associated with the item (for example, user_id field of an ad) :return: True if user should be allowed to update the item, False otherwise """ if "authorized_user_id" in login_session: if int(user_id_to_check) == int(login_session["authorized_user_id"]): lib.debug_print("authorized") return True lib.debug_print("not authorized") return False
def ReadPress(self): debug_print('ReadPress') self.ChipSelect() result = self.__SendBytes( bytearray([self.READ_MASK | self.REG_PRESS_OUT_XL] + 3 * [self.DUMMY_BYTE])) self.ChipRelease() press_hPa = (256 * 256 * float(result[3]) + 256 * float(result[2]) + float(result[1])) / 4096 press_atm = .000987 * press_hPa debug_print('pressure in hPa: ' + str(press_hPa) + ', pressure in atmospheres: ' + str(press_atm)) return (press_hPa)
def read_dataset(self, logfile, dset_name): # returns a dataset, must specify logfile and full path to dataset. Ex: read_dataset('20170614.hdf5','/20170614_120400/collector 1') debug_print('read_dataset started') try: with h5py.File('%s/%s' % (self.logdirname, logfile)) as f: dset = f[dset_name] data = np.array(dset) attributes = {} for key in dset.attrs.keys(): attributes[key] = dset.attrs[key] return data, attributes except: print(dset_name, ' not found.\n')
def ReadID(self): """ Read the ID from the LPS chip :returns: numeric identifier of the LPS chip """ debug_print("ReadID") self.ChipSelect() byte1 = self.READ_MASK | self.REG_WHO_AM_I byte2 = self.DUMMY_BYTE result = self.__SendBytes(bytearray((byte1, byte2))) self.ChipRelease() myid = hex((result[1])) debug_print("myid = " + myid) return (myid)
def identifpi(self): #get serial number for each pi, tie to ip address debug_print('identifpi started') ip_serial = bidict.bidict() for ip in self.ip_list: self.ssh.connect(ip, username=self.username, password=self.password) command = "cat /proc/cpuinfo | grep Serial | cut -d ' ' -f 2" stdin, stdout, stderr = self.ssh.exec_command(command) ip_serial[ip] = stdout.read().decode().replace('\n', '') self.ssh.close() debug_print('ip_serial: {}'.format(ip_serial)) return ip_serial
def DataDelay(self): """ Delay from last SCLK edge for DIN to first SCLK rising edge for DOUT Datasheet states that the delay between requesting data and reading the bus must be minimum 50x CLKIN period. """ debug_print("DataDelay") start = time.time() elapsed = time.time() - start # Wait for TIMEOUT to elapse while elapsed < self.DATA_DELAY: elapsed = time.time() - start
def ConfigADC(self): debug_print("configuring ADC") self.ChipSelect() byte1 = self.CMD_WREG | 0x00 # start write at addr 0x00 byte2 = self.REG_DRATE # end write at addr REG_DRATE byte3 = self.STATUS_AUTOCAL_ENABLE + self.STATUS_BUFFER_ENABLE byte4 = 0x08 # input channel parameters byte5 = self.AD_GAIN_2 # ADCON control register, gain byte6 = self.DRATE_500 # data rate self.__SendBytes(bytearray((byte1, byte2, byte3, byte4, byte5, byte6))) self.ChipRelease() self.DataDelay()
def get_page_info(): """ :return: dictionary of standard page info items for page nav bar """ page_info = dict() page_info["user_logged_in"] = False page_info["left_text"] = "S-classifieds" page_info["right_text"] = "" lib.debug_print("get_page_info") lib.debug_print(flask_login.current_user.get_id()) # first need to check if user is set to AnonymousUserMixin object if flask_login.current_user.get_id(): if flask_login.current_user.is_authenticated(): page_info["user_logged_in"] = True page_info[ "right_text"] = "Logged in as " + flask_login.current_user.email return page_info
def WaitDRDY(self): """ Delays until DRDY line goes low, allowing for automatic calibration """ start = time.time() elapsed = time.time() - start # Waits for DRDY to go to zero or TIMEOUT seconds to pass drdy_level = wp.digitalRead(self.DRDY_PIN) while (drdy_level == wp.HIGH) and (elapsed < self.DRDY_TIMEOUT): elapsed = time.time() - start drdy_level = wp.digitalRead(self.DRDY_PIN) if elapsed >= self.DRDY_TIMEOUT: debug_print("WaitDRDY() Timeout\n") return (1) else: return (0)
def kill_processes(self, client_file): #takes a dictionary of form: ip:PID and iterates through it, killing each PID debug_print('kill_processes started') killed = {} try: for ip in self.ip_list: self.ssh.connect(ip, username=self.username, password=self.password) stdin, stdout, stderr = self.ssh.exec_command( 'pgrep -f "python3 -u %s"' % (client_file)) pids = stdout.read().decode() for pid in pids.split('\n'): if pid != '': self.ssh.exec_command('sudo kill %s' % pid) print('%s: killed "%s"' % (ip, pid)) self.ssh.close() except Exception as e: print('Error in kill_processes: ' + str(e))
def ReadPressAndTemp(self): debug_print('ReadPressAndTemp') # perform one shot to get new data # note: chip release and select needed between commands self.OneShot() self.ChipSelect() # read status, pressure, and temperature registers byte1 = self.READ_MASK | self.REG_STATUS byte2 = self.DUMMY_BYTE result = self.__SendBytes(bytearray([byte1] + 6 * [byte2])) # analyze status register if result[1] & 0x03 != 0x03: print('Invalid data') # return converted values temp_c = (256 * float(result[6]) + float(result[5])) / 100 press_hPa = (256 * 256 * float(result[4]) + 256 * float(result[3]) + float(result[2])) / 4096 self.ChipRelease() return (press_hPa, temp_c)