# i2c_api — LLM Reference `i2c_api` is a small, pure-Python library that defines an **abstract, driver-agnostic API for I2C master/controller devices** (typically USB-to-I2C dongles such as I2CDriver, MCP2221, FT232H) to talk to I2C slave/client devices. It does **not** contain a concrete hardware driver. Concrete implementations are provided by the companion package [`i2c_drivers`](https://github.com/Brainless-Software/i2c_drivers), which registers subclasses of `I2CMaster`. The library offers three levels of abstraction: 1. **Direct convenience methods** — `I2CMaster.read(...)`, `.write(...)`, `.read_register(...)`, `.write_register(...)`. 2. **A fluent transaction DSL ("I2C Language")** — build arbitrary start/restart/address/read/write/stop transactions with a type-guided chain, execute them, and serialize them to/from JSON. 3. **`I2CMaster.exec(...)`** — execute a pre-built `I2CTransaction` and get an `ExecResults` named tuple. The public API represents **master-side** functionality only; the library has no I2C slave implementation. --- ## 1. Package facts | Item | Value | |---|---| | Distribution name | `i2c-api` (`i2c_api` on PyPI) | | Import package | `i2c_api` | | Language / runtime | Python **>= 3.13** | | Runtime dependency | [`bitstring`](https://bitstring.readthedocs.io/) `>= 5.0.0, < 6.0.0` (per `pyproject.toml`) | | License | MIT | | Source layout | `src/i2c_api/` | | Tests | `tests/test_master.py`, `tests/test_language.py` (pytest) | | Docs | `docs/` (mkdocs-material) | | Repo | https://github.com/Brainless-Software/i2c_api | | Docs site | https://brainless-software.github.io/i2c_api/ | Install: ```bash uv add i2c-api # or, with concrete dongle drivers: uv add i2c-api i2c-drivers # or pip: pip install i2c-api ``` Concrete drivers supported by the companion library: I2CDriver, MCP2221, FT232H. Any other hardware can be supported by subclassing `I2CMaster`. --- ## 2. I2C concepts used by the API - The bus is a 2-wire bus: **SDA** (data) and **SCL** (clock). The master drives the clock. - A **transaction** starts with a **start** condition (`S`), contains one or more **frames**, and ends with a **stop** condition (`P`). Frames may be separated by a **restart** condition (`Sr`). - A **frame** starts with a 7-bit slave address plus one read/write bit, followed by data bytes (write) or returned bytes (read). Every byte is acknowledged by the receiver with **ACK** or **NACK**. - A **register read** is conventionally a write frame carrying the register address followed by a restart and a read frame. A **register write** is a write frame carrying the register address followed by the value bytes. - In this library, a successful operation means the slave ACKed; a NACK surfaces as `None` (reads/register operations), `False` (writes), or `is_success == False` (`exec`). The API generally does **not** raise on NACK. Formal shape of a transaction: ```ebnf transaction = S frame { Sr frame } P ; frame = read_frame | write_frame ; read_frame = address_7bits read_bit [ byte_from_slave { byte_from_slave } ] ; write_frame = address_7bits write_bit { byte_to_slave } ; ``` The transaction builder accepts exactly this shape. Each fluent call returns only a stage object exposing the next valid operations, so out-of-order sequences cannot be expressed through the fluent API; the only way to obtain an `I2CTransaction` is to finish the chain with `stop()`. --- ## 3. Module map | Module | Contents | |---|---| | `i2c_api/__init__.py` | Public re-exports and `I2CAPI_IMPL` provider registry. | | `i2c_api/master.py` | Abstract `I2CMaster` (ABC), `RegisterAddress`, `DummyI2CMaster`, `DummyI2CLogger`. | | `i2c_api/language.py` | `I2CTransaction`, `I2CTransactionBuilder`, and the chain-stage classes `I2CAddress`, `I2CReadWrite`, `I2CStopStart`. Defines a structural `I2CMaster` Protocol used for typing. | | `i2c_api/commands.py` | Transaction command objects: `S`, `Address`, `Address10`, `W`, `Data`, `Read`, `Sr`, `P` (all subclass `Command`). | | `i2c_api/exec_results.py` | `ExecResults` named tuple returned by `exec`. | | `i2c_api/logger.py` | `I2CLogger` ABC. | | `i2c_api/log.py` | Log-message element classes and the `I2CMessage` constant namespace. | | `i2c_api/provider.py` | `I2CMasterProvider` dataclass and `I2CMasterProviderDummy` registry entry. | Public names exported from `i2c_api`: ```python from i2c_api import ( ExecResults, I2CTransaction, I2CTransactionBuilder, I2CMessage, I2CLogger, I2CMaster, RegisterAddress, I2CMasterProvider, I2CAPI_IMPL, I2CMasterProviderDummy, ) ``` `DummyI2CMaster` and `DummyI2CLogger` are importable from `i2c_api.master` (not re-exported at package level). --- ## 4. `I2CMaster` — abstract master API `I2CMaster` is an `abc.ABC`. It cannot be instantiated directly; concrete subclasses implement the hardware-specific parts. It has two roles: - provide ready-made transaction helpers (`read`, `write`, `read_register`, `write_register`, `exec`); - define the contract (`_exec`, `scan`, pullups, clock speeds, `close`) that concrete drivers implement. ### 4.1 Construction and lifecycle ```python class I2CMaster(ABC): def __init__(self, port: str | None, logger: I2CLogger | None = None): ... def __repr__(self) -> str: ... # "ClassName" or "ClassName :: port" def logger(self) -> I2CLogger: ... def __enter__(self): ... # returns self def __exit__(self, exc_type, exc_val, exc_tb): ... # calls close(); returns False ``` - `port` is stored as `self.port`; it is a human-readable device path such as `"/dev/ttyUSB0"` or `"COM7"` (interpretation is driver-specific). - If `logger` is omitted, a no-op `DummyI2CLogger` is used. - Always `close()` a master (`with` blocks do this automatically) because some dongles require explicit teardown. Abstract methods that every concrete driver must implement: ```python def display_name(self) -> str: ... def _exec(self, transaction: I2CTransaction, device_address: int = -1) -> ExecResults: ... def scan(self) -> list[int]: ... def list_pullups(self) -> list[str]: ... def set_pullup(self, pullup_value: str) -> None: ... def get_pullup(self) -> str: ... def list_clk_speeds(self) -> list[int]: ... # KHz def get_clk_speed(self) -> int: ... # KHz def set_clk_speed(self, speed: int) -> None: ... def close(self): ... ``` `read`, `write`, `read_register`, `write_register`, and `exec` are concrete and implemented in terms of `_exec`, so drivers normally only implement `_exec` plus the management methods above. ### 4.2 `read(address, num_bytes=1) -> Bits | None` ```python data: Bits | None = master.read(0x42, num_bytes=2) ``` - Performs a complete transaction: `S`, address+read, `num_bytes` bytes, `P`. - Returns the received data as a `BitArray` (a `Bits` subclass), or `None` if the slave NACKed / the driver failed. - Result bit length is `num_bytes * 8` on success. - Emits a log message (see §10). ### 4.3 `write(address, data, num_bytes=None) -> bool` ```python ok: bool = master.write(0x42, data=0x10) ok = master.write(0x42, data=[0x07, 0x10]) ok = master.write(0x42, data="0b111") # 1 byte, zero-padded ok = master.write(0x42, data="0b111", num_bytes=2) ``` - Performs a complete transaction: `S`, address+write, payload bytes, `P`. - Returns `True` iff the slave ACKed, `False` on NACK/failure. Payload-type errors raise (`ValueError`/`TypeError`); a NACK does not raise. - `data` forms: - `int` — one unsigned byte (0..255). - `list[int]` — one byte per element (each 0..255). - `str` — bitstring literal understood by `BitArray`, e.g. `"0b10010"`, `"0x07"`. - `Bits`/`BitArray` — used as-is. - `num_bytes` pads the payload on the **left** (prepends zero bits) to exactly `num_bytes * 8` bits. With `num_bytes=None`, the payload is padded on the left to the nearest whole byte. If the payload is wider than `num_bytes * 8`, `ValueError` is raised. - An empty `list` is legal and produces a transaction with no data bytes (address/write only). Detailed payload rules are in §9. ### 4.4 `exec(transaction, device_address=-1) -> ExecResults` ```python results: ExecResults = master.exec(transaction) results = master.exec(transaction, 0x42) ``` - Executes a complete `I2CTransaction` as one bus transaction (one `S ... P`, possibly with `Sr`). - Validates that: - `transaction` is an `I2CTransaction`, else `ValueError`; - the command list is non-empty and ends with `P`, else `ValueError("Unable to execute incomplete transaction")`; - if `device_address == -1`, no `Address(-1)` ("auto") commands remain, else `ValueError`. - If `device_address != -1`, it is passed to `_exec`; **the driver is responsible for applying it to auto-address commands**. Use `I2CTransaction.exec(...)` if you want the library to substitute addresses before dispatching (see §7.5). - Returns `ExecResults(data, is_success)` (§8). ### 4.5 Register access ```python @dataclass(frozen=True, slots=True) class RegisterAddress: address: int bus_width_in_bytes: int # __post_init__: raises ValueError unless # 0 <= address <= 2**(bus_width_in_bytes*8) - 1 ``` `RegisterAddress` describes the register number and how many bytes are used to transmit it. `bus_width_in_bytes=1` means a one-byte register address. It does not validate `bus_width_in_bytes` beyond the range calculation. #### `read_register` ```python def read_register( address: int, register: RegisterAddress | int, num_bytes: int = 1, use_restart: bool = True, ) -> Bits | None: ... ``` - Writing an `int` for `register` implies `RegisterAddress(register, bus_width_in_bytes=1)`; valid 0..255. - Semantics: 1. write the register address to the slave; 2. read `num_bytes` bytes. - With `use_restart=True` (default), steps 1 and 2 are one transaction joined by `Sr`. Drivers that cannot do restart raise `RuntimeError`. - With `use_restart=False`, two separate transactions are used (`write_register`-style write, then `read`), with the bus released between them. - Returns the register value as `BitArray`, or `None` on NACK/failure. ```python from i2c_api import RegisterAddress value = master.read_register(0x42, 0x07) # 1-byte register addr, 1 byte result value = master.read_register(0x42, 0x07, num_bytes=4) # 4-byte result value = master.read_register(0x42, RegisterAddress(0x1234, 2)) # 2-byte register addr value = master.read_register(0x42, 0x07, use_restart=False) # dongle without Sr support ``` #### `write_register` ```python def write_register( address: int, register: RegisterAddress | int, data: Bits | str | int | list[int], num_bytes: int | None = None, read_back: bool = False, use_restart: bool = True, ) -> Bits | None: ... ``` - Sends `register_address_bytes + payload` in one write transaction. - `register` follows the same `int`/`RegisterAddress` rules as `read_register`. - `data` accepts the same forms as `write` (int, list of bytes, bitstring literal, `Bits`). - `data=[]` is allowed: only the register address/command is sent. - Returns: - if `read_back=False` (default): the payload written, as a `BitArray`; - if `read_back=True`: the value read back via `read_register` (so `None` may mean the write worked but the readback failed); - `None` if the write (or readback) was NACKed/failed. - `use_restart` only matters when `read_back=True` and is forwarded to `read_register`. ```python written = master.write_register(0x42, 0x07, 0x11) # BitArray 0x11 written = master.write_register(0x42, 0x07, [0x11, 0x22]) checked = master.write_register(0x42, 0x07, 0x11, read_back=True) # write then Sr+read checked = master.write_register(0x42, 0x07, 0x11, read_back=True, use_restart=False) ``` ### 4.6 Bus management ```python master.scan() # -> list[int] of responding 7-bit addresses master.list_pullups() # -> list[str], human-readable, e.g. ["disabled", "20 kOhm"] master.set_pullup("20 kOhm") # value must be from list_pullups() master.get_pullup() # -> currently active pullup string master.list_clk_speeds() # -> list[int] in KHz, e.g. [100, 400] master.get_clk_speed() # -> int KHz master.set_clk_speed(400) # must be in list_clk_speeds(), else RuntimeError ``` These are abstract: exact values and available settings are driver-specific. Contract: `set_clk_speed` raises `RuntimeError` for an unsupported speed; `set_pullup` expects one of `list_pullups()`. ### 4.7 Auto-instantiation from config ```python master = I2CMaster.new_auto_instance() ``` Static method that builds a concrete master from `.i2c_driver.json`: - Looks for `.i2c_driver.json` in the **current working directory** first, then in the **home directory** (`$HOME/.i2c_driver.json`). - If neither exists, raises `ValueError`. - File format: ```json { "class": "i2c_drivers.I2CMasterI2CDriver", "params": { "port": "/dev/ttyUSB0" } } ``` - `"class"` is required: fully-qualified `module.ClassName` (split on the final dot; module imported with `importlib.import_module`, class fetched with `getattr`). - `"params"` is optional and is passed as keyword arguments to the class constructor. - The class must implement `I2CMaster`. This lets application code depend only on `i2c_api` and swap dongles by editing JSON, with no code changes. ### 4.8 Implementing a concrete driver Minimal skeleton: ```python from i2c_api import I2CMaster, I2CTransaction, ExecResults from i2c_api.commands import Address, Data, P, Read, S, Sr, W from bitstring import BitArray class MyMaster(I2CMaster): def __init__(self, port: str, logger=None): super().__init__(port, logger) # open serial/USB device here def display_name(self) -> str: return "Acme :: MyI2CDongle" def _exec(self, transaction: I2CTransaction, device_address: int = -1) -> ExecResults: commands = transaction._i2c._i2c_commands # internal command list # 1. If device_address != -1, replace any Address(-1) with it. # 2. Translate S/Sr/Address/W/Data/Read/P into dongle operations. # 3. Return ExecResults(data=[[...]], is_success=...). # Outer list: one entry per Read(...) command. # Inner list: one BitArray (or byte value — see §12) per byte. return ExecResults(data=[], is_success=True) def scan(self) -> list[int]: return [] def list_pullups(self) -> list[str]: return ["disabled"] def set_pullup(self, pullup_value: str) -> None: pass def get_pullup(self) -> str: return "disabled" def list_clk_speeds(self) -> list[int]: return [100] def get_clk_speed(self) -> int: return 100 def set_clk_speed(self, speed: int) -> None: pass def close(self): pass ``` `transaction._i2c._i2c_commands` is private but is the intended interchange format for drivers: a list of `Command` instances from `i2c_api.commands`. `_exec` is called only for complete transactions (non-empty, ends in `P`) when invoked via `I2CMaster.exec`. --- ## 5. The "I2C Language" — fluent transaction builder `I2CTransactionBuilder` provides a chain whose stage types only expose valid next operations, so invalid transaction sequences cannot be assembled. ```python class I2CTransactionBuilder: def __init__(self, i2c_master: I2CMaster | None = None, default_device_address: int = -1): ... def start(self) -> I2CAddress: ... def __repr__(self) -> str: ... ``` Chain stages: | Stage class | Methods | Returns | |---|---|---| | `I2CAddress` | `address(device_address: int = -1)` | `I2CReadWrite` | | `I2CReadWrite` | `read(number_of_bytes: int)` | `I2CStopStart` | | `I2CReadWrite` | `write(data: int \| list[int])` | `I2CStopStart` | | `I2CStopStart` | `restart()` | `I2CAddress` | | `I2CStopStart` | `stop()` | `I2CTransaction` | `I2CTransactionBuilder.start()` returns a **new** builder stage (copies the master and default address), so it can be reused safely: ```python from i2c_api import I2CTransactionBuilder i2c = I2CTransactionBuilder() read_reg = i2c.start().address(0x42).write(0x07).restart().address(0x42).read(1).stop() print(read_reg) # S().Address(0x42).W().Data(0x07).Sr().Address(0x42).Read(1).P() ``` `write` in the language accepts only `int` (one byte) or `list[int]` (bytes); for `str`/`Bits` payloads use `I2CMaster.write(...)` or construct `Data` commands manually. It appends a `W()` and one `Data(...)` per byte. `address()` with no argument appends `Address(-1)`, rendered `Address(auto)`, to be filled at execution time: ```python tr = i2c.start().address().write([0x07, 0x11]).stop() print(tr) # S().Address(auto).W().Data(0x07).Data(0x11).P() ``` ### 5.1 Command objects All in `i2c_api.commands`; all have `__repr__()` and `to_dict()`: | Class | Constructor | `repr` example | `to_dict()` | |---|---|---|---| | `S` | `S()` | `S()` | `{"cmd": "S"}` | | `Address` | `Address(address: int)` | `Address(0x42)`, `Address(auto)` for `-1` | `{"cmd": "Address", "address": ""}` | | `Address10` | `Address10(address: int)` | `Address10(0x42)` | `{"cmd": "Address10", "address": ""}` | | `W` | `W()` | `W()` | `{"cmd": "W"}` | | `Data` | `Data(data: int)` | `Data(0x07)` | `{"cmd": "Data", "payload": ""}` | | `Read` | `Read(num_bytes: int)` | `Read(2)` | `{"cmd": "Read", "num_bytes": ""}` | | `Sr` | `Sr()` | `Sr()` | `{"cmd": "Sr"}` | | `P` | `P()` | `P()` | `{"cmd": "P"}` | `Address10` exists but is not exposed by the builder and is not handled by JSON deserialization; it is currently effectively unused/internal. ### 5.2 Executing a transaction Two equivalent call styles: ```python results = master.exec(transaction) # or master.exec(transaction, 0x42) results = transaction.exec(master) # or transaction.exec(master, 0x42) ``` `I2CTransaction.exec(master=None, device_address=-1)`: - If `master` is omitted, uses the master supplied to `I2CTransactionBuilder(...)`; if none, raises `ValueError`. - If `device_address` is `-1`, uses the builder's `default_device_address` if set. - If the resolved address is still `-1` and any `Address(-1)` remains, raises `ValueError` with: *"Some Address(...) commands are given without the address. Thus, argument `device_address` must be provided."* - If an address is available, it **auto-fills only the unfilled** `Address(-1)` commands (explicit addresses are preserved) by creating a new transaction, then calls `master.exec(...)`. - The builder's default address mechanism: ```python i2c = I2CTransactionBuilder(master, default_device_address=0x42) tr = i2c.start().address().write(0x07).stop() res = tr.exec() # auto address becomes 0x42 ``` ### 5.3 Repr `repr(transaction)` / `str(transaction)` is the dot-joined command list, e.g.: ``` S().Address(0x42).W().Data(0x07).Sr().Address(0x42).Read(1).P() ``` `Data` is formatted as two-digit uppercase hex; `Address` as `0xNN` or `auto`. --- ## 6. JSON serialization of transactions `I2CTransaction` has static methods: ```python # static methods on I2CTransaction def to_json(transaction: I2CTransaction) -> str: ... def from_json(json_str: str) -> I2CTransaction: ... ``` The JSON representation is a flat list of command dictionaries (`to_dict()` output). Example: ```python tr = i2c.start().address().write([0x07, 0x11]).restart().address(0x44).read(2).stop() I2CTransaction.to_json(tr) ``` produces (whitespace added here for readability): ```json [ {"cmd": "S"}, {"cmd": "Address", "address": "-1"}, {"cmd": "W"}, {"cmd": "Data", "payload": "7"}, {"cmd": "Data", "payload": "17"}, {"cmd": "Sr"}, {"cmd": "Address", "address": "68"}, {"cmd": "Read", "num_bytes": "2"}, {"cmd": "P"} ] ``` Notes: - All numeric fields are encoded as **decimal strings**. - `W` and each `Data` are separate entries; `from_json` accumulates `Data` payloads and flushes them as a single `write([...])` when it encounters `Sr` or `P`. - `from_json` requires a trailing `P`; otherwise it raises `ValueError("Unable to deserialize I2C transaction from provided string")`. - It ignores any commands after `P` (it returns at `P`). - It does not handle `Address10` (falls through the `match`). - With `Address(-1)` round-tripped, `Address(auto)` is preserved and still requires an address at execution time. - `str(tr1) == str(I2CTransaction.from_json(I2CTransaction.to_json(tr1)))` holds for builder-produced transactions (covered by tests). --- ## 7. `ExecResults` ```python class ExecResults(NamedTuple): data: list[list[BitArray]] is_success: bool def values(self) -> list[BitArray]: ... def pp(self) -> str: ... ``` - **Field order is `(data, is_success)`**, i.e. `ExecResults(data, is_success)`. `results.data`, `results.is_success`, or tuple unpacking/matching `data, ok = results` work. (`docs/api.md` lists `is_success` first; the code order is authoritative.) - `data`: outer list has **one entry per `Read(n)` command** in the transaction; each inner list has one entry per byte read. On failure it may still be non-empty (partial reads). - `values()`: combines each inner byte list into one `BitArray` per read command, returning `list[BitArray]`. Implementation wraps each element as `BitArray(f"uint:8={x}")`, so elements must be integer-like (see §12). - `pp()`: pretty string, e.g. ``` ExecResults(values=['0b0000001000000011'], is_success=True) ``` Also goes through `values()`. Pattern-matching example (from docs): ```python match results: case ExecResults(_, True): print("success:", results.values()[0]) case ExecResults(_, False): print("transaction failed") ``` --- ## 8. Logging The library can report the *intended* bus activity to a user-supplied logger. It is advisory only: many dongles cannot report exactly where a NACK occurred. ```python from i2c_api import I2CLogger class PrintLogger(I2CLogger): def log_message(self, message): print(" ".join(repr(m) for m in message)) master = SomeConcreteMaster("/dev/ttyUSB0", logger=PrintLogger()) ``` - `I2CLogger` is an ABC with one method: `log_message(message: list[I2CTransactionElement]) -> None`. - `DummyI2CLogger` (in `i2c_api.master`) is the default no-op logger. - `I2CMaster.read`, `.write`, `.read_register`, `.write_register` emit one log message each. **`.exec()` does not log** — it expects the driver to handle logging if desired. - Log elements are classes in `i2c_api.log`; `I2CMessage` holds ready-made singletons and two classes: ```python I2CMessage.START # START() I2CMessage.STOP # STOP() I2CMessage.RESTART # RESTART() I2CMessage.READ # READ() I2CMessage.WRITE # WRITE() I2CMessage.ACK # ACK() I2CMessage.NACK # NACK() I2CMessage.DATA_MOSI # class; construct with Bits, e.g. I2CMessage.DATA_MOSI(BitArray("uint:8=7")) I2CMessage.DATA_MISO # class; construct with Bits ``` `DATA_MOSI`/`DATA_MISO` instances have a `.payload: Bits` attribute and `__match_args__ = ("payload",)`. --- ## 9. Payload conversion (`I2CMaster.mk_payload`) `I2CMaster.mk_payload(data, pad_up_to_num_bytes=None) -> BitArray` is a public static helper used by `write`, `write_register`, and `read_register`. | Input | Interpretation | Example | |---|---|---| | `int` | one unsigned byte (0..255) | `mk_payload(7)` → `0x07` | | `list[int]` | one byte per element (each 0..255); empty list is allowed | `mk_payload([7, 10])` → `0x070A` | | `str` | `BitArray` literal syntax | `mk_payload("0b111")` → `0x07` | | `Bits` / `BitArray` | used as-is | `mk_payload(Bits("0x02"))` → `0x02` | | anything else | `TypeError("Invalid payload type")` | — | Padding behavior (`__pad_up_to_bytes`): - `pad_up_to_num_bytes is None`: if bit length is not a multiple of 8, **prepend** zero bits to reach the next whole byte. - `pad_up_to_num_bytes=N`: **prepend** zero bits to make exactly `N * 8` bits. - If the payload is already wider than `N * 8`, `ValueError` is raised. - Padding is on the **left** (most-significant side): `"0b111"` → `0b00000111`; `"0b111", num_bytes=2` → `0b0000000000000111` (`0x0007`). - Invalid byte values (negative, >255) raise `ValueError` from `bitstring`. `read_register` uses the same helper to encode the register address at `bus_width_in_bytes * 8` bits. --- ## 10. Providers and driver discovery ```python @dataclass(frozen=True) class I2CMasterProvider: make: str model: str new_i2c_master: Callable[[str, I2CLogger], I2CMaster] ports_required: bool list_ports: Callable[[], Optional[list[str]]] = lambda: None def make_and_model(self) -> str: ... # "make :: model" ``` - `new_i2c_master(port, logger)` is a factory for a concrete master. - `ports_required` indicates whether a port must be chosen. - `list_ports()` optionally enumerates available ports (`None` if not applicable). - At package import, `I2CAPI_IMPL` is a module-level mutable list containing `I2CMasterProviderDummy` (the demo provider). Driver packages are expected to append their providers to `i2c_api.I2CAPI_IMPL`, enabling GUI/CLI discovery. This is a convention, not enforced by the library. ```python import i2c_api from i2c_api import I2CMasterProvider i2c_api.I2CAPI_IMPL.append( I2CMasterProvider( make="Acme", model="I2C-9000", new_i2c_master=lambda port, logger: MyMaster(port, logger), ports_required=True, ) ) ``` `I2CMasterProviderDummy`: ```python I2CMasterProviderDummy = I2CMasterProvider( make="Demo", model="DummyI2CDongle", new_i2c_master=lambda port, logger: DummyI2CMaster(port, logger), ports_required=False, ) ``` --- ## 11. Dummy implementations `DummyI2CMaster` (in `i2c_api.master`) is a stub useful for tests/smoke checks: - `display_name()` → `"Demo :: DummyI2CDongle"` - `scan()` → `[]` - `list_pullups()` / `get_pullup()` → `["disabled"]` / `"disabled"` - `list_clk_speeds()` / `get_clk_speed()` → `[100]` / `100` - `set_pullup` / `set_clk_speed` / `close` → no-op - `_exec(...)` is unimplemented (`pass`, returns `None`), so `exec`, `read`, `write`, and register helpers will fail with `TypeError` if used. It is not a simulated bus. `DummyI2CLogger` is a no-op `I2CLogger` and is the default when no logger is supplied. --- ## 12. Behavior notes, edge cases, and doc/code discrepancies These are important when generating code against this library: 1. **`ExecResults` field order is `(data, is_success)`**, not `(is_success, data)` as listed in `docs/api.md`. Construct with `ExecResults(data=..., is_success=...)`. 2. **`ExecResults.values()` byte handling is inconsistent with `I2CMaster.read()`**: - `values()`/`pp()` execute `BitArray(f"uint:8={x}")` on each inner element, so each `x` must be an `int` (e.g. `2`). - `I2CMaster.read()` iterates the inner elements as `BitArray`s (it concatenates them with `+` and passes them to `DATA_MISO`), so it expects `BitArray` elements. - Therefore a driver returning `BitArray` per byte makes `.values()` raise `ValueError` (`invalid literal for int()`), while a driver returning `int` per byte makes `.read()` fail. Treat the inner representation as driver-defined and check the specific driver; prefer iterating `results.data` directly if unsure. The type annotation says `list[list[BitArray]]`. 3. **`I2CMaster` is abstract** (`ABC`). Snippets in the docs use `master = I2CMaster()` only as shorthand; it cannot be instantiated. Obtain an instance from `i2c_drivers`, a custom subclass, or `I2CMaster.new_auto_instance()`. 4. **`read_register` default is `use_restart=True`.** If the dongle does not support restart, it raises `RuntimeError`; pass `use_restart=False` to use two transactions. (`docs/api.md` text sometimes says the default is `False`; the signature is authoritative.) 5. **`write_register(read_back=True)` also defaults to `use_restart=True`** via its pass-through to `read_register`. Set it explicitly for restart-less dongles. 6. **Register `int` shorthand is one byte only.** Use `RegisterAddress(address, bus_width_in_bytes)` for wider register addresses. `RegisterAddress` validates the address fits the width. 7. **Padding is left-aligned (leading zero bits)**, not trailing. This matters for small integer payloads. 8. **`num_bytes` smaller than the payload raises `ValueError`**, it does not truncate. 9. **`I2CMaster.exec` does not auto-fill `Address(-1)`**; it only validates and passes `device_address` to `_exec`. `I2CTransaction.exec` does the auto-fill. Both documented call styles work, but only if the driver honors `device_address` in `_exec`. 10. **`Address10` is defined but unsupported** by the fluent builder (`address()` always creates `Address`) and by `from_json`. 11. **`DummyI2CMaster._exec` returns `None`** (no simulated transaction execution). 12. **NACKs are values, not exceptions**: `read`/register reads return `None`, `write` returns `False`, `exec` returns `is_success=False`. Programming/payload errors raise `ValueError`/`TypeError`; missing config raises `ValueError`; incomplete transactions raise `ValueError`. 13. **`I2CMaster.new_auto_instance()` only checks CWD and `$HOME`**, in that order; the first file found wins. It does not search parent directories or use environment variables. 14. **`I2CMaster.write`/`read` create their own transactions internally**; a subclass should implement only `_exec` and not override them unless it needs different behavior. 15. **Logging is advisory and excludes `exec`.** Logs may not reflect the true wire-level sequence. 16. `src/i2capi.egg-info/PKG-INFO` is stale (shows `bitstring>=4.4.0`); `pyproject.toml` is authoritative (`>=5.0.0,<6.0.0`). --- ## 13. Complete examples ### 13.1 Configure and open a dongle ```json // .i2c_driver.json in the project directory or $HOME { "class": "i2c_drivers.I2CMasterI2CDriver", "params": { "port": "/dev/ttyUSB0" } } ``` ```python from i2c_api import I2CMaster with I2CMaster.new_auto_instance() as master: print(master.display_name(), master.port) print("devices:", [hex(a) for a in master.scan()]) ``` ### 13.2 Direct read/write ```python from bitstring import Bits from i2c_api import I2CMaster master = I2CMaster.new_auto_instance() try: data: Bits | None = master.read(0x42, num_bytes=2) if data is None: print("read failed (NACK)") else: print(data.hex, data.bin) if not master.write(0x42, [0x07, 0x11]): print("write failed (NACK)") # 3-bit payload, left-padded to 2 bytes: 0x0007 master.write(0x42, "0b111", num_bytes=2) finally: master.close() ``` ### 13.3 Register access ```python from i2c_api import RegisterAddress # Read one byte from register 0x07 on device 0x42 value = master.read_register(0x42, 0x07) # Read 4 bytes from a 2-byte register address, without restart value = master.read_register( 0x42, RegisterAddress(address=0x1234, bus_width_in_bytes=2), num_bytes=4, use_restart=False, ) # Write 0x11 into register 0x07 and verify written = master.write_register(0x42, register=0x07, data=0x11) readback = master.write_register(0x42, register=0x07, data=0x11, read_back=True) ``` ### 13.4 Fluent transaction: register read and auto address ```python from i2c_api import I2CTransactionBuilder i2c = I2CTransactionBuilder() # Explicit address tr = i2c.start().address(0x42).write(0x07).restart().address(0x42).read(1).stop() print(tr) # S().Address(0x42).W().Data(0x07).Sr().Address(0x42).Read(1).P() results = tr.exec(master) if results.is_success: reg_value = results.data[0][0] # first read command, first byte print("register:", reg_value) else: print("NACK") # Auto address, supplied at execution time tr2 = i2c.start().address().write([0x07, 0x11]).stop() print(tr2) # S().Address(auto).W().Data(0x07).Data(0x11).P() results2 = tr2.exec(master, 0x42) assert results2.is_success ``` ### 13.5 Default address in the builder ```python from i2c_api import I2CTransactionBuilder i2c = I2CTransactionBuilder(master, default_device_address=0x42) tr = i2c.start().address().read(2).stop() res = tr.exec() # no address argument needed print(res.is_success) ``` ### 13.6 Serialize a transaction ```python from i2c_api import I2CTransaction, I2CTransactionBuilder tr = ( I2CTransactionBuilder() .start() .address(0x42) .write(0x07) .restart() .address(0x42) .read(1) .stop() ) json_text = I2CTransaction.to_json(tr) restored = I2CTransaction.from_json(json_text) assert repr(tr) == repr(restored) results = restored.exec(master) ``` ### 13.7 Inspect `ExecResults` ```python from i2c_api import ExecResults data, ok = results # field order: data first, then is_success print(ok) for read_index, byte_list in enumerate(data): print(read_index, byte_list) print(results.values()) # list[BitArray], one per Read(...) command (if bytes are ints) print(results.pp()) ``` ### 13.8 Scan the bus and adjust link settings ```python print("devices:", master.scan()) speeds = master.list_clk_speeds() print("speeds (KHz):", speeds) if 400 in speeds: master.set_clk_speed(400) print("current speed:", master.get_clk_speed()) pullups = master.list_pullups() print("pullups:", pullups) if pullups: master.set_pullup(pullups[0]) print("current pullup:", master.get_pullup()) ``` --- ## 14. Error and return-value summary | Operation | Success | NACK/failure | Invalid input / misuse | |---|---|---|---| | `read` | `BitArray` of `num_bytes*8` bits | `None` | `ValueError` for bad transaction/details; driver errors possible | | `write` | `True` | `False` | `ValueError` (bad int/`num_bytes` too small), `TypeError` (bad type) | | `read_register` | `BitArray` | `None` | `ValueError` (bad `RegisterAddress`), `RuntimeError` (restart unsupported) | | `write_register` | `BitArray` written/read back | `None` | `ValueError`/`TypeError`, `RuntimeError` (restart unsupported) | | `exec` | `ExecResults(data, True)` | `ExecResults(data, False)` | `ValueError` (not a transaction, incomplete, unresolved address) | | `I2CTransaction.exec` | `ExecResults` | `ExecResults` | `ValueError` (no master, unresolved address) | | `set_clk_speed` | `None` | — | `RuntimeError` if speed unsupported | | `new_auto_instance` | `I2CMaster` | — | `ValueError` if config missing / import errors propagate | | `RegisterAddress(...)` | instance | — | `ValueError` if address outside width | | `mk_payload` | `BitArray` | — | `ValueError` (out-of-range byte / too-small `num_bytes`), `TypeError` (bad type) | Lifecycle: always `close()`; use `with I2CMaster.new_auto_instance() as master:` where possible. --- ## 15. Cheat sheet ```python # Get a master (requires .i2c_driver.json) from i2c_api import I2CMaster, RegisterAddress, I2CTransaction, I2CTransactionBuilder master = I2CMaster.new_auto_instance() # High level master.scan() master.read(0x42, 2) # -> Bits | None master.write(0x42, [0x07, 0x11]) # -> bool master.read_register(0x42, 0x07) # -> Bits | None master.write_register(0x42, 0x07, 0x11) # -> Bits | None master.write_register(0x42, 0x07, 0x11, read_back=True) # Fluent language i2c = I2CTransactionBuilder() tr = i2c.start().address(0x42).write(0x07).restart().address(0x42).read(1).stop() tr.exec(master) # -> ExecResults(data, is_success) tr.exec(master, 0x42) # fill Address(auto) I2CTransaction.from_json(I2CTransaction.to_json(tr)) # Results data, ok = tr.exec(master) ok = tr.exec(master).is_success values = tr.exec(master).values() # list[Bits], one per read op # Lifecycle master.close() ```