/ adafruit_debug_i2c.py
adafruit_debug_i2c.py
  1  # The MIT License (MIT)
  2  #
  3  # Copyright (c) 2019 Kattni Rembor for Adafruit Industries
  4  #
  5  # Permission is hereby granted, free of charge, to any person obtaining a copy
  6  # of this software and associated documentation files (the "Software"), to deal
  7  # in the Software without restriction, including without limitation the rights
  8  # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9  # copies of the Software, and to permit persons to whom the Software is
 10  # furnished to do so, subject to the following conditions:
 11  #
 12  # The above copyright notice and this permission notice shall be included in
 13  # all copies or substantial portions of the Software.
 14  #
 15  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 16  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 17  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 18  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 19  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 20  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 21  # THE SOFTWARE.
 22  """
 23  `adafruit_debug_i2c`
 24  ================================================================================
 25  
 26  Wrapper library for debugging I2C.
 27  
 28  
 29  * Author(s): Roy Hooper, Kattni Rembor
 30  
 31  Implementation Notes
 32  --------------------
 33  
 34  **Software and Dependencies:**
 35  
 36  * Adafruit CircuitPython firmware for the supported boards:
 37    https://github.com/adafruit/circuitpython/releases
 38  
 39  """
 40  
 41  __version__ = "0.0.0-auto.0"
 42  __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Debug_I2C.git"
 43  
 44  
 45  class DebugI2C:
 46      """
 47      Wrapper library for debugging I2C.
 48  
 49      This library wraps an I2C object and prints buffers before writes and after reads.
 50  
 51      See the I2C documentation for detailed documentation on the methods in this class.
 52  
 53      :param i2c: An initialized I2C object to debug.
 54  
 55      This example uses the LIS3DH accelerometer. This lib can be used with any I2C device. Save
 56      the code to your board.
 57  
 58      .. code-block:: python
 59  
 60          import adafruit_lis3dh
 61          from adafruit_debug_i2c import DebugI2C
 62          import busio
 63          import board
 64          import digitalio
 65  
 66          i2c = DebugI2C(busio.I2C(board.SCL, board.SDA))
 67          int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
 68          accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1)
 69  
 70          print(accelerometer.acceleration)
 71  
 72          for i in range(2):
 73              print(accelerometer.acceleration)
 74  
 75      """
 76  
 77      def __init__(self, i2c):
 78          self._i2c = i2c
 79          if hasattr(self._i2c, "writeto_then_readfrom"):
 80              self.writeto_then_readfrom = self._writeto_then_readfrom
 81  
 82      def __enter__(self):
 83          """
 84          No-op used in Context Managers.
 85          """
 86          return self._i2c.__enter__()
 87  
 88      def __exit__(self, exc_type, exc_val, exc_tb):
 89          """
 90          Automatically deinitialises the hardware on context exit.
 91          """
 92          return self._i2c.__exit__(exc_type, exc_val, exc_tb)
 93  
 94      def deinit(self):
 95          """
 96          Releases control of the underlying I2C hardware so other classes can use it.
 97          """
 98          return self._i2c.deinit()
 99  
100      def readfrom_into(self, address, buffer, *args, start=0, end=None):
101          """
102          Debug version of ``readfrom_into`` that prints the buffer after reading.
103  
104          :param int address: 7-bit device address
105          :param bytearray buffer: buffer to write into
106          :param int start: Index to start writing at
107          :param int end: Index to write up to but not include
108  
109          """
110          self._i2c.readfrom_into(address, buffer, *args, start=start, end=end)
111  
112          in_buffer_str = ", ".join([hex(i) for i in buffer])
113          print("\tI2CREAD  @ {} ::".format(hex(address)), in_buffer_str)
114  
115      def scan(self):
116          """
117          Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of those that
118          respond.
119  
120          :return: List of device ids on the I2C bus
121          :rtype: list
122          """
123          return self._i2c.scan()
124  
125      def try_lock(self):
126          """
127          Attempts to grab the I2C lock. Returns True on success.
128  
129          :return: True when lock has been grabbed
130          :rtype: bool
131          """
132          return self._i2c.try_lock()
133  
134      def unlock(self):
135          """
136          Releases the I2C lock.
137          """
138          return self._i2c.unlock()
139  
140      def writeto(self, address, buffer, *args, **kwargs):
141          """
142          Debug version of ``write`` that prints the buffer before sending.
143  
144          :param int address: 7-bit device address
145          :param bytearray buffer: buffer containing the bytes to write
146          :param int start: Index to start writing from
147          :param int end: Index to read up to but not include
148          :param bool stop: If true, output an I2C stop condition after the
149                            buffer is written
150          """
151          self._i2c.writeto(address, buffer, *args, **kwargs)
152  
153          out_buffer_str = ", ".join([hex(i) for i in buffer])
154          print("\tI2CWRITE @ {} ::".format(hex(address)), out_buffer_str)
155  
156      def _writeto_then_readfrom(
157          self,
158          address,
159          buffer_out,
160          buffer_in,
161          *args,
162          out_start=0,
163          out_end=None,
164          in_start=0,
165          in_end=None
166      ):
167          """
168          Debug version of ``write_readinto`` that prints the ``buffer_out`` before writing and the
169          ``buffer_in`` after reading.
170  
171          :TODO Verify parameter documentation is accurate
172          :param address: 7-bit device address
173          :param bytearray buffer_out: Write out the data in this buffer
174          :param bytearray buffer_in: Read data into this buffer
175          :param int out_start: Start of the slice of buffer_out to write out:
176                                ``buffer_out[out_start:out_end]``
177          :param int out_end: End of the slice; this index is not included. Defaults to
178                              ``len(buffer_out)``
179          :param int in_start: Start of the slice of ``buffer_in`` to read into:
180                               ``buffer_in[in_start:in_end]``
181          :param int in_end: End of the slice; this index is not included. Defaults to
182                             ``len(buffer_in)``
183          """
184          out_buffer_str = ", ".join([hex(i) for i in buffer_out[out_start:out_end]])
185          print("\tI2CWRITE @ {} ::".format(hex(address)), out_buffer_str)
186  
187          self._i2c.writeto_then_readfrom(
188              address,
189              buffer_out,
190              buffer_in,
191              *args,
192              out_start=out_start,
193              out_end=out_end,
194              in_start=in_start,
195              in_end=in_end,
196          )
197  
198          in_buffer_str = ", ".join([hex(i) for i in buffer_in[in_start:in_end]])
199          print("\tI2CREAD  @ {} ::".format(hex(address)), in_buffer_str)