Skip to content

Commit 8454b24

Browse files
committed
add Circuitpython/Linux(auto) as I2cTransceiver
1 parent 9da10df commit 8454b24

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

sensirion_i2c_driver/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,13 @@
55
from .version import version as __version__ # noqa: F401
66
from .device import I2cDevice # noqa: F401
77
from .connection import I2cConnection # noqa: F401
8-
from .linux_i2c_transceiver import LinuxI2cTransceiver # noqa: F401
8+
9+
import sys
10+
if sys.implementation.name.lower() == "circuitpython":
11+
from .circuitpython_i2c_transceiver import CircuitPythonI2cTransceiver as I2cTransceiver
12+
else:
13+
from .linux_i2c_transceiver import LinuxI2cTransceiver as I2cTransceiver
14+
915
from .command import I2cCommand # noqa: F401
1016
from .sensirion_command import SensirionI2cCommand # noqa: F401
1117
from .crc_calculator import CrcCalculator # noqa: F401
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from adafruit_bus_device.i2c_device import I2CDevice
2+
from .transceiver_v1 import I2cTransceiverV1
3+
import time
4+
5+
class CircuitPythonI2cTransceiver(I2cTransceiverV1):
6+
def __init__(self, i2c, device_address):
7+
super(CircuitPythonI2cTransceiver, self).__init__()
8+
self._device = I2CDevice(i2c, device_address)
9+
10+
@property
11+
def description(self):
12+
return "CircuitPython I2C Transceiver"
13+
14+
def transceive(self, slave_address, tx_data, rx_length, read_delay, timeout):
15+
error = None
16+
status = self.STATUS_OK
17+
try:
18+
if tx_data is not None:
19+
self.write(tx_data)
20+
except OSError as e:
21+
status = self.STATUS_UNSPECIFIED_ERROR
22+
error = e
23+
24+
if read_delay > 0:
25+
time.sleep(read_delay)
26+
if(status == self.STATUS_OK):
27+
try:
28+
if rx_length is not None:
29+
return status, error, self.read(rx_length)
30+
except OSError as e:
31+
status = self.STATUS_UNSPECIFIED_ERROR
32+
error = e
33+
34+
return status, error, bytearray(b"")
35+
36+
37+
def write(self, data):
38+
data_bytes = bytearray(data) if isinstance(data, (bytes, bytearray, list, tuple)) else bytearray()
39+
if(len(data_bytes) == 0):
40+
return
41+
with self._device as i2c_device:
42+
i2c_device.write(data_bytes)
43+
44+
def read(self, count):
45+
read_buffer = bytearray(count)
46+
with self._device as i2c_device:
47+
i2c_device.readinto(read_buffer)
48+
return read_buffer

0 commit comments

Comments
 (0)