]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/ft232h/i2c.py
Use black to fix formatting.
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / ft232h / i2c.py
1 """I2C Class for FT232H"""
2 from adafruit_blinka.microcontroller.ft232h.pin import Pin
3 from adafruit_blinka.microcontroller.ft232h.url import get_ftdi_url
4
5
6 class I2C:
7     """Custom I2C Class for FT232H"""
8
9     def __init__(self, *, frequency=400000):
10         # change GPIO controller to I2C
11         # pylint: disable=import-outside-toplevel
12         from pyftdi.i2c import I2cController
13
14         # pylint: enable=import-outside-toplevel
15
16         self._i2c = I2cController()
17         self._i2c.configure(get_ftdi_url(), frequency=frequency)
18         Pin.ft232h_gpio = self._i2c.get_gpio()
19
20     def scan(self):
21         """Perform an I2C Device Scan"""
22         return [addr for addr in range(0x79) if self._i2c.poll(addr)]
23
24     def writeto(self, address, buffer, *, start=0, end=None, stop=True):
25         """Write data from the buffer to an address"""
26         end = end if end else len(buffer)
27         port = self._i2c.get_port(address)
28         port.write(buffer[start:end], relax=stop)
29
30     def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
31         """Read data from an address and into the buffer"""
32         end = end if end else len(buffer)
33         port = self._i2c.get_port(address)
34         result = port.read(len(buffer[start:end]), relax=stop)
35         for i, b in enumerate(result):
36             buffer[start + i] = b
37
38     # pylint: disable=unused-argument
39     def writeto_then_readfrom(
40         self,
41         address,
42         buffer_out,
43         buffer_in,
44         *,
45         out_start=0,
46         out_end=None,
47         in_start=0,
48         in_end=None,
49         stop=False
50     ):
51         """Write data from buffer_out to an address and then
52         read data from an address and into buffer_in
53         """
54         out_end = out_end if out_end else len(buffer_out)
55         in_end = in_end if in_end else len(buffer_in)
56         port = self._i2c.get_port(address)
57         result = port.exchange(
58             buffer_out[out_start:out_end], in_end - in_start, relax=True
59         )
60         for i, b in enumerate(result):
61             buffer_in[in_start + i] = b
62
63     # pylint: enable=unused-argument