i2c-api 0.20.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- i2c_api/__init__.py +5 -0
- i2c_api/commands.py +80 -0
- i2c_api/exec_results.py +18 -0
- i2c_api/language.py +136 -0
- i2c_api/log.py +66 -0
- i2c_api/logger.py +9 -0
- i2c_api/master.py +314 -0
- i2c_api-0.20.0.dist-info/METADATA +36 -0
- i2c_api-0.20.0.dist-info/RECORD +12 -0
- i2c_api-0.20.0.dist-info/WHEEL +5 -0
- i2c_api-0.20.0.dist-info/licenses/LICENSE +21 -0
- i2c_api-0.20.0.dist-info/top_level.txt +1 -0
i2c_api/__init__.py
ADDED
i2c_api/commands.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
class Command:
|
|
2
|
+
def __repr__(self) -> str:
|
|
3
|
+
return f"{self.__class__.__name__}()"
|
|
4
|
+
|
|
5
|
+
def to_dict(self) -> dict[str, str]:
|
|
6
|
+
return {"cmd": self.__class__.__name__}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class S(Command):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Address(Command):
|
|
14
|
+
__match_args__ = ("address",)
|
|
15
|
+
|
|
16
|
+
def __init__(self, address: int):
|
|
17
|
+
self.address = address
|
|
18
|
+
|
|
19
|
+
def __repr__(self) -> str:
|
|
20
|
+
if self.address == -1:
|
|
21
|
+
return f"{self.__class__.__name__}(auto)"
|
|
22
|
+
else:
|
|
23
|
+
return f"{self.__class__.__name__}(0x{self.address:02X})"
|
|
24
|
+
|
|
25
|
+
def to_dict(self) -> dict[str, str]:
|
|
26
|
+
return {"cmd": self.__class__.__name__, "address": f"{self.address}"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Address10(Command):
|
|
30
|
+
__match_args__ = ("address",)
|
|
31
|
+
|
|
32
|
+
def __init__(self, address: int):
|
|
33
|
+
self.address = address
|
|
34
|
+
|
|
35
|
+
def __repr__(self) -> str:
|
|
36
|
+
if self.address == -1:
|
|
37
|
+
return f"{self.__class__.__name__}(auto)"
|
|
38
|
+
else:
|
|
39
|
+
return f"{self.__class__.__name__}(0x{self.address:02X})"
|
|
40
|
+
|
|
41
|
+
def to_dict(self) -> dict[str, str]:
|
|
42
|
+
return {"cmd": self.__class__.__name__, "address": f"{self.address}"}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class W(Command):
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Data(Command):
|
|
50
|
+
__match_args__ = ("data",)
|
|
51
|
+
|
|
52
|
+
def __init__(self, data: int):
|
|
53
|
+
self.data = data
|
|
54
|
+
|
|
55
|
+
def __repr__(self) -> str:
|
|
56
|
+
return f"{self.__class__.__name__}(0x{self.data:02X})"
|
|
57
|
+
|
|
58
|
+
def to_dict(self) -> dict[str, str]:
|
|
59
|
+
return {"cmd": self.__class__.__name__, "payload": f"{self.data}"}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Read(Command):
|
|
63
|
+
__match_args__ = ("num_bytes",)
|
|
64
|
+
|
|
65
|
+
def __init__(self, num_bytes: int):
|
|
66
|
+
self.num_bytes = num_bytes
|
|
67
|
+
|
|
68
|
+
def __repr__(self) -> str:
|
|
69
|
+
return f"{self.__class__.__name__}({self.num_bytes})"
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> dict[str, str]:
|
|
72
|
+
return {"cmd": self.__class__.__name__, "num_bytes": f"{self.num_bytes}"}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Sr(Command):
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class P(Command):
|
|
80
|
+
pass
|
i2c_api/exec_results.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from functools import reduce
|
|
2
|
+
from typing import NamedTuple
|
|
3
|
+
|
|
4
|
+
from bitstring import BitArray
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ExecResults(NamedTuple):
|
|
8
|
+
data: list[list[BitArray]]
|
|
9
|
+
is_success: bool
|
|
10
|
+
|
|
11
|
+
def values(self) -> list[BitArray]:
|
|
12
|
+
"""Returns contained response data as a list of BitArray with consecutive bytes combined"""
|
|
13
|
+
return [reduce(lambda v, acc: v + acc, [BitArray(f"uint:8={x}") for x in rsp], BitArray()) for rsp in self.data]
|
|
14
|
+
|
|
15
|
+
def pp(self) -> str:
|
|
16
|
+
"""Pretty print"""
|
|
17
|
+
values_ = ["0b" + v.bin for v in self.values()]
|
|
18
|
+
return f"ExecResults(values={values_}, is_success={self.is_success})"
|
i2c_api/language.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import Protocol
|
|
3
|
+
|
|
4
|
+
from i2c_api.commands import Address, Command, Data, P, Read, S, Sr, W
|
|
5
|
+
from i2c_api.exec_results import ExecResults
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class I2CMaster(Protocol):
|
|
9
|
+
def exec(self, transaction: "I2CTransaction", device_address: int = -1) -> ExecResults: ...
|
|
10
|
+
|
|
11
|
+
def _exec(self, transaction: "I2CTransaction", device_address: int = -1) -> ExecResults: ...
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class I2CTransaction:
|
|
15
|
+
def __init__(self, i2c: "I2CTransactionBuilder"):
|
|
16
|
+
self._i2c = i2c
|
|
17
|
+
|
|
18
|
+
def __repr__(self) -> str:
|
|
19
|
+
return ".".join(str(c) for c in self._i2c._i2c_commands)
|
|
20
|
+
|
|
21
|
+
def exec(self, master: I2CMaster, device_address: int = -1) -> ExecResults:
|
|
22
|
+
if master is None:
|
|
23
|
+
raise ValueError("I2CMaster must be provided to execute this transaction")
|
|
24
|
+
|
|
25
|
+
def get_transaction():
|
|
26
|
+
if device_address == -1:
|
|
27
|
+
for c in self._i2c._i2c_commands:
|
|
28
|
+
if isinstance(c, Address) and c.address == -1:
|
|
29
|
+
raise ValueError(
|
|
30
|
+
"Some Address(...) commands are given without the address. "
|
|
31
|
+
"Thus, argument `device_address` must be provided."
|
|
32
|
+
)
|
|
33
|
+
return self
|
|
34
|
+
|
|
35
|
+
else:
|
|
36
|
+
# Autofill addresses if necessary.
|
|
37
|
+
new_root = I2CTransactionBuilder()
|
|
38
|
+
for c in self._i2c._i2c_commands:
|
|
39
|
+
if isinstance(c, Address):
|
|
40
|
+
if c.address == -1:
|
|
41
|
+
new_root._i2c_commands.append(Address(device_address))
|
|
42
|
+
else:
|
|
43
|
+
new_root._i2c_commands.append(c)
|
|
44
|
+
else:
|
|
45
|
+
new_root._i2c_commands.append(c)
|
|
46
|
+
|
|
47
|
+
return I2CTransaction(new_root)
|
|
48
|
+
|
|
49
|
+
return master.exec(get_transaction())
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def to_json(transaction: "I2CTransaction") -> str:
|
|
53
|
+
return json.dumps([cmd.to_dict() for cmd in transaction._i2c._i2c_commands])
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def from_json(json_str: str) -> "I2CTransaction":
|
|
57
|
+
i2c = I2CTransactionBuilder()
|
|
58
|
+
op = ""
|
|
59
|
+
payload_acc: list[int] = []
|
|
60
|
+
for cmd in json.loads(json_str):
|
|
61
|
+
match cmd["cmd"]:
|
|
62
|
+
case "S":
|
|
63
|
+
i2c = i2c.start()
|
|
64
|
+
case "Address":
|
|
65
|
+
i2c = i2c.address(int(cmd["address"]))
|
|
66
|
+
case "W":
|
|
67
|
+
op = "write"
|
|
68
|
+
case "Data":
|
|
69
|
+
payload_acc.append(int(cmd["payload"]))
|
|
70
|
+
case "Sr":
|
|
71
|
+
if op == "write":
|
|
72
|
+
i2c = i2c.write(payload_acc)
|
|
73
|
+
op = ""
|
|
74
|
+
payload_acc.clear()
|
|
75
|
+
i2c = i2c.restart()
|
|
76
|
+
case "Read":
|
|
77
|
+
i2c = i2c.read(int(cmd["num_bytes"]))
|
|
78
|
+
case "P":
|
|
79
|
+
if op == "write":
|
|
80
|
+
i2c = i2c.write(payload_acc)
|
|
81
|
+
return i2c.stop()
|
|
82
|
+
|
|
83
|
+
raise ValueError("Unable to deserialize I2C transaction from provided string")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class I2CStopStart:
|
|
87
|
+
def __init__(self, i2c: "I2CTransactionBuilder"):
|
|
88
|
+
self._i2c = i2c
|
|
89
|
+
|
|
90
|
+
def stop(self) -> I2CTransaction:
|
|
91
|
+
self._i2c._i2c_commands.append(P())
|
|
92
|
+
return I2CTransaction(self._i2c)
|
|
93
|
+
|
|
94
|
+
def restart(self) -> "I2CAddress":
|
|
95
|
+
self._i2c._i2c_commands.append(Sr())
|
|
96
|
+
return I2CAddress(self._i2c)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class I2CReadWrite:
|
|
100
|
+
def __init__(self, i2c: "I2CTransactionBuilder"):
|
|
101
|
+
self._i2c = i2c
|
|
102
|
+
|
|
103
|
+
def read(self, number_of_bytes: int) -> I2CStopStart:
|
|
104
|
+
self._i2c._i2c_commands.append(Read(number_of_bytes))
|
|
105
|
+
return I2CStopStart(self._i2c)
|
|
106
|
+
|
|
107
|
+
def write(self, data: int | list[int]) -> I2CStopStart:
|
|
108
|
+
self._i2c._i2c_commands.append(W())
|
|
109
|
+
if isinstance(data, int):
|
|
110
|
+
self._i2c._i2c_commands.append(Data(data))
|
|
111
|
+
else:
|
|
112
|
+
for b in data:
|
|
113
|
+
self._i2c._i2c_commands.append(Data(b))
|
|
114
|
+
return I2CStopStart(self._i2c)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class I2CAddress:
|
|
118
|
+
def __init__(self, i2c: "I2CTransactionBuilder"):
|
|
119
|
+
self._i2c = i2c
|
|
120
|
+
|
|
121
|
+
def address(self, device_address: int = -1) -> I2CReadWrite:
|
|
122
|
+
self._i2c._i2c_commands.append(Address(device_address))
|
|
123
|
+
return I2CReadWrite(self._i2c)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class I2CTransactionBuilder:
|
|
127
|
+
def __init__(self):
|
|
128
|
+
self._i2c_commands: list[Command] = []
|
|
129
|
+
|
|
130
|
+
def start(self) -> I2CAddress:
|
|
131
|
+
new_root = I2CTransactionBuilder()
|
|
132
|
+
new_root._i2c_commands.append(S())
|
|
133
|
+
return I2CAddress(new_root)
|
|
134
|
+
|
|
135
|
+
def __repr__(self) -> str:
|
|
136
|
+
return ".".join(str(c) for c in self._i2c_commands)
|
i2c_api/log.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from bitstring import Bits
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class I2CTransactionElement:
|
|
5
|
+
def __repr__(self) -> str:
|
|
6
|
+
return f"{self.__class__.__name__}()"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class START(I2CTransactionElement):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class STOP(I2CTransactionElement):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RESTART(I2CTransactionElement):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class READ(I2CTransactionElement):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class WRITE(I2CTransactionElement):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ACK(I2CTransactionElement):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class NACK(I2CTransactionElement):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DATA_MOSI(I2CTransactionElement):
|
|
38
|
+
__match_args__ = ("payload",)
|
|
39
|
+
|
|
40
|
+
def __init__(self, payload: Bits):
|
|
41
|
+
self.payload = payload
|
|
42
|
+
|
|
43
|
+
def __repr__(self) -> str:
|
|
44
|
+
return f"{self.__class__.__name__}({self.payload})"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class DATA_MISO(I2CTransactionElement):
|
|
48
|
+
__match_args__ = ("payload",)
|
|
49
|
+
|
|
50
|
+
def __init__(self, payload: Bits):
|
|
51
|
+
self.payload = payload
|
|
52
|
+
|
|
53
|
+
def __repr__(self) -> str:
|
|
54
|
+
return f"{self.__class__.__name__}({self.payload})"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class I2CMessage:
|
|
58
|
+
START = START()
|
|
59
|
+
STOP = STOP()
|
|
60
|
+
RESTART = RESTART()
|
|
61
|
+
READ = READ()
|
|
62
|
+
WRITE = WRITE()
|
|
63
|
+
ACK = ACK()
|
|
64
|
+
NACK = NACK()
|
|
65
|
+
DATA_MOSI = DATA_MOSI
|
|
66
|
+
DATA_MISO = DATA_MISO
|
i2c_api/logger.py
ADDED
i2c_api/master.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from functools import reduce
|
|
4
|
+
|
|
5
|
+
from bitstring import BitArray, Bits
|
|
6
|
+
|
|
7
|
+
from i2c_api.commands import Address, P
|
|
8
|
+
from i2c_api.exec_results import ExecResults
|
|
9
|
+
from i2c_api.language import I2CTransaction, I2CTransactionBuilder
|
|
10
|
+
from i2c_api.log import I2CMessage, I2CTransactionElement
|
|
11
|
+
from i2c_api.logger import I2CLogger
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DummyI2CLogger(I2CLogger):
|
|
15
|
+
def log_message(self, message: list[I2CTransactionElement]):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class RegisterAddress:
|
|
21
|
+
address: int
|
|
22
|
+
bus_width_in_bytes: int
|
|
23
|
+
|
|
24
|
+
def __post_init__(self):
|
|
25
|
+
if self.address < 0 or self.address > (pow(2, self.bus_width_in_bytes * 8) - 1):
|
|
26
|
+
raise ValueError(f"Register address 0x{self.address:02X} is outside of valid range")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class I2CMaster(ABC):
|
|
30
|
+
def __init__(self, logger: I2CLogger | None = None):
|
|
31
|
+
self.__logger: I2CLogger = DummyI2CLogger() if logger is None else logger
|
|
32
|
+
|
|
33
|
+
@staticmethod
|
|
34
|
+
def __pad_up_to_bytes(data: BitArray, num_bytes: int | None) -> BitArray:
|
|
35
|
+
if num_bytes is None:
|
|
36
|
+
if len(data) % 8 != 0:
|
|
37
|
+
data.prepend(BitArray.from_zeros(8 - len(data) % 8))
|
|
38
|
+
return data
|
|
39
|
+
elif len(data) <= num_bytes * 8:
|
|
40
|
+
data.prepend(BitArray.from_zeros(num_bytes * 8 - len(data)))
|
|
41
|
+
return data
|
|
42
|
+
else:
|
|
43
|
+
raise ValueError(f"Input bit array is larger then pad_up_to_num_bytes={num_bytes}")
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def mk_payload(data: Bits | str | int | list[int], pad_up_to_num_bytes: int | None = None) -> BitArray:
|
|
47
|
+
"""
|
|
48
|
+
Creates BitArray to be used as a payload in i2c write operations from `data` argument.
|
|
49
|
+
If `pad_up_to_num_bytes` is None, then returned value will be padded to the next nearest number of bytes to
|
|
50
|
+
ensure that returned value is integer multiple of 8 bits.
|
|
51
|
+
|
|
52
|
+
If data is str then pass, then construct BitArray(data). For example, you can pass "`0b10010`" as a string.
|
|
53
|
+
If data is Bits, then simply wrap it in BitArray.
|
|
54
|
+
If data is int, then it is interpreted as unsigned value of one byte
|
|
55
|
+
if data is list[int], then that is assumed to be a list of bytes.
|
|
56
|
+
"""
|
|
57
|
+
if isinstance(data, int):
|
|
58
|
+
return I2CMaster.__pad_up_to_bytes(BitArray(f"uint:8={data}"), pad_up_to_num_bytes)
|
|
59
|
+
elif isinstance(data, list):
|
|
60
|
+
return I2CMaster.__pad_up_to_bytes(BitArray("".join([f"uint:8={a}," for a in data])), pad_up_to_num_bytes)
|
|
61
|
+
elif isinstance(data, (str, Bits)):
|
|
62
|
+
return I2CMaster.__pad_up_to_bytes(BitArray(data), pad_up_to_num_bytes)
|
|
63
|
+
else:
|
|
64
|
+
raise TypeError("Invalid payload type")
|
|
65
|
+
|
|
66
|
+
def logger(self) -> I2CLogger:
|
|
67
|
+
return self.__logger
|
|
68
|
+
|
|
69
|
+
def write(
|
|
70
|
+
self,
|
|
71
|
+
address: int,
|
|
72
|
+
data: Bits | str | int | list[int],
|
|
73
|
+
num_bytes: int | None = None,
|
|
74
|
+
) -> bool:
|
|
75
|
+
"""
|
|
76
|
+
Performs write transaction sending `data` to the target device identified by `address`. At the end master will
|
|
77
|
+
issue Stop condition and will release the clock line.
|
|
78
|
+
|
|
79
|
+
:param address: i2c address of the target device
|
|
80
|
+
:param data: array of bits to send to the target device; if int or list[int], then these are assumed to be bytes;
|
|
81
|
+
If it is a string, then BitArray is constructed from that string and that is used as a payload.
|
|
82
|
+
:param num_bytes: number of bytes to send or if None, then send all bits in `data` padded with zero bits to fit
|
|
83
|
+
payload into fixed number of bytes. Raises ValueError if num_bytes is not None and is less than data width.
|
|
84
|
+
:return: True or False indicating if write succeeded, which is that client responded with ACK bits.
|
|
85
|
+
"""
|
|
86
|
+
log_message = [I2CMessage.START, I2CMessage.DATA_MOSI(BitArray(f"uint:7={address}")), I2CMessage.WRITE]
|
|
87
|
+
data_out: list[Bits] = [BitArray(f"uint:8={x}") for x in I2CMaster.mk_payload(data, num_bytes).tobytes()]
|
|
88
|
+
try:
|
|
89
|
+
data, is_success = (
|
|
90
|
+
I2CTransactionBuilder().start().address(address).write([b.uint for b in data_out]).stop().exec(self)
|
|
91
|
+
)
|
|
92
|
+
if is_success:
|
|
93
|
+
log_message.append(I2CMessage.ACK)
|
|
94
|
+
for b in data_out:
|
|
95
|
+
log_message.extend([I2CMessage.DATA_MOSI(b), I2CMessage.ACK])
|
|
96
|
+
else:
|
|
97
|
+
log_message.append(I2CMessage.NACK)
|
|
98
|
+
return is_success
|
|
99
|
+
finally:
|
|
100
|
+
log_message.append(I2CMessage.STOP)
|
|
101
|
+
self.logger().log_message(log_message)
|
|
102
|
+
|
|
103
|
+
def read(self, address: int, num_bytes: int = 1) -> Bits | None:
|
|
104
|
+
"""
|
|
105
|
+
Performs read transaction reading `num_bytes` (default is 1) from the target device identified by `address`.
|
|
106
|
+
At the end master will issue Stop condition and will release the clock line.
|
|
107
|
+
|
|
108
|
+
:param address: i2c address of the target device
|
|
109
|
+
:param num_bytes: number of bytes to read
|
|
110
|
+
:return: None if failed to read data from the client (that is client did not send ACK bits) or data is Bits
|
|
111
|
+
"""
|
|
112
|
+
log_message = [I2CMessage.START, I2CMessage.DATA_MOSI(BitArray(f"uint:7={address}")), I2CMessage.READ]
|
|
113
|
+
try:
|
|
114
|
+
data, is_success = I2CTransactionBuilder().start().address(address).read(num_bytes).stop().exec(self)
|
|
115
|
+
if is_success:
|
|
116
|
+
log_message.append(I2CMessage.ACK)
|
|
117
|
+
for b in data[0]:
|
|
118
|
+
log_message.extend([I2CMessage.DATA_MISO(b), I2CMessage.ACK])
|
|
119
|
+
return reduce(lambda acc, b: acc + b, data[0], BitArray())
|
|
120
|
+
else:
|
|
121
|
+
log_message.append(I2CMessage.NACK)
|
|
122
|
+
return None
|
|
123
|
+
finally:
|
|
124
|
+
log_message.append(I2CMessage.STOP)
|
|
125
|
+
self.logger().log_message(log_message)
|
|
126
|
+
|
|
127
|
+
def exec(self, transaction: I2CTransaction, device_address: int = -1) -> ExecResults:
|
|
128
|
+
"""
|
|
129
|
+
Executes I2C commands in a single transaction and returns a named tuple `ExecResults` where first value is list
|
|
130
|
+
of lists of read bytes if any and second value is True or False indicating if transaction completed successfully.
|
|
131
|
+
Unsuccessful completion usual means that slave device responded with NACK at some point during communication
|
|
132
|
+
between master and the slave. Each sub-list within the list corresponds contiguous sequence of read bytes coming
|
|
133
|
+
from the slave.
|
|
134
|
+
"""
|
|
135
|
+
if not isinstance(transaction, I2CTransaction):
|
|
136
|
+
raise ValueError("transaction argument must be instance of I2CTransaction")
|
|
137
|
+
elif transaction._i2c._i2c_commands == [] or not isinstance(transaction._i2c._i2c_commands[-1], P):
|
|
138
|
+
raise ValueError("Unable to execute incomplete transaction")
|
|
139
|
+
elif device_address == -1:
|
|
140
|
+
for c in transaction._i2c._i2c_commands:
|
|
141
|
+
if isinstance(c, Address) and c.address == -1:
|
|
142
|
+
raise ValueError(
|
|
143
|
+
"Some Address(...) commands are given without the address. "
|
|
144
|
+
"Thus, argument `address` must be provided."
|
|
145
|
+
)
|
|
146
|
+
return self._exec(transaction, device_address)
|
|
147
|
+
|
|
148
|
+
@abstractmethod
|
|
149
|
+
def _exec(self, transaction: I2CTransaction, device_address: int = -1) -> ExecResults:
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
def read_register(
|
|
153
|
+
self,
|
|
154
|
+
address: int,
|
|
155
|
+
register: RegisterAddress | int,
|
|
156
|
+
num_bytes: int = 1,
|
|
157
|
+
use_restart: bool = True,
|
|
158
|
+
) -> Bits | None:
|
|
159
|
+
"""
|
|
160
|
+
Reads register from the target device identified by `address`. This is a compound operation where we
|
|
161
|
+
send first `write(address, register, num_bytes=1)` followed by `read(address, register, num_bytes)`.
|
|
162
|
+
If `use_restart` is True (default), then if device supports it i2c restart will be used between read and write
|
|
163
|
+
operations and if device does not support it them RuntimeError will be raised. if `use_restart` is False, then
|
|
164
|
+
two separate transactions will be used to perform register read operation with clock line being released between
|
|
165
|
+
them.
|
|
166
|
+
|
|
167
|
+
:param address: i2c address of the target device
|
|
168
|
+
:param register: address of the register to read; if int, then it is assumed that register address is one
|
|
169
|
+
byte wide and thus valid value for this field is from 0 to 255.
|
|
170
|
+
:param num_bytes: number of bytes to read; this should match length of the register
|
|
171
|
+
:param use_restart: True or False (default) indicating if we should try using I2C restart op between read and
|
|
172
|
+
write operations
|
|
173
|
+
:return: None if at any point during these transactions client sends NACK or actual Bits holding response data
|
|
174
|
+
"""
|
|
175
|
+
register_addr: RegisterAddress = (
|
|
176
|
+
RegisterAddress(address=register, bus_width_in_bytes=1) if isinstance(register, int) else register
|
|
177
|
+
)
|
|
178
|
+
register_address_bitarray: BitArray = I2CMaster.mk_payload(
|
|
179
|
+
BitArray(f"uint:{8 * register_addr.bus_width_in_bytes}={register_addr.address}"),
|
|
180
|
+
register_addr.bus_width_in_bytes,
|
|
181
|
+
)
|
|
182
|
+
reg_addr_out = [BitArray(f"uint:8={x}") for x in register_address_bitarray.tobytes()]
|
|
183
|
+
|
|
184
|
+
if not use_restart:
|
|
185
|
+
if self.write(address, register_address_bitarray):
|
|
186
|
+
return self.read(address, num_bytes)
|
|
187
|
+
else:
|
|
188
|
+
return None
|
|
189
|
+
else:
|
|
190
|
+
addr_log_message = I2CMessage.DATA_MOSI(BitArray(f"uint:7={address}"))
|
|
191
|
+
log_message = [I2CMessage.START, addr_log_message, I2CMessage.WRITE]
|
|
192
|
+
try:
|
|
193
|
+
data, is_success = (
|
|
194
|
+
I2CTransactionBuilder()
|
|
195
|
+
.start()
|
|
196
|
+
.address(address)
|
|
197
|
+
.write([b.uint for b in reg_addr_out])
|
|
198
|
+
.restart()
|
|
199
|
+
.address(address)
|
|
200
|
+
.read(num_bytes)
|
|
201
|
+
.stop()
|
|
202
|
+
.exec(self)
|
|
203
|
+
)
|
|
204
|
+
if is_success:
|
|
205
|
+
log_message.append(I2CMessage.ACK)
|
|
206
|
+
for b in reg_addr_out:
|
|
207
|
+
log_message.extend([I2CMessage.DATA_MOSI(b), I2CMessage.ACK])
|
|
208
|
+
log_message.extend([I2CMessage.RESTART, addr_log_message, I2CMessage.READ, I2CMessage.ACK])
|
|
209
|
+
for b in data[0]:
|
|
210
|
+
log_message.extend([I2CMessage.DATA_MISO(b), I2CMessage.ACK])
|
|
211
|
+
return reduce(lambda acc, b: acc + b, data[0], BitArray())
|
|
212
|
+
else:
|
|
213
|
+
log_message.append(I2CMessage.NACK)
|
|
214
|
+
return None
|
|
215
|
+
finally:
|
|
216
|
+
log_message.append(I2CMessage.STOP)
|
|
217
|
+
self.logger().log_message(log_message)
|
|
218
|
+
|
|
219
|
+
def write_register(
|
|
220
|
+
self,
|
|
221
|
+
address: int,
|
|
222
|
+
register: RegisterAddress | int,
|
|
223
|
+
data: Bits | str | int | list[int],
|
|
224
|
+
num_bytes: int | None = None,
|
|
225
|
+
read_back: bool = False,
|
|
226
|
+
use_restart: bool = True,
|
|
227
|
+
) -> Bits | None:
|
|
228
|
+
"""
|
|
229
|
+
Writes register to the target device. This is basically same as `write(...)` where first write byte is register
|
|
230
|
+
address and subsequent bytes are values to write into a register.
|
|
231
|
+
|
|
232
|
+
:param address: i2c address of the target device
|
|
233
|
+
:param register: address of the register to write to; if int, then it is assumed that register address is one
|
|
234
|
+
byte wide and thus valid value for this field is from 0 to 255.
|
|
235
|
+
:param data: array of bits to send to the target device; if int or list[int], then these are assumed to be
|
|
236
|
+
bytes. It can be empty list which means that i2c transaction will include only register address/command.
|
|
237
|
+
:param num_bytes: number of bytes to send or if None, then send all bits in `data` padded with zero bits to fit
|
|
238
|
+
payload into fixed number of bytes. Raises ValueError if num_bytes is not None and is less than data width.
|
|
239
|
+
:param read_back: if True, then register read operation will be performed at the end and its value returned.
|
|
240
|
+
Otherwise, if False (default), then just do write and return back to the user the same BitArray that was
|
|
241
|
+
supplied to this function as `data`.
|
|
242
|
+
:param use_restart: True or False (default) indicating if we should try using I2C restart op between write and
|
|
243
|
+
read operations. This value is applicable only of `read_back` is `True`.
|
|
244
|
+
:return: Value written into the register or None if NACK was received at any moment from the client device
|
|
245
|
+
including when performing readback or any other reason that i2c driver failed. Which means that write into
|
|
246
|
+
register might be a success but readback fail and thus None be returned.
|
|
247
|
+
"""
|
|
248
|
+
register_addr: RegisterAddress = (
|
|
249
|
+
RegisterAddress(address=register, bus_width_in_bytes=1) if isinstance(register, int) else register
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
register_value = I2CMaster.mk_payload(data, num_bytes)
|
|
253
|
+
write_data = BitArray(f"uint:{8 * register_addr.bus_width_in_bytes}={register_addr.address}") + register_value
|
|
254
|
+
if not self.write(address, write_data):
|
|
255
|
+
return None
|
|
256
|
+
elif read_back:
|
|
257
|
+
return self.read_register(address, register_addr, len(register_value.tobytes()), use_restart=use_restart)
|
|
258
|
+
else:
|
|
259
|
+
return register_value
|
|
260
|
+
|
|
261
|
+
@abstractmethod
|
|
262
|
+
def scan(self) -> list[int]:
|
|
263
|
+
"""
|
|
264
|
+
Scans for all client devices connected on this I2C bus.
|
|
265
|
+
|
|
266
|
+
:return: list of addresses of connected devices
|
|
267
|
+
"""
|
|
268
|
+
|
|
269
|
+
@abstractmethod
|
|
270
|
+
def list_pullups(self) -> list[str]:
|
|
271
|
+
"""
|
|
272
|
+
Returns list of possible configurable pullup resistor values.
|
|
273
|
+
These should be human-readable values like [20 OHm]
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
@abstractmethod
|
|
277
|
+
def set_pullup(self, pullup_value: str) -> None:
|
|
278
|
+
"""
|
|
279
|
+
Set pullup resistor value. This should be one of the strings returned by `list_pullups()` method.
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
@abstractmethod
|
|
283
|
+
def get_pullup(self) -> str:
|
|
284
|
+
"""
|
|
285
|
+
Returns currently active pullup resistor value in human-readable format.
|
|
286
|
+
"""
|
|
287
|
+
|
|
288
|
+
@abstractmethod
|
|
289
|
+
def list_clk_speeds(self) -> list[int]:
|
|
290
|
+
"""Returns list of available configurable clock speeds in KHz."""
|
|
291
|
+
|
|
292
|
+
@abstractmethod
|
|
293
|
+
def get_clk_speed(self) -> int:
|
|
294
|
+
"""Returns currently configured clock speed in KHz."""
|
|
295
|
+
|
|
296
|
+
@abstractmethod
|
|
297
|
+
def set_clk_speed(self, speed: int) -> None:
|
|
298
|
+
"""
|
|
299
|
+
Sets clock speed to `speed` value in KHz. Supplied value must be one of the returned one by
|
|
300
|
+
method `list_clk_speeds()`, if not, then RuntimeError is raised.
|
|
301
|
+
"""
|
|
302
|
+
|
|
303
|
+
@abstractmethod
|
|
304
|
+
def close(self):
|
|
305
|
+
"""
|
|
306
|
+
Some dongles require to close instance of I2CMaster. Thus make sure to call it.
|
|
307
|
+
"""
|
|
308
|
+
|
|
309
|
+
def __enter__(self):
|
|
310
|
+
return self
|
|
311
|
+
|
|
312
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
313
|
+
self.close()
|
|
314
|
+
return False
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: i2c_api
|
|
3
|
+
Version: 0.20.0
|
|
4
|
+
Summary: I2C API
|
|
5
|
+
Requires-Python: >=3.13
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: bitstring<6.0.0,>=5.0.0
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# I²C API
|
|
12
|
+
|
|
13
|
+
[](https://github.com/Brainless-Software/i2c_api/blob/master/LICENSE)
|
|
14
|
+
[](https://pypi.org/project/i2c_api/)
|
|
15
|
+
[](https://github.com/Brainless-Software/i2c_api/actions/workflows/test.yml)
|
|
16
|
+
[](https://brainless-software.github.io/i2c_api/)
|
|
17
|
+
|
|
18
|
+
Python library that provides abstract classes for [I2C](https://en.wikipedia.org/wiki/I2C) master devices (normally
|
|
19
|
+
dongles such as [I2CDriver](https://i2cdriver.com/) and similar) to communicate with I2C slaves.
|
|
20
|
+
|
|
21
|
+
It is intended to be used together with [i2c_drivers](https://github.com/Brainless-Software/i2c_drivers) library that
|
|
22
|
+
implements this API for several common USB-to-I2C dongles.
|
|
23
|
+
|
|
24
|
+
[Documentation](https://brainless-software.github.io/i2c_api/)
|
|
25
|
+
|
|
26
|
+
To add this library to your project do
|
|
27
|
+
|
|
28
|
+
```shell
|
|
29
|
+
uv add i2c_api
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
or with `i2c_drivers`
|
|
33
|
+
|
|
34
|
+
```shell
|
|
35
|
+
uv add i2c_api i2c_drivers
|
|
36
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
i2c_api/__init__.py,sha256=RremT9QF0-Nw52s4G_6BjSrnn7TxxkwMUtgrw-SqdO0,203
|
|
2
|
+
i2c_api/commands.py,sha256=amPxXaUSt2LtVmi9nMkojDwbl82Mi0oZ3cvuB-4YeVM,1883
|
|
3
|
+
i2c_api/exec_results.py,sha256=w3iwgqkBRItPt_YkMvVZvC5MGol33bwcpw8HIXUC1Eo,625
|
|
4
|
+
i2c_api/language.py,sha256=vW_7jql9mj9CeXdAhzquupYwCv9-0fcgj6-7FbUVkQ8,4655
|
|
5
|
+
i2c_api/log.py,sha256=mJZ_ud3BPGF80sPgGXWh8x_qFKbJWxJ9BMUVGF2ciLo,1145
|
|
6
|
+
i2c_api/logger.py,sha256=UYTW-En43WHs2QSfWNShW1v0PVaM2qwLFYaa0exRxBU,198
|
|
7
|
+
i2c_api/master.py,sha256=vvTY3vhEJynnDwuv-36WHxOiuB16dG1MSGOpqh4jBPc,14974
|
|
8
|
+
i2c_api-0.20.0.dist-info/licenses/LICENSE,sha256=UBiXDGNSvplE3Bx8SPXgZpdje80HPyWokuB6Tqq4EPg,1071
|
|
9
|
+
i2c_api-0.20.0.dist-info/METADATA,sha256=FoKr7qs-Kv_YelNw9dxy9DMALg89cI04tf05YTQJlWs,1344
|
|
10
|
+
i2c_api-0.20.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
i2c_api-0.20.0.dist-info/top_level.txt,sha256=oOrsQIg1xS-T_Hc1foy6vfbQs6gHzQkxA7nCBHZE7oQ,8
|
|
12
|
+
i2c_api-0.20.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dmitri Priimak
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
i2c_api
|