Driver contract¶
What every driver-<chip> repository provides. A driver is an MCU-agnostic C++20 template on a CRTP port: the
user writes the port for their MCU, and the driver works the same on ESP32, STM32, any other MCU or a host. ESP32
is the first example platform, not a dependency.
A driver carries no brand (ADR-0012): it is usable, and forkable, without
anything else from Kokeb Labs. Examples below use a fictional ZP100 pressure sensor on I2C; replace zp100 /
ZP100 with the chip.
Repository layout¶
driver-<chip>/
├── inc/
│ ├── <chip>.hpp umbrella header: the only one users include
│ ├── <chip>_<bus>_interface.hpp the CRTP port base and its pin enums
│ ├── <chip>_types.hpp Error, Result<T>, Config, enums
│ ├── <chip>_registers.hpp register map (optional)
│ ├── <chip>_kconfig.hpp optional: maps CONFIG_<CHIP>_* onto Config defaults
│ └── <chip>_version.h.in version template, generated by CMake
├── src/<chip>.ipp template implementation, included at the end of <chip>.hpp
├── cmake/<chip>_build_settings.cmake version, target name, sources: the single source of truth
├── cmake/<chip>Config.cmake.in
├── examples/
│ ├── host/ runs on any PC: host port over the register model, built and run in CI
│ └── <platform>/ one self-contained folder per platform with its own port (esp32/: ESP-IDF)
├── tests/ host tests, doc snippets, install consumer
├── docs/ the driver page set (see docs.md)
├── _config/ all tool configuration: org .clang-format and .clang-tidy, Doxyfile,
│ mkdocs.yml (docs_dir: ../docs), Kconfig, markdownlint, yamllint, lychee
├── .github/ workflows, CONTRIBUTING.md, SECURITY.md, CODEOWNERS, templates
├── .claude/ agent skills
├── CMakeLists.txt the CMake library, and under ESP_PLATFORM the ESP-IDF component
├── driver.yml driver metadata: bus, supported MCUs, minimum kb-core
└── README.md, LICENSE (MIT), CHANGELOG.md, AGENTS.md, CLAUDE.md, .gitignore, .gitmodules
The root holds only these entries (ADR-0011): what GitHub or a tool needs at
the root and what a reader looks for first. Tool configuration MUST live in _config/, and every command and
workflow names its path; the root MUST NOT hold copies of or symlinks to it.
Names¶
(ADR-0012)
| Thing | Name | Example |
|---|---|---|
| Repository | driver-<chip> |
driver-pcal95555 |
| Namespace | <chip> |
pcal95555 |
| Driver class | <chip>::<CHIP> |
pcal95555::PCAL95555 |
| Umbrella header | inc/<chip>.hpp |
inc/pcal95555.hpp |
| CMake package and target | find_package(<chip>), <chip>::<chip> |
find_package(pcal95555), pcal95555::pcal95555 |
| Build settings | cmake/<chip>_build_settings.cmake |
cmake/pcal95555_build_settings.cmake |
| Macros and CMake options | <CHIP>_* |
PCAL95555_VERSION_MAJOR, PCAL95555_BUILD_TESTS |
| Kconfig | CONFIG_<CHIP>_* |
CONFIG_PCAL95555_I2C_ADDRESS |
- A driver MUST NOT contain an org prefix: no
kb_,kb::,KB_or any other brand in a name, namespace, macro, target, file or option. A fork MUST NOT inherit one. - Everything MUST be inside
namespace <chip>(lower case, the part number:zp100,tmc9660). Nothing is declared at global scope, including freeGetDriverVersion()helpers andusingdeclarations. - The driver class MUST be
<chip>::<CHIP>with the part number in upper case:zp100::ZP100. NotDevice,Driveror a product name. - A driver for a family names the class after the family member it was written for and lists the others in the
README (
at25040::AT25040also drives AT25010B and AT25020B). - Naming inside the namespace follows naming-and-style.md.
Platforms¶
- Driver code (
inc/,src/) MUST NOT include an SDK, RTOS or vendor header. Platform code lives only inexamples/<platform>/: each folder carries its own port, an example program and a README, and builds on its own. - Every driver MUST ship
examples/host/: a host port over the test register model and a program that initialises the driver and reads it, built with the test flags and run by the host tests. It is the quickstart's first step. - A platform is added only with a CI job that builds its example. Plain CMake covers STM32, RP2040, nRF and the
host; the root
CMakeLists.txtcovers ESP-IDF. Zephyr, Arduino or PlatformIO manifests are added only when a user needs them, never as a second copy of the sources. - A driver that needs one MCU's peripheral is the documented case in MCU-bound drivers.
The port¶
The port is how the driver reaches the bus. The user derives a class from the driver's CRTP base and implements its hooks; the driver is a template on that class.
// inc/zp100_i2c_interface.hpp
namespace zp100 {
enum class CtrlPin : uint8_t { Int = 0 }; // logical pins, not MCU pin numbers
enum class GpioSignal : uint8_t { INACTIVE = 0, ACTIVE = 1 };
template <typename Derived>
class I2cInterface {
public:
I2cInterface(const I2cInterface&) = delete;
I2cInterface& operator=(const I2cInterface&) = delete;
protected:
I2cInterface() = default;
~I2cInterface() = default;
};
/// Satisfied by a class that derives from I2cInterface<P> and implements the required hooks.
template <typename P>
concept I2cPort = std::derived_from<P, I2cInterface<P>> &&
requires(P& p, uint8_t addr, const uint8_t* tx, uint8_t* rx, size_t n) {
{ p.EnsureInitialized() } -> std::same_as<bool>;
{ p.Write(addr, tx, n) } -> std::same_as<bool>;
{ p.WriteRead(addr, tx, n, rx, n) } -> std::same_as<bool>;
};
} // namespace zp100
// The user's port, for their MCU
class MyI2c : public zp100::I2cInterface<MyI2c> {
public:
bool EnsureInitialized() noexcept;
bool Write(uint8_t addr, const uint8_t* data, size_t len) noexcept;
bool WriteRead(uint8_t addr, const uint8_t* tx, size_t tx_len, uint8_t* rx, size_t rx_len) noexcept;
void DelayUs(uint32_t us) noexcept; // optional hook
};
Rules:
- The base MUST be named
<chip>::{Spi,I2c,Uart,Adc}Interface<Derived>and the concept<chip>::{Spi,I2c,Uart,Adc}Port. A chip with two buses has one base per bus. There are no virtual functions. - The driver template MUST be constrained by the concept (
template <I2cPort Port> class ZP100), so a missing or misspelt hook is a compile error at the point of use. - The base MUST NOT declare the required hooks itself. A forwarding hook in the base turns a missing override into
infinite recursion at run time. The base MAY provide helpers built on hooks (
GpioSetActive(pin)). - Hooks MUST be PascalCase,
noexcept, and returnbool(true= the transfer completed). Avoidhook hides bus errors and is not allowed. - Hooks move raw bytes only. The driver MUST NOT configure the bus (speed, mode, pins); the port or the board does. Register addresses travel in the payload.
EnsureInitialized()on the port brings the bus up on first use and is idempotent.- Pins are logical:
CtrlPinnames the chip's function (Reset,Int,Enable) andGpioSignal::ACTIVEmeans "function asserted", whatever the electrical polarity. The port maps both to the board.
Required hooks per bus¶
| Bus | Hooks |
|---|---|
| SPI | bool Transfer(const uint8_t* tx, uint8_t* rx, size_t len): one full-duplex transaction with chip select asserted for its whole length; tx or rx may be nullptr |
| I2C | bool Write(uint8_t addr, const uint8_t* data, size_t len), bool WriteRead(uint8_t addr, const uint8_t* tx, size_t tx_len, uint8_t* rx, size_t rx_len) (repeated start); bool Read(uint8_t addr, uint8_t* data, size_t len) when the chip needs it |
| UART | bool Write(const uint8_t* data, size_t len), bool Read(uint8_t* data, size_t len, uint32_t timeout_ms) (all len bytes or false), bool FlushInput() |
| ADC | bool ReadVoltageMv(uint8_t channel, uint32_t& voltage_mv) |
All of them plus bool EnsureInitialized(). A chip with a protocol that does not fit (a multi-phase frame, a
DMA stream) MAY add hooks; they follow the same rules and are listed on the Porting page.
Bus requirements¶
The bus interface header states what the chip needs from the bus as constexpr values, not only as prose
(KB-CPP-123). The Porting page lists them, and each example port checks its own
settings against them with static_assert, so a port that clocks too fast or in the wrong mode does not compile.
| Bus | Constant | Meaning |
|---|---|---|
| SPI | kSpiMode |
The SPI mode (0 to 3) the chip samples in; a chip that accepts two names the one the driver is tested with |
| SPI | kMsbFirst |
true when each byte is sent most significant bit first |
| SPI | kMaxClockHz |
The highest SCK frequency the chip accepts |
| SPI | kMinCsHighNs |
The shortest time chip select stays high between frames |
| SPI | kCsSetupNs, kCsHoldNs |
Chip select low to the first SCK edge, last SCK edge to chip select high |
| SPI | kContinuousWord |
true when a frame must be clocked without idle time between its bytes |
| I2C | kI2cAddress |
The 7-bit address, or the base address when address pins add to it |
| I2C | kMaxClockHz |
The highest SCL frequency the chip accepts |
| I2C | kRepeatedStart |
true when a register read needs a combined write-read with a repeated START |
| UART | kMaxBaudRate, kTurnaroundUs |
The highest baud rate, and the time the line needs between the last byte sent and the reply |
// inc/zp100_spi_interface.hpp
inline constexpr uint8_t kSpiMode = 0; // datasheet 6.2: CPOL 0, CPHA 0
inline constexpr bool kMsbFirst = true;
inline constexpr uint32_t kMaxClockHz = 10'000'000;
inline constexpr uint32_t kMinCsHighNs = 50;
inline constexpr uint32_t kCsSetupNs = 20;
inline constexpr uint32_t kCsHoldNs = 20;
inline constexpr bool kContinuousWord = false;
// examples/host/host_zp100_port.hpp
static_assert(kPortClockHz <= zp100::kMaxClockHz, "the port clocks the ZP100 too fast");
A chip with a turnaround or an inter-frame gap adds a constant for it the same way. An I2C driver also documents which transfers the chip NACKs by design (a reset command, a busy chip) and never probes with a zero-length transfer (KB-CPP-130).
Control pins have a stated idle level. The Porting page lists each CtrlPin with its polarity and the level the
port drives before the pin's output is enabled, and the port drives that inactive level before it enables the output
and before the first frame (KB-HW-018).
Optional hooks¶
| Hook | When missing |
|---|---|
void DelayUs(uint32_t us), void DelayMs(uint32_t ms) |
Compile error at the first call that needs the wait. A driver whose chip has a timing requirement MUST NOT skip the wait. |
bool GpioSet(CtrlPin pin, GpioSignal signal) |
The function that needs the pin returns Error::Unsupported, or the driver uses the documented software alternative (for example a soft reset instead of the reset pin). |
bool GpioRead(CtrlPin pin, GpioSignal& signal) |
Same as GpioSet; interrupt-driven reads fall back to polling a status register when the chip has one. |
void Log(LogLevel level, const char* message) |
No output. The message is a fixed string; the driver never formats text, and the hook is not variadic. |
Optional hooks MUST be detected with a C++20 requires expression in one place, never with void_t or by
calling through the base:
namespace zp100::detail {
template <typename Port>
void DelayUs(Port& port, uint32_t us) noexcept {
if constexpr (requires { port.DelayUs(us); }) {
port.DelayUs(us);
} else {
static_assert(sizeof(Port) == 0, "zp100: the port must implement DelayUs(uint32_t)");
}
}
} // namespace zp100::detail
A missing hook therefore either falls back in a documented, safe way or fails to compile. It never silently skips a step.
Errors and Result<T>¶
Each driver has its own error enum and result type, so it stays usable outside kb-core
(ADR-0001). Handlers map them to kb::Status (errors.md).
namespace zp100 {
enum class Error : uint8_t {
// Base set: every driver declares these, with these values, in this order.
Ok = 0,
NotInitialized = 1, // an I/O call before EnsureInitialized() succeeded
InvalidArgument = 2, // a parameter outside the documented range; nothing was sent
Bus = 3, // a port hook returned false
Timeout = 4, // the chip did not become ready in time
DeviceIdMismatch = 5, // the ID register did not match the part
Crc = 6, // a frame failed its CRC or checksum
Busy = 7, // the chip refused the command because it is busy
DeviceFault = 8, // the chip reported a fault (status register, error frame)
Unsupported = 9, // the hook or feature this call needs is absent
// Chip-specific values start at 16.
FifoOverflow = 16,
};
[[nodiscard]] constexpr const char* ToString(Error error) noexcept;
template <typename T>
struct [[nodiscard]] Result {
T value{};
Error error{Error::Ok};
[[nodiscard]] constexpr bool ok() const noexcept { return error == Error::Ok; }
constexpr explicit operator bool() const noexcept { return ok(); }
};
template <>
struct [[nodiscard]] Result<void> {
Error error{Error::Ok};
[[nodiscard]] constexpr bool ok() const noexcept { return error == Error::Ok; }
constexpr explicit operator bool() const noexcept { return ok(); }
};
} // namespace zp100
Rules:
- Every public call that can fail MUST return
Result<T>(orResult<void>). Noboolsuccess flags, no out-parameter plusbool, no error code read back from a getter. - The base set MUST be declared with the values above, so one mapping table serves every driver. A driver MAY never return some base values; its API guide says which.
- Each chip-specific value MUST be returned by at least one call. Unused values are deleted.
- Every port failure MUST propagate as
Error::Bus(orCrc,Timeoutwhen that is what happened). A getter that returns a stale or zero value after a failed read is a defect. TMUST be default-constructible and trivially copyable. A failed call leavesvaluedefault-initialised.- Sticky chip status (fault latches, error counters) is extra: a getter MAY expose it, but it never replaces the
Resultof the call that hit the error. ToString()returns a static string for every value.NoDevice,PinandNotReady, when a driver needs them, mean what errors.md says.
Replies, retries and resynchronisation¶
These rules come from testing the migrated drivers on hardware; each failure they prevent was seen on a bench.
- A reply is decoded only when the protocol proves it answers the request: CRC, plus the reply's type and width, plus the echoed opcode, address or tag the protocol has (KB-ARCH-042).
- A reply a stuck, floating or looped-back line can produce (all zeros, all ones, the command echoed, one word
repeated) is never data; it is
NoDeviceor another error, and an idle status a line could fake is confirmed by a second read (KB-CPP-116). - A chip that answers one or more frames later is served inside one public call, results matched on the reply's content, never its position; the Porting page states that nothing may access the chip between those frames (KB-ARCH-043).
- After a failed transfer, or one with an unknown outcome, the next frame brings the chip's protocol back to a known point (KB-CPP-118).
- A retry repeats only idempotent frames, never a reset, enable toggle or deinitialise the datasheet does not ask for, and every retry loop has a bound and counts its attempts (KB-ARCH-044).
State, shadows and latches¶
- A setter updates the driver's copy only after the chip accepted the change, and finishes a change the chip applies later before it returns (KB-CPP-120).
- A setter changes only what it names; a change the chip accepts only in some state is refused outside it, and nothing is sent (KB-CPP-121).
- Control and output registers are written whole from the copy; a read-modify-write uses only a validated read (KB-CPP-122).
- Clear-on-read and write-1-to-clear flags collect in one latch the driver owns, from every read it makes,
internal ones included:
GetLatched*()returns it with no I/O andClearLatched*()empties it (KB-CPP-119).
// Every STATUS read the driver makes, including the busy polls inside other calls:
latched_status_ = static_cast<uint8_t>(latched_status_ | (byte & reg::kStatusClearOnRead));
[[nodiscard]] Status GetLatchedStatus() const noexcept; // no I/O
void ClearLatchedStatus() noexcept; // no I/O
Start-up¶
On top of the sequence under Lifecycle:
- The identity check is one the chip must answer actively (select-and-echo, a bit it must toggle, a write and a read-back), so a dead or looped bus cannot pass it (KB-CPP-117).
- Start-up waits for the chip's own ready indication: the datasheet minimum, then a bounded poll with a deadline
from
Config(KB-CPP-124). - Nothing from before the host reset is trusted: the chip is reset or fully rewritten, and faults latched before the start are cleared or reported (KB-CPP-058).
- The variant is confirmed before any variant-specific write (KB-CPP-125).
- Load-dependent diagnostics are enabled only for channels
Configdeclares as loaded, and fault routing is set from the same declaration before the chip is armed (KB-CPP-131).
Values and diagnostics¶
- Arguments and
Configare checked against the datasheet's operating range and never silently clamped; a quantised setting reports what was programmed (KB-CPP-126). - A state that is not a measurement is an error, never a number; a multi-item read reports validity per item (KB-CPP-127).
- A conversion that depends on another setting uses the chip's actual setting (KB-CPP-128).
- Status bits are named by meaning, not raw polarity (KB-CPP-038).
- Every driver has a single-shot raw access with no retries (
ReadRegister()or a frame trace) and aGetLast*()accessor for the last raw reply, with no I/O (KB-CPP-129).
Lifecycle¶
template <I2cPort Port>
class ZP100 {
public:
explicit ZP100(Port& port, uint8_t address = kDefaultAddress,
const Config& config = {}) noexcept; // stores, no I/O
Result<void> EnsureInitialized() noexcept; // the one start: once, then Ok with no I/O
[[nodiscard]] bool IsInitialized() const noexcept;
Result<void> Deinitialize() noexcept; // chip to its safe low-power state
Result<void> ApplyConfig(const Config& config) noexcept; // write when running, store before
Result<float> ReadPressurePa() noexcept;
Result<void> SetOversampling(Oversampling osr) noexcept;
};
- The constructor MUST be
noexcept, MUST NOT perform I/O and MUST NOT fail. It stores the port, any bus argument and the configuration (its last parameter, defaulted). EnsureInitialized()MUST be the only public way to start. Its first call MUST, in order: check the stored configuration withValidate()(InvalidArgument, no I/O), call the port'sEnsureInitialized()(Buson failure), reset the chip (hardware reset if the pin hook exists, else software reset), read and check the chip ID (DeviceIdMismatch), apply the configuration, and only then mark the driver initialised. On any failure the driver stays uninitialised and the next call starts again. Once initialised it returnsOkat once with no I/O.- The sequence is a private member (
initialize()); a driver has no publicInitialize(). ApplyConfig(config)validates first; on a running driver it writes the configuration, before the start it only stores it for the firstEnsureInitialized(), with no I/O.Deinitialize()puts the chip in its documented safe state (outputs off, low-power mode) and clears the initialised flag. Calling it on an uninitialised driver returnsOk.- Every call that touches the bus MUST return
NotInitialized, and send nothing, beforeEnsureInitialized()succeeded. No read or write resets or starts the chip as a side effect. Recovery after a fault isDeinitialize()thenEnsureInitialized(). - A chip without an ID register checks the closest equivalent (a reset value, a known status bit) and documents it.
- Destructive operations (firmware update, OTP write, factory reset) MUST take their data or confirmation explicitly. No default argument may trigger them.
Config and Kconfig¶
struct Config {
Oversampling pressure_osr = Oversampling::X8; // datasheet default unless the README says why not
uint16_t odr_mhz = 50'000; // units as suffixes
uint32_t ready_timeout_ms = 10;
};
- Run-time configuration MUST be one
Configstruct with unit-suffixed fields and defaults taken from the datasheet. The struct is passed to the constructor and changed withApplyConfig(); individual setters MAY exist for values that change at run time. - What differs between products (which channels are used, which features are on, a profile table) is a field of
Config(a mask, astd::spanpassed in), never a compile-time switch for one product (layers.md). - Kconfig is an optional ESP-IDF layer, in
_config/Kconfig(registered withKCONFIGby the rootCMakeLists.txt). If a driver ships aKconfig, theCONFIG_<CHIP>_*values MUST be read in exactly one header,inc/<chip>_kconfig.hpp, which produces aConfig(<chip>::KconfigDefaults()). Kconfig values MUST NOT appear in public signatures, constructors or other headers. - A driver that reads
CONFIG_*without shipping theKconfigthat defines it is a defect. - ESP-IDF projects set values through
sdkconfig.defaults; a fullsdkconfigis not committed.
Verification is opt-in¶
A call does what the datasheet needs and nothing more, so a control loop pays only for the transfer it asked for.
enum class Verify : uint8_t { None, ReadBack };
Result<void> Write(uint16_t address, std::span<const uint8_t> data, Verify verify = Verify::None) noexcept;
- A read-back after a write, a second read to compare, or any check the datasheet does not require is asked for
per call, with a trailing
Verifyargument that defaults toVerify::None. One driver object then serves a control loop (no extra traffic) and a factory write (Verify::ReadBack) without reconfiguring. The doc comment says whatReadBackcosts on that call (for example "one more I2C read per write") and what it catches. - Not extra, so not optional: the start-up identity check in
EnsureInitialized(), a busy poll the datasheet requires before a command, and verification steps in an irreversible procedure (an OTP or fuse burn). - A host test shows that the default call sends no extra transfer, and another passes
Verify::ReadBackand shows it catching the fault.
Memory and threads¶
(ADR-0004)
- No heap (
new,malloc,std::vector,std::string), no exceptions, no RTTI, nostd::function, noprintf-family calls, nostaticmutable state (including function-local statics and report buffers). - Callbacks are a function pointer plus a
void*context:using DataReadyFn = void (*)(void* ctx);. - Buffers are members sized by
constexprlimits, or caller-providedstd::span. - The driver is not thread-safe and MUST NOT lock. One driver object is used from one thread at a time; kb-core handlers own the locking. The driver MUST NOT call an RTOS.
- The driver MUST NOT sleep except through the port's delay hooks.
Large chips¶
A chip with many subsystems (a motor controller, an IMU with a sensor hub) MAY split its API into sub-object
facades held by the driver (driver.telemetry().ReadSupplyMv()). Each facade follows this contract; they share
the driver's port, lifecycle and Error.
Build, export and versioning¶
- C++20 (ADR-0010),
target_compile_features(... cxx_std_20). MIT (ADR-0009). cmake/<chip>_build_settings.cmakeMUST be the single source of the version (<CHIP>_VERSION_MAJOR,_MINOR,_PATCH), the target name and the source list.project(), the package version, the generated<chip>_version.h,PROJECT_NUMBERin_config/Doxyfileand the version indriver.ymlall come from it or are checked against it, and a test checks that every copy agrees.- The target MUST have
EXPORT_NAME <chip>and a<chip>::<chip>alias, so<chip>::<chip>works after bothadd_subdirectory()andfind_package(<chip>). - Install rules MUST install every header the umbrella header includes, the
.ipp, the generated version header and the package config. - Options are
<CHIP>_BUILD_TESTS(host tests and doc snippets,OFFby default) and<CHIP>_ENABLE_WARNINGS. - The root
CMakeLists.txtMUST also be the ESP-IDF component: underESP_PLATFORMit callsidf_component_register()from the build settings, withKCONFIG ${CMAKE_CURRENT_LIST_DIR}/_config/Kconfig, and returns beforeproject(). This is build glue, not driver code:inc/andsrc/never testESP_PLATFORM. ESP-IDF projects use the repository throughEXTRA_COMPONENT_DIRS, a checkout undercomponents/, or a component-manager git dependency; there is no wrapper component and noidf_component.yml(added only if registry publishing is chosen). - Every repository MUST use the shared CI,
kokeb-labs/ci-tools/.github/workflows/<name>.yml@v1. - The version is SemVer 0.x until the API is declared stable (release.md).
Metadata: driver.yml¶
Every driver carries driver.yml at the root. kb-core builds its compatibility file, catalog/compat.yml, from
the driver.yml of each pinned driver (release.md); the file drives the CMake MCU
gate, the kb command-line tool and the web configurator.
name: zp100
version: 0.2.0 # checked against cmake/zp100_build_settings.cmake
bus: [i2c] # spi, i2c, uart, adc, pio (a timed bit stream), or a protocol (canopen)
mcus: [any] # any, or the families it needs: [esp32]
peripheral: null # the MCU peripheral it needs, with mcus: RMT
kb_core_min: 0.1.0 # the oldest kb-core whose handler and adapters work with this version
mcusis[any]unless the driver needs one MCU's peripheral; then it names the families andperipheralnames the peripheral, which becomes a row of the MCU gate table ("WS2812:ESP32:RMT").kb_core_minis the only mention of kb-core in a driver, and it is metadata: the driver's code never depends on kb-core.- CI checks the file against the build settings and the examples it builds.
Tests¶
tests/mock_<chip>.hpp: a register-level model of the chip implementing the port, used by every host test. It is written from the datasheet on its own: it does not include<chip>_registers.hpp, it carries its own register map with datasheet page references, and a test (tests/test_model.cpp)static_asserts the model's map against the driver's, so a wrong constant in the driver cannot hide behind the same constant in the model (KB-TST-030). Every behaviour found on hardware becomes a fault mode of the model and a regression test, and a chip with timing has a virtual clock in its model.- A host suite built on gcc and clang with
-Wall -Wextra -Werror -fno-exceptions -fno-rtti, run by the shared host-test workflow. It covers: every public call beforeEnsureInitialized()(NotInitialized), the chip-ID mismatch, a failing port hook on every call path (Bus), argument validation, and the register traffic of each feature. tests/docs/: every code block on the documentation site compiles here (<!-- generated: ... -->regions).tests/install_consumer/: installs the driver and builds a consumer withfind_package(<chip>)and<chip>::<chip>.- A version test: the CMake version,
_config/Doxyfile,driver.ymlandGetDriverVersion()agree. examples/host/is built with the test flags and run by the host tests, and CI builds everyexamples/<platform>/(the shared ESP32 example-build workflow for ESP32).
Docs¶
The driver page set in docs.md, plus:
- Doxygen with
EXTRACT_ALL = NOand warnings as errors oninc/: every public symbol is documented. - The quickstart checks every return value.
- The Porting page shows a complete port for each bus, compiled in
tests/docs/. - The API guide lists the
Errorvalues each call can return.
Exceptions¶
MCU-bound drivers¶
A chip that only works with one MCU peripheral (WS2812 LEDs timed by the ESP32 RMT) still gets a platform-free driver: it builds frames, encodes pixels and checks arguments, and reaches the peripheral through its port. The MCU-specific part is not in the driver:
- In kb-core, the peripheral backend lives in
interfaces/mcu/<family>/behind aBase*interface, and the driver is listed in the MCU gate table (layers.md). - In the driver repository, the backend is the port in
examples/<family>/. driver.ymlnames the families and the peripheral; the README and Contract page say the driver is MCU-bound.examples/host/MAY be replaced by host tests over a mock of the peripheral.
The driver keeps the repository shell, the root layout, the error model, the lifecycle and the naming. It MUST
NOT include the vendor SDK in inc/ or src/.
Protocol clients¶
A driver for a device reached over a protocol rather than a chip (a fictional motor-controller node over CANopen)
skips the chip-specific rules: chip-ID check, register model, datasheet defaults and the register mock. It follows
everything else: namespace, port, Result<T> and Error, lifecycle, no heap, build, driver.yml, tests and docs.
Its EnsureInitialized() checks the remote identity (device type, vendor ID) instead of a chip ID.