1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
 
   3 # SPDX-License-Identifier: MIT
 
   4 """Generic Linux I2C class using PureIO's smbus class"""
 
   7 from Adafruit_PureIO import smbus
 
  14     Baudrate has no effect on Linux systems. The argument is only there for compatibility.
 
  23     # pylint: disable=unused-argument
 
  24     def __init__(self, bus_num, mode=MASTER, baudrate=None):
 
  25         if mode != self.MASTER:
 
  26             raise NotImplementedError("Only I2C Master supported!")
 
  29         if baudrate is not None:
 
  31                 "I2C frequency is not settable in python, ignoring!", RuntimeWarning
 
  35             self._i2c_bus = smbus.SMBus(bus_num)
 
  36         except FileNotFoundError:
 
  38                 "I2C Bus #%d not found, check if enabled in config!" % bus_num
 
  41     # pylint: enable=unused-argument
 
  44         """Try to read a byte from each address, if you get an OSError
 
  45         it means the device isnt there"""
 
  47         for addr in range(0, 0x80):
 
  49                 self._i2c_bus.read_byte(addr)
 
  55     # pylint: disable=unused-argument
 
  56     def writeto(self, address, buffer, *, start=0, end=None, stop=True):
 
  57         """Write data from the buffer to an address"""
 
  60         self._i2c_bus.write_bytes(address, buffer[start:end])
 
  62     def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
 
  63         """Read data from an address and into the buffer"""
 
  67         readin = self._i2c_bus.read_bytes(address, end - start)
 
  68         for i in range(end - start):
 
  69             buffer[i + start] = readin[i]
 
  71     # pylint: enable=unused-argument
 
  73     def writeto_then_readfrom(
 
  85         """Write data from buffer_out to an address and then
 
  86         read data from an address and into buffer_in
 
  89             out_end = len(buffer_out)
 
  91             in_end = len(buffer_in)
 
  93             # To generate a stop in linux, do in two transactions
 
  94             self.writeto(address, buffer_out, start=out_start, end=out_end, stop=True)
 
  95             self.readfrom_into(address, buffer_in, start=in_start, end=in_end)
 
  97             # To generate without a stop, do in one block transaction
 
  98             readin = self._i2c_bus.read_i2c_block_data(
 
  99                 address, buffer_out[out_start:out_end], in_end - in_start
 
 101             for i in range(in_end - in_start):
 
 102                 buffer_in[i + in_start] = readin[i]