Skip to content

Add type annotations, update documentation #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ confidence=
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,unspecified-encoding
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,unspecified-encoding,duplicate-code

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
Expand Down
55 changes: 38 additions & 17 deletions adafruit_bus_device/i2c_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@
====================================================
"""

try:
from typing import Optional, Type
from types import TracebackType
from busio import I2C

try:
from circuitpython_typing import ReadableBuffer, WriteableBuffer
except ImportError:
from _typing import ReadableBuffer, WriteableBuffer
except ImportError:
pass

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_BusDevice.git"

Expand Down Expand Up @@ -41,15 +53,17 @@ class I2CDevice:
device.write(bytes_read)
"""

def __init__(self, i2c, device_address, probe=True):
def __init__(self, i2c: I2C, device_address: int, probe: bool = True) -> None:

self.i2c = i2c
self.device_address = device_address

if probe:
self.__probe_for_device()

def readinto(self, buf, *, start=0, end=None):
def readinto(
self, buf: WriteableBuffer, *, start: int = 0, end: Optional[int] = None
) -> None:
"""
Read into ``buf`` from the device. The number of bytes read will be the
length of ``buf``.
Expand All @@ -58,15 +72,17 @@ def readinto(self, buf, *, start=0, end=None):
as if ``buf[start:end]``. This will not cause an allocation like
``buf[start:end]`` will so it saves memory.

:param bytearray buffer: buffer to write into
:param ~WriteableBuffer buffer: buffer to write into
:param int start: Index to start writing at
:param int end: Index to write up to but not include; if None, use ``len(buf)``
"""
if end is None:
end = len(buf)
self.i2c.readfrom_into(self.device_address, buf, start=start, end=end)

def write(self, buf, *, start=0, end=None):
def write(
self, buf: ReadableBuffer, *, start: int = 0, end: Optional[int] = None
) -> None:
"""
Write the bytes from ``buffer`` to the device, then transmit a stop
bit.
Expand All @@ -75,7 +91,7 @@ def write(self, buf, *, start=0, end=None):
as if ``buffer[start:end]``. This will not cause an allocation like
``buffer[start:end]`` will so it saves memory.

:param bytearray buffer: buffer containing the bytes to write
:param ~ReadableBuffer buffer: buffer containing the bytes to write
:param int start: Index to start writing from
:param int end: Index to read up to but not include; if None, use ``len(buf)``
"""
Expand All @@ -86,14 +102,14 @@ def write(self, buf, *, start=0, end=None):
# pylint: disable-msg=too-many-arguments
def write_then_readinto(
self,
out_buffer,
in_buffer,
out_buffer: ReadableBuffer,
in_buffer: WriteableBuffer,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None
):
out_start: int = 0,
out_end: Optional[int] = None,
in_start: int = 0,
in_end: Optional[int] = None
) -> None:
"""
Write the bytes from ``out_buffer`` to the device, then immediately
reads into ``in_buffer`` from the device. The number of bytes read
Expand All @@ -109,8 +125,8 @@ def write_then_readinto(
cause an allocation like ``in_buffer[in_start:in_end]`` will so
it saves memory.

:param bytearray out_buffer: buffer containing the bytes to write
:param bytearray in_buffer: buffer containing the bytes to read into
:param ~ReadableBuffer out_buffer: buffer containing the bytes to write
:param ~WriteableBuffer in_buffer: buffer containing the bytes to read into
:param int out_start: Index to start writing from
:param int out_end: Index to read up to but not include; if None, use ``len(out_buffer)``
:param int in_start: Index to start writing at
Expand All @@ -133,16 +149,21 @@ def write_then_readinto(

# pylint: enable-msg=too-many-arguments

def __enter__(self):
def __enter__(self) -> "I2CDevice":
while not self.i2c.try_lock():
pass
return self

def __exit__(self, exc_type, exc_val, exc_tb):
def __exit__(
self,
exc_type: Optional[Type[type]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> bool:
self.i2c.unlock()
return False

def __probe_for_device(self):
def __probe_for_device(self) -> None:
"""
Try to read a byte from an address,
if you get an OSError it means the device is not there
Expand Down
36 changes: 26 additions & 10 deletions adafruit_bus_device/spi_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
====================================================
"""

try:
from typing import Optional, Type
from types import TracebackType
from busio import SPI
from digitalio import DigitalInOut
except ImportError:
pass

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_BusDevice.git"

Expand All @@ -23,6 +31,9 @@ class SPIDevice:
DigitalInOut API.
:param bool cs_active_value: Set to true if your device requires CS to be active high.
Defaults to false.
:param int baudrate: The SPI baudrate
:param int polarity: The SPI polarity
:param int phase: The SPI phase
:param int extra_clocks: The minimum number of clock cycles to cycle the bus after CS is high.
(Used for SD cards.)

Expand Down Expand Up @@ -54,15 +65,15 @@ class SPIDevice:

def __init__(
self,
spi,
chip_select=None,
spi: SPI,
chip_select: Optional[DigitalInOut] = None,
*,
cs_active_value=False,
baudrate=100000,
polarity=0,
phase=0,
extra_clocks=0
):
cs_active_value: bool = False,
baudrate: int = 100000,
polarity: int = 0,
phase: int = 0,
extra_clocks: int = 0
) -> None:
self.spi = spi
self.baudrate = baudrate
self.polarity = polarity
Expand All @@ -73,7 +84,7 @@ def __init__(
if self.chip_select:
self.chip_select.switch_to_output(value=True)

def __enter__(self):
def __enter__(self) -> SPI:
while not self.spi.try_lock():
pass
self.spi.configure(
Expand All @@ -83,7 +94,12 @@ def __enter__(self):
self.chip_select.value = self.cs_active_value
return self.spi

def __exit__(self, exc_type, exc_val, exc_tb):
def __exit__(
self,
exc_type: Optional[Type[type]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> bool:
if self.chip_select:
self.chip_select.value = not self.cs_active_value
if self.extra_clocks > 0:
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
# Uncomment the below if you use native CircuitPython modules such as
# digitalio, micropython and busio. List the modules you use. Without it, the
# autodoc module docs will fail to generate with a warning.
# autodoc_mock_imports = ["adafruit_bus_device", "micropython"]
autodoc_mock_imports = ["busio", "digitalio", "circuitpython_typing", "_typing"]

intersphinx_mapping = {
"python": ("https://docs.python.org/3.4", None),
Expand Down