Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ea17818

Browse files
authoredJun 30, 2021
bool switch between write probing and read
This enables probing with I2C-read (without write) from the sensor libraries.
1 parent 5089bd1 commit ea17818

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed
 

‎adafruit_bus_device/i2c_device.py

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,21 @@ class I2CDevice:
4141
device.write(bytes_read)
4242
"""
4343

44-
def __init__(self, i2c, device_address, probe=True):
45-
44+
def __init__(self, i2c, device_address, probe=True, probe_with_write=True):
45+
"""
46+
If probe is true you will probing the device.
47+
With probe_with_write you can switch between:
48+
True - a probing with write (& read if OSError)
49+
False - only probing with read
50+
"""
4651
self.i2c = i2c
4752
self.device_address = device_address
4853

4954
if probe:
50-
self.__probe_for_device()
55+
if probe_with_write:
56+
self.__write_probe_for_device()
57+
else:
58+
self.__only_read_probe_for_device()
5159

5260
def readinto(self, buf, *, start=0, end=None):
5361
"""
@@ -142,7 +150,32 @@ def __exit__(self, exc_type, exc_val, exc_tb):
142150
self.i2c.unlock()
143151
return False
144152

145-
def __probe_for_device(self):
153+
def __write_probe_for_device(self):
154+
"""
155+
Try to write empty byte string to an address.
156+
If OSError:
157+
Try to read a byte from an address,
158+
if you get an OSError it means the device is not there
159+
or that the device does not support these means of probing
160+
"""
161+
while not self.i2c.try_lock():
162+
pass
163+
try:
164+
self.i2c.writeto(self.device_address, b"")
165+
except OSError:
166+
# some OS's dont like writing an empty bytesting...
167+
# Retry by reading a byte
168+
try:
169+
result = bytearray(1)
170+
self.i2c.readfrom_into(self.device_address, result)
171+
except OSError:
172+
# pylint: disable=raise-missing-from
173+
raise ValueError("No I2C device at address: 0x%x" % self.device_address)
174+
# pylint: enable=raise-missing-from
175+
finally:
176+
self.i2c.unlock()
177+
178+
def __only_read_probe_for_device(self):
146179
"""
147180
Try to read a byte from an address,
148181
if you get an OSError it means the device is not there

0 commit comments

Comments
 (0)
Please sign in to comment.