@@ -41,13 +41,21 @@ class I2CDevice:
41
41
device.write(bytes_read)
42
42
"""
43
43
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
+ """
46
51
self .i2c = i2c
47
52
self .device_address = device_address
48
53
49
54
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 ()
51
59
52
60
def readinto (self , buf , * , start = 0 , end = None ):
53
61
"""
@@ -142,7 +150,32 @@ def __exit__(self, exc_type, exc_val, exc_tb):
142
150
self .i2c .unlock ()
143
151
return False
144
152
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 ):
146
179
"""
147
180
Try to read a byte from an address,
148
181
if you get an OSError it means the device is not there
0 commit comments