Skip to content

Adding ability to skip device probing upon object init. … #35

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
Nov 26, 2019
Merged
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
45 changes: 26 additions & 19 deletions adafruit_bus_device/i2c_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class I2CDevice:

:param ~busio.I2C i2c: The I2C bus the device is on
:param int device_address: The 7 bit device address
:param bool probe: Probe for the device upon object creation, default is true

.. note:: This class is **NOT** built into CircuitPython. See
:ref:`here for install instructions <bus_device_installation>`.
Expand All @@ -57,29 +58,14 @@ class I2CDevice:
device.write(bytes_read)
"""

def __init__(self, i2c, device_address):
"""
Try to read a byte from an address,
if you get an OSError it means the device is not there
"""
while not i2c.try_lock():
pass
try:
i2c.writeto(device_address, b'')
except OSError:
# some OS's dont like writing an empty bytesting...
# Retry by reading a byte
try:
result = bytearray(1)
i2c.readfrom_into(device_address, result)
except OSError:
raise ValueError("No I2C device at address: %x" % device_address)
finally:
i2c.unlock()
def __init__(self, i2c, device_address, probe=True):

self.i2c = i2c
self.device_address = device_address

if probe:
self.__probe_for_device()

def readinto(self, buf, **kwargs):
"""
Read into ``buf`` from the device. The number of bytes read will be the
Expand Down Expand Up @@ -164,3 +150,24 @@ def __enter__(self):
def __exit__(self, *exc):
self.i2c.unlock()
return False

def __probe_for_device(self):
"""
Try to read a byte from an address,
if you get an OSError it means the device is not there
or that the device does not support these means of probing
"""
while not self.i2c.try_lock():
pass
try:
self.i2c.writeto(self.device_address, b'')
except OSError:
# some OS's dont like writing an empty bytesting...
# Retry by reading a byte
try:
result = bytearray(1)
self.i2c.readfrom_into(self.device_address, result)
except OSError:
raise ValueError("No I2C device at address: %x" % self.device_address)
finally:
self.i2c.unlock()