def humidity_temp_set(self): """Sends command to read humidity. Then reads humidity with a pause between the two bytes. Temperature then reads as a temp reading is taken by the sensor for compensation for humidity reading """ # Reading values for humidity with SMBusWrapper(1) as bus: # Write command to start reading humidity self.humidity_write = i2c_msg.write(self.address, [self.humidityCommand]) # Read command to actually read humidity self.humidity_read = i2c_msg.read(self.address, 2) # Execute with a pause bus.i2c_rdwr(self.humidity_write) time.sleep(0.25) bus.i2c_rdwr(self.humidity_read) #Reading values for temperature with SMBusWrapper(1) as bus: # Write command to start reading temperature self.temp_write = i2c_msg.write(self.address, [self.tempCommand]) # Read command to actually read temperature self.temp_read = i2c_msg.read(self.address, 2) # Execute bus.i2c_rdwr(self.temp_write) bus.i2c_rdwr(self.temp_read)
def setRange(self, RangeValue): """ Use to set a short, medium or long distance range mode. Default behaviour is automatic switching, with a loss in accuracy while changing. For some applications, fixed range mode might be more useful. Here, first automatic changes are disabled, then a specific range is locked in. Use 0x00, 0x03 or 0x07 for short, medium or long range. """ self.RangeValue = RangeValue while RangeValue not in {0x00, 0x03, 0x07}: print("Use 0x00, 0x03 or 0x07 for short, medium or long range.") return self.AddReg = i2c_msg.write(self.address, self.RegDetPattern) self._setReg = i2c_msg.write(self.address, [0x01]) """deactivate automatic range switching""" print("Set range mode to fixed.") with SMBus(self.I2Cbus) as bus: bus.i2c_rdwr(self.AddReg, self.SetReg) print("Set range distance.") self.AddReg2 = i2c_msg.write(self.address, self.RegDetRange) self.SetReg2 = i2c_msg.write(self.address, [self.RangeValue]) """ set fixed range """ with SMBus(self.I2Cbus) as bus: bus.i2c_rdwr(self.AddReg2, self.SetReg2) time.sleep(0.01) return
def write_read(self, addr, size, value, bus): if bus == False: value = wrap(value, 2) for x in range(len(value)): value[x] = int(value[x], 16) write = i2c_msg.write(int(addr, 16), value) read = i2c_msg.read(int(addr, 16), int(size, 10)) bus0.i2c_rdwr(write, read) dat = list(read) for x in range(len(dat)): dat[x] = hex(dat[x]) print(dat) elif bus == True: value = wrap(value, 2) for x in range(len(value)): value[x] = int(value[x], 16) write = i2c_msg.write(int(addr, 16), value) read = i2c_msg.read(int(addr, 16), int(size, 10)) bus1.i2c_rdwr(write, read) dat = list(read) for x in range(len(dat)): dat[x] = hex(dat[x]) print(dat) return dat
def i2c_read_transaction(handle, reg, data_len): reg_msb = (reg & 0xff00) >> 8 reg_lsb = (reg & 0xff) header = [reg_msb, reg_lsb] #print(data_out) try: with SMBus(handle) as bus: read = i2c_msg.read(DEV_ADDR, data_len) bus.i2c_rdwr(i2c_msg.write(DEV_ADDR, header), read) except IOError: print("[IOError]read again") retry = 1 while retry: try: with SMBus(handle) as bus: read = i2c_msg.read(DEV_ADDR, data_len) bus.i2c_rdwr(i2c_msg.write(DEV_ADDR, header), read) break except IOError: print("retry ", (2 - retry)) time.sleep(5) retry -= 1 data_in = list(read) if data_in[0] != calc_checksum(data_in[1:]): print("readback data doesn't meet the checksum value") return data_in
def handle_write(data): if len(data) < 14: logging.error("Got incorrect write request, length < 14 bytes") return None addr = int.from_bytes(data[12:14], byteorder='big') length = int.from_bytes(data[8:12], byteorder='big') if (length == 0): # Client might not implement length correctly and leave # it empty length = len(data) - 14 _safeload = data[1] # TODO: use this #if addr == SigmaTCPHandler.dsp.KILLCORE_REGISTER and not(SigmaTCPHandler.updating): #logging.debug( #"write to KILLCORE seen, guessing something is updating the DSP") #SigmaTCPHandler.prepare_update() print("writing {} bytes to {:04X}".format(length, addr)) memdata = data[14:] #print(addr) #print(memdata) #mw = i2c_msg.write(0x38, [(addr >> 8) & 0xFF, addr & 0xFF ] + list(memdata)) #mr = i2c_msg.read(0x38, length) #print('mw = {}'.format(list(mw))) print( 'LEN memdata = {} |||||||| '.format(len(list(memdata))) ) #len(list(mw))) ) with SMBus(5) as bus: #if len(list(memdata)) <= 4094: i = 0 n = len(memdata) + 2 block_size = 4094 mw = i2c_msg.write(0x38, [(addr >> 8) & 0xFF, addr & 0xFF ] + list(memdata[0:block_size])) print( 'LEN MW = {} |||||||| '.format(len(list(mw))) ) bus.i2c_rdwr(mw) i += block_size while i < n: mw = i2c_msg.write(0x38, [((addr+i) >> 8) & 0xFF, (addr+i) & 0xFF ] + list(memdata[i:i+block_size])) print( 'LEN MW = {} |||||||| '.format(len(list(mw))) ) bus.i2c_rdwr(mw) i += block_size #bus.i2c_rdwr(mw) res = 0 #SigmaTCPHandler.spi.write(addr, memdata) #if addr == SigmaTCPHandler.dsp.HIBERNATE_REGISTER and \ #SigmaTCPHandler.updating and memdata == b'\00\00': #logging.debug( #"set HIBERNATE to 0 seen, guessing update is done") #SigmaTCPHandler.finish_update() return res
def _setRegister(self, register, setvalue): """ helper function """ self.register = register self.setvalue = setvalue self.AddReg = i2c_msg.write(self.address, self.register) self.SetReg = i2c_msg.write(self.address, [setvalue]) with SMBus(self.I2Cbus) as bus: bus.i2c_rdwr(self.AddReg, self.SetReg) time.sleep(0.01) return
def smbus_i2c_write(self, address, reg, data_p, length, addrsize=8): ret_val = 0 data = [] for index in range(length): data.append(data_p[index]) if addrsize == 8: msg_w = i2c_msg.write(address, [reg] + data) elif addrsize == 16: msg_w = i2c_msg.write(address, [reg >> 8, reg & 0xff] + data) else: raise Exception("address must be 8 or 16 bits long only") self.i2c.i2c_rdwr(msg_w) return ret_val
def send_pid(p, i, d): with SMBus(i2c_bus) as bus: if p != None: #bus.write_block_data(address, 0, bytes(set_kp(p))) msg = i2c_msg.write(address, set_kp(p)) bus.i2c_rdwr(msg) if i != None: msg = i2c_msg.write(address, set_ki(i)) bus.i2c_rdwr(msg) if d != None: msg = i2c_msg.write(address, set_kd(d)) bus.i2c_rdwr(msg)
def send_limits(pwm, max, min): print(pwm) with SMBus(i2c_bus) as bus: if pwm != None: msg = i2c_msg.write(address, limit_pwm(pwm)) bus.i2c_rdwr(msg) if max != None: msg = i2c_msg.write(address, limit_target_max(max)) bus.i2c_rdwr(msg) if min != None: msg = i2c_msg.write(address, limit_target_min(min)) bus.i2c_rdwr(msg)
def write(self, addr, value, bus): value = wrap(value, 2) if bus == False: for x in range(len(value)): value[x] = int(value[x], 16) write = i2c_msg.write(int(addr, 16), value) bus0.i2c_rdwr(write) elif bus == True: for x in range(len(value)): value[x] = int(value[x], 16) write = i2c_msg.write(int(addr, 16), value) bus1.i2c_rdwr(write) return value[0]
def _getResponseLength(timeout: int): PN532_NACK = [0, 0, 0xFF, 0xFF, 0, 0] timer = 0 while 1: msg = i2c_msg.read(PN532_I2C_ADDRESS, 6) _wire.i2c_rdwr(msg) data = list(msg) DMSG('_getResponseLength length frame: {!r}'.format(data)) if data[0] & 0x1: # check first byte --- status break # PN532 is ready time.sleep(.0005) # sleep 0.5 ms timer += 1 if ((0 != timeout) and (timer > timeout)): return -1 if (PN532_PREAMBLE != data[1] or # PREAMBLE PN532_STARTCODE1 != data[2] or # STARTCODE1 PN532_STARTCODE2 != data[3] # STARTCODE2 ): DMSG('Invalid Length frame: {}'.format(data)) return PN532_INVALID_FRAME length = data[4] DMSG('_getResponseLength length is {:d}'.format(length)) # request for last respond msg again DMSG('_getResponseLength writing nack: {!r}'.format(PN532_NACK)) msg = i2c_msg.write(PN532_I2C_ADDRESS, PN532_NACK) _wire.i2c_rdwr(msg) return length
def writeCommand(header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0xFF) + 1) # checksum of length data_out.append(PN532_HOSTTOPN532) dsum = PN532_HOSTTOPN532 + sum(header) + sum(body) # sum of TFI + DATA data_out += list(header) data_out += list(body) checksum = ((~dsum & 0xFF) + 1) & 0xFF # checksum of TFI + DATA data_out += [checksum, PN532_POSTAMBLE] DMSG("writeCommand: {} {} {}".format(header, body, data_out)) # send data msg = i2c_msg.write(PN532_I2C_ADDRESS, list(tuple(data_out))) _wire.i2c_rdwr(msg) return _readAckFrame()
def read_block(self, start_block, count, bs=32): """ Reads multiple registers starting at a given block. :param start_block: The starting block :param count: THe amount of registers to read :param bs: Standard block size of 32 bits :return: None """ start_block = start_block * 4 data = [] # We'll add our read results to here # If read count is not divisible by block size, # we'll have one partial read at the last read full_reads, remainder = divmod(count, bs) if remainder: full_reads += 1 # adding that last read if needed for i in range(full_reads): start = i * bs + start_block # next block address hb, lb = start >> 8, start & 0xff # into high and low byte write = i2c_msg.write(self.address, [hb, lb]) # If we're on last cycle and remainder != 0, not doing a full read count = remainder if (remainder and i == full_reads - 1) else bs read = i2c_msg.read(self.address, count) self.bus.i2c_rdwr(write, read) # combined read&write data += list(read) return data
def set_multiple_switch(self, control, list=[]): """Set multiple switch state at once\n Control options: "on"/"off"\n list input : pairs of switches [x,y]\n e.g [1,2,5,6,7,8] = X1&Y2 , X5&y6, X7&Y8\n Register will latched during the sending sequence\n Register will be update at once after the last command\n Meaning all switches will be update simultaneously :param control: "on" or "off" :type control: str :param list: Pairs of switches, defaults to [] :type list: list """ with SMBus(1) as bus: for i in range(0, len(list), 2): if i != len(list) - 2: lsb = 0x00 | LATCH else: lsb = 0x00 | NO_LATCH msb = ( (CONTROL[control] << 7) | X[list[i]] << 3) | Y[list[i + 1]] print([hex(msb), hex(lsb)]) msg = i2c_msg.write(self.i2c_addr, [msb, lsb]) bus.i2c_rdwr(msg)
def handle_read(data): addr = int.from_bytes(data[10:12], byteorder='big') length = int.from_bytes(data[6:10], byteorder='big') #logging.debug("Handle read %s/%s",addr,length) #spi_response = bytes([0x00] * length) #arr = bytearray() #[addr >> 8] mw = i2c_msg.write(0x38, [(addr >> 8) & 0xFF, addr & 0xFF ]) mr = i2c_msg.read(0x38, length) #print('mw = {}'.format(list(mw))) printh(list(mw)) with SMBus(5) as bus: bus.i2c_rdwr(mw, mr) #print('mr = {}'.format(list(mr))) printh(list(mr)) spi_response = bytes(list(mr)) #print('spi_response ({}) = {}'.format(len(spi_response), list(spi_response))) #SigmaTCPHandler.spi.read(addr, length) print("read {} bytes from {:04X}".format(length, addr)) res = SigmaTCPHandler._response_packet(COMMAND_READRESPONSE, addr, len(spi_response)) + spi_response return res
def pageReadEEPROM(self, pageNum): """Implementation of pageReadEEPROM """ data = [ 0xa5, 0x05, self.__Command_code.COMMAND_PAGE_READ_EEPROM.value, pageNum ] checksum = 0 for x in data: checksum += x data.append(checksum % 256) write = i2c_msg.write(self._address, data) self._bus.i2c_rdwr(write) time.sleep(0.05) ## ## Read the specified length of data - ACK, Num Bytes, EEPROM Page Data, Checksum ## -> 1 + 1 + 16 + 1 = 19 bytes of data ## read = i2c_msg.read(self._address, 19) self._bus.i2c_rdwr(read) buf = [] buf.extend(read) return (self.__checkHeaderAndChecksum(16, buf), buf[2:-1])
def __registerReadNBytes(self, addressHigh, addressLow, numBytesToRead): """Implementation of RegisterReadNBytes """ data = [ 0xa5, 0x08, self.__Command_code.COMMAND_SET_ADDRESS_POINTER.value, addressHigh, addressLow, self.__Command_code.COMMAND_REGISTER_READ_N_BYTES.value, numBytesToRead ] checksum = 0 for x in data: checksum += x # Add checksum at the end data.append(checksum % 256) write = i2c_msg.write(self._address, data) self._bus.i2c_rdwr(write) time.sleep(0.05) read = i2c_msg.read(self._address, numBytesToRead + 3) self._bus.i2c_rdwr(read) buf = [] buf.extend(read) # print buf return (self.__checkHeaderAndChecksum(numBytesToRead, buf), buf)
def i2c_read8(self, reg): """Read a single (8bit) register from the device.""" msg_w = i2c_msg.write(self._i2c_addr, [reg]) msg_r = i2c_msg.read(self._i2c_addr, 1) self._i2c_dev.i2c_rdwr(msg_w, msg_r) return list(msg_r)[0]
def _send_command(self, cmd, value): self.busy = True bytes_to_read = 1 command = [pack('>B', cmd), pack('>I', value)] try: with SMBusWrapper(1) as bus: write = i2c_msg.write(self.address, command) # Have to get rid of the last byte on...smbus2 messes with the last word, not am sure why. read = i2c_msg.read(self.address, bytes_to_read + 1) bus.i2c_rdwr(write, read) data = list(read) data.pop() data = bytes(data) result = unpack('>I', data)[0] if (result == 10): print('Command Read: ' + str(cmd) + ' successful.') else: print('Command Read: ' + str(cmd) + ' failed.') except: self.read_scale_timer.error() print('Command Read: Scale ' + str(self.scale_number) + ' command ' + str(cmd) + ' timed out.') self.busy = False
def write(self, data): try: write_msg = i2c_msg.write(self._address, data) self._bus.i2c_rdwr(write_msg) except TypeError: traceback.print_exc() raise TransportException()
def __init__(self, config, bus_nr=1): self.config = config sensor_parameters = self.config.get_sensor_parameters('hm3301') with SMBus(bus_nr) as bus: write = i2c_msg.write(HM3301_DEFAULT_I2C_ADDR, [SELECT_I2C_ADDR]) bus.i2c_rdwr(write)
def setup(i2c_bus=1, i2c_addr=0x20, bits=24, read_mode=False, invert=False): """Set up the IO expander devices.""" global _I2C_ADDR global _BITS global _BUS global _PORT_VALUE global _READMODE global _INVERT _I2C_ADDR = i2c_addr _BITS = bits _READMODE = read_mode _INVERT = invert # Make 8-bits (can be 2- or 4-bits, but should always pack in a 8-bit msg) while bits % 8: bits += 1 # Increase array size _PORT_VALUE = [0xFF] * int(bits / 8) # Set up I2C bus connectivity _BUS = SMBus(i2c_bus) # Write 1 to all pins to prepaire them for reading, or bring hardware in a defined state msg = i2c_msg.write(_I2C_ADDR, _PORT_VALUE) if _BUS: _BUS.i2c_rdwr(msg) else: raise ReferenceError( "I2C bus was not created, please check I2C address!") # If in read mode: do first hw read to have memory ready if read_mode: hw_to_memory()
def set_full_cycle(self): """Sets the duty cycle to 100% """ with SMBus(1) as bus: msg = i2c_msg.write(I2C_ADDR, [0x20]) bus.i2c_rdwr(msg)
def read_result(self): ''' result reading sequence ''' # humidity self.bus.i2c_rdwr(i2c_msg.write(self.address, [self.HUMIDITY])) time.sleep(self.delay) humidity = i2c_msg.read(self.address, 2) self.bus.i2c_rdwr(humidity) time.sleep(self.delay) # temperature self.bus.i2c_rdwr(i2c_msg.write(self.address, [self.TEMPERATURE])) time.sleep(self.delay) temperature = i2c_msg.read(self.address, 2) self.bus.i2c_rdwr(temperature) return list(humidity), list(temperature)
def i2c_read_write( self, write: Union[int, ByteString], read: int = 0, rdelay: Optional[float] = None) -> Union[int, ByteString]: """ Generic I2C read/write operation. :param write: stream to send :param read: number of bytes to read :param rdelay: read delay :return: read bytes if final operation is read else int with number of bytes written """ if isinstance(write, int): write = bytes((write, )) messages = [i2c_msg.write(self.device_addr, write)] if rdelay is not None: # write it already and wait afterwards self.i2c_rdwr(*messages) messages.clear() time.sleep(rdelay) if read > 0: # append read message and execute rd_msg = i2c_msg.read(self.device_addr, read) messages.append(rd_msg) self.i2c_rdwr(*messages) messages.clear() return bytes(tuple(rd_msg)) if messages: self.i2c_rdwr(*messages) messages.clear() return len(write)
def _send_command(self, opcode, param_1, param_2=0x00, data=""): """Sends a security command packet over i2c. :param byte opcode: The command Opcode :param byte param_1: The first parameter :param byte param_2: The second parameter, can be two bytes. :param byte param_3 data: Optional remaining input data. """ # assembling command packet command_packet = bytearray(8 + len(data)) # word address command_packet[0] = 0x03 # i/o group: count command_packet[1] = len(command_packet) - 1 # count # security command packets command_packet[2] = opcode command_packet[3] = param_1 command_packet[4] = param_2 & 0xFF command_packet[5] = param_2 >> 8 for i, cmd in enumerate(data): command_packet[6 + i] = cmd # Checksum, CRC16 verification crc = self._at_crc(command_packet[1:-2]) command_packet[-1] = crc >> 8 command_packet[-2] = crc & 0xFF if self._debug: print("Command Packet Sz: ", len(command_packet)) print("\tSending:", [hex(i) for i in command_packet]) self.wakeup() w_msg = i2c_msg.write(self._address, command_packet) self._i2c.i2c_rdwr(w_msg) # small sleep time.sleep(0.001)
def __registerWriteNBytes(self, addressHigh, addressLow, numBytes, byteArray): """Implementation of registerWriteNBytes """ data = [ 0xa5, numBytes + 8, self.__Command_code.COMMAND_SET_ADDRESS_POINTER.value, addressHigh, addressLow, self.__Command_code.COMMAND_REGISTER_WRITE_N_BYTES.value, numBytes ] ## data here data.extend(byteArray) # print data ## compute and fill checksum as last element checksum = 0 for x in data: checksum += x data.append(checksum % 256) write = i2c_msg.write(self._address, data) self._bus.i2c_rdwr(write) time.sleep(0.05) header = self._bus.read_byte(self._address) self._logger.debug(header) return self.__checkHeader(header)
def write_block(self, start_block, data, bs=32, sleep_time=0.01): """ Write data in blocks, starting at pos start_block. :param start_block: The starting block :param data: The data to write :param bs: The block size. Set at 32 for this EEPROM :param sleep_time: A default value to delay between operations """ start_block = start_block*4 b_l = len(data) # Last block may not be complete if data length not divisible by block size b_c = int(ceil(b_l/float(bs))) # Block count # Actually splitting our data into blocks blocks = [data[bs*x:][:bs] for x in range(b_c)] for i, block in enumerate(blocks): if sleep_time: sleep(sleep_time) start = i*bs+start_block hb, lb = start >> 8, start & 0xff data = [hb, lb]+block write = i2c_msg.write(self.address, data) self.bus.i2c_rdwr(write)
def pageWriteEEPROM(self, pageNum, byteArray): """Implementation of pageWriteEEPROM """ if (len(byteArray) != 16): return self.Error_code.ERROR_INSUFFICIENT_ARRAY_SIZE.value data = [ 0xa5, 21, self.__Command_code.COMMAND_PAGE_WRITE_EEPROM.value, pageNum ] # Data here... data.extend(byteArray) checksum = 0 for x in data: checksum += x data.append(checksum % 256) write = i2c_msg.write(self._address, data) self._bus.i2c_rdwr(write) time.sleep(0.05) header = self._bus.read_byte(self._address) self._logger.debug(header) return self.__checkHeader(header)
def readVar(self,address,writeInts,readCount): #https://github.com/kplindegaard/smbus2 'dual i2c_rdrw' write = i2c_msg.write(address, writeInts) if readCount: read = i2c_msg.read(address,readCount) m=self.i2c.i2c_rdwr(write, read) return [chr(n) for n in list(read)]