]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/ftdi_mpsse/mpsse/i2c.py
Format with black, fix pylint errors
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / ftdi_mpsse / mpsse / i2c.py
1 """I2C Class for FTDI MPSSE"""
2 from adafruit_blinka.microcontroller.ftdi_mpsse.mpsse.pin import Pin
3
4
5 class I2C:
6     """Custom I2C Class for FTDI MPSSE"""
7
8     MASTER = 0
9     SLAVE = 1
10     _mode = None
11
12     # pylint: disable=unused-argument
13     def __init__(self, i2c_id=None, mode=MASTER, baudrate=None, frequency=400000):
14         if mode != self.MASTER:
15             raise NotImplementedError("Only I2C Master supported!")
16         _mode = self.MASTER
17
18         # change GPIO controller to I2C
19         # pylint: disable=import-outside-toplevel
20         from pyftdi.i2c import I2cController
21
22         # pylint: enable=import-outside-toplevel
23
24         self._i2c = I2cController()
25         if i2c_id is None:
26             self._i2c.configure("ftdi://ftdi:ft232h/1", frequency=frequency)
27         else:
28             self._i2c.configure(
29                 "ftdi://ftdi:ft2232h/{}".format(i2c_id + 1), frequency=frequency
30             )
31         Pin.mpsse_gpio = self._i2c.get_gpio()
32
33     def scan(self):
34         """Perform an I2C Device Scan"""
35         return [addr for addr in range(0x79) if self._i2c.poll(addr)]
36
37     def writeto(self, address, buffer, *, start=0, end=None, stop=True):
38         """Write data from the buffer to an address"""
39         end = end if end else len(buffer)
40         port = self._i2c.get_port(address)
41         port.write(buffer[start:end], relax=stop)
42
43     def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
44         """Read data from an address and into the buffer"""
45         end = end if end else len(buffer)
46         port = self._i2c.get_port(address)
47         result = port.read(len(buffer[start:end]), relax=stop)
48         for i, b in enumerate(result):
49             buffer[start + i] = b
50
51     # pylint: disable=unused-argument
52     def writeto_then_readfrom(
53         self,
54         address,
55         buffer_out,
56         buffer_in,
57         *,
58         out_start=0,
59         out_end=None,
60         in_start=0,
61         in_end=None,
62         stop=False,
63     ):
64         """Write data from buffer_out to an address and then
65         read data from an address and into buffer_in
66         """
67         out_end = out_end if out_end else len(buffer_out)
68         in_end = in_end if in_end else len(buffer_in)
69         port = self._i2c.get_port(address)
70         result = port.exchange(
71             buffer_out[out_start:out_end], in_end - in_start, relax=True
72         )
73         for i, b in enumerate(result):
74             buffer_in[in_start + i] = b
75
76     # pylint: enable=unused-argument