Skip to content

Add typing, minor tweaks #24

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 4 commits into from
Jan 10, 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
46 changes: 29 additions & 17 deletions adafruit_onewire/bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
import busio
from micropython import const

try:
from typing import Optional, List, Tuple
from microcontroller import Pin
except ImportError:
pass

_SEARCH_ROM = const(0xF0)
_MATCH_ROM = const(0x55)
_SKIP_ROM = const(0xCC)
Expand All @@ -30,56 +36,56 @@ class OneWireError(Exception):
class OneWireAddress:
"""A class to represent a 1-Wire address."""

def __init__(self, rom):
def __init__(self, rom: bytearray) -> None:
self._rom = rom

@property
def rom(self):
def rom(self) -> bytearray:
"""The unique 64 bit ROM code."""
return self._rom

@property
def crc(self):
def crc(self) -> int:
"""The 8 bit CRC."""
return self._rom[7]

@property
def serial_number(self):
def serial_number(self) -> bytearray:
"""The 48 bit serial number."""
return self._rom[1:7]

@property
def family_code(self):
def family_code(self) -> int:
"""The 8 bit family code."""
return self._rom[0]


class OneWireBus:
"""A class to represent a 1-Wire bus."""

def __init__(self, pin):
def __init__(self, pin: Pin) -> None:
# pylint: disable=no-member
self._ow = busio.OneWire(pin)
self._readbit = self._ow.read_bit
self._writebit = self._ow.write_bit
self._maximum_devices = _MAX_DEV

@property
def maximum_devices(self):
def maximum_devices(self) -> int:
"""The maximum number of devices the bus will scan for. Valid range is 1 to 255.
It is an error to have more devices on the bus than this number. Having less is OK.
"""
return self._maximum_devices

@maximum_devices.setter
def maximum_devices(self, count):
def maximum_devices(self, count: int) -> None:
if not isinstance(count, int):
raise ValueError("Maximum must be an integer value 1 - 255.")
if count < 1 or count > 0xFF:
raise ValueError("Maximum must be an integer value 1 - 255.")
self._maximum_devices = count

def reset(self, required=False):
def reset(self, required: bool = False) -> bool:
"""
Perform a reset and check for presence pulse.

Expand All @@ -90,7 +96,9 @@ def reset(self, required=False):
raise OneWireError("No presence pulse found. Check devices and wiring.")
return not reset

def readinto(self, buf, *, start=0, end=None):
def readinto(
self, buf: bytearray, *, 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 @@ -108,7 +116,9 @@ def readinto(self, buf, *, start=0, end=None):
for i in range(start, end):
buf[i] = self._readbyte()

def write(self, buf, *, start=0, end=None):
def write(
self, buf: bytearray, *, start: int = 0, end: Optional[int] = None
) -> None:
"""
Write the bytes from ``buf`` to the device.

Expand All @@ -125,11 +135,11 @@ def write(self, buf, *, start=0, end=None):
for i in range(start, end):
self._writebyte(buf[i])

def scan(self):
def scan(self) -> List[OneWireAddress]:
"""Scan for devices on the bus and return a list of addresses."""
devices = []
diff = 65
rom = False
rom = None
count = 0
for _ in range(0xFF):
rom, diff = self._search_rom(rom, diff)
Expand All @@ -146,18 +156,20 @@ def scan(self):
break
return devices

def _readbyte(self):
def _readbyte(self) -> int:
val = 0
for i in range(8):
val |= self._ow.read_bit() << i
return val

def _writebyte(self, value):
def _writebyte(self, value: int) -> None:
for i in range(8):
bit = (value >> i) & 0x1
self._ow.write_bit(bit)

def _search_rom(self, l_rom, diff):
def _search_rom(
self, l_rom: Optional[bytearray], diff: int
) -> Tuple[bytearray, int]:
if not self.reset():
return None, 0
self._writebyte(_SEARCH_ROM)
Expand Down Expand Up @@ -185,7 +197,7 @@ def _search_rom(self, l_rom, diff):
return rom, next_diff

@staticmethod
def crc8(data):
def crc8(data: bytearray) -> int:
"""
Perform the 1-Wire CRC check on the provided data.

Expand Down
28 changes: 22 additions & 6 deletions adafruit_onewire/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,38 @@
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_OneWire.git"

try:
from typing import Optional, Type
from types import TracebackType
from adafruit_onewire.bus import OneWireBus, OneWireAddress
except ImportError:
pass

_MATCH_ROM = b"\x55"


class OneWireDevice:
"""A class to represent a single device on the 1-Wire bus."""

def __init__(self, bus, address):
def __init__(self, bus: OneWireBus, address: OneWireAddress):
self._bus = bus
self._address = address

def __enter__(self):
def __enter__(self) -> "OneWireDevice":
self._select_rom()
return self

def __exit__(self, *exc):
def __exit__(
self,
exception_type: Optional[Type[type]],
exception_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> bool:
return False

def readinto(self, buf, *, start=0, end=None):
def readinto(
self, buf: bytearray, *, 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 @@ -49,7 +63,9 @@ def readinto(self, buf, *, start=0, end=None):
if self._bus.crc8(buf):
raise RuntimeError("CRC error.")

def write(self, buf, *, start=0, end=None):
def write(
self, buf: bytearray, *, start: int = 0, end: Optional[int] = None
) -> None:
"""
Write the bytes from ``buf`` to the device.

Expand All @@ -63,7 +79,7 @@ def write(self, buf, *, start=0, end=None):
"""
return self._bus.write(buf, start=start, end=end)

def _select_rom(self):
def _select_rom(self) -> None:
self._bus.reset()
self.write(_MATCH_ROM)
self.write(self._address.rom)