This guide shows how to implement a driver and its matching stream, register the driver with the engine, and keep the data path deterministic and safe.

0. Send a Block From a Model (the common case)

Most model code never implements a new driver or stream - it just publishes an already-configured ICD block on a stream that already exists. This is unrelated to EngineSync: EngineSync only synchronizes engine frame timing against an external signal, it is not how you send or receive stream data. The rest of this guide (1 onward) is only for implementing a new driver/stream from scratch.

void CMyModel::SendStreamMessage(const char* blockName)
{
    uint64_t engSize, rawSize;

    // Get the block's Eng buffer and set the fields you want to send
    auto pEng = CLRUsProj::LRU_MyLru->GetBlockEng(blockName, engSize);
    // ... set fields on pEng (cast to the block's struct type) ...

    // Convert Eng -> Raw, then send the Raw bytes on the stream
    CLRUsProj::LRU_MyLru->Eng2RawByName(blockName);
    auto pRaw = CLRUsProj::LRU_MyLru->GetBlockRaw(blockName, rawSize);

    auto result = CDrivers::SendBlock("streamName", pRaw, rawSize);

    // Optional bookkeeping
    if (result > CDriverBase::EIOResult::eNoIO)
        CStreams::IncBlockMessageCounter(pEng);
    else if (result == CDriverBase::EIOResult::eFail)
        CStreams::IncBlockMessageErrCounter(pEng);
    CStreams::SetBlockTimeStamp(pEng);
}
CLRUsProj::LRU_MyLru is your project's generated LRU accessor (one per LRU, named after it) - it's how you reach a block's Eng/Raw buffers by name. CDrivers::SendBlock(streamName, rawPtr, rawSize) is the actual send call. The CStreams::... helpers are optional message/error counters and timestamp bookkeeping - not required to send data.

0b. Get a Block's Raw or Eng Data (the common case)

To just read a block's data - no sending involved - call the same LRU accessor directly. This is unrelated to implementing a driver's Recv() loop (section 4 below is only for building a new driver/stream from scratch):

uint64_t engSize, rawSize;
auto pEng = CLRUsProj::LRU_MyLru->GetBlockEng(blockName, engSize); // eng-side pointer + size
auto pRaw = CLRUsProj::LRU_MyLru->GetBlockRaw(blockName, rawSize); // raw-side pointer + size

If you need every block of the LRU converted at once (typically once per OnRun(), right after new raw data has arrived on a stream) use the whole-LRU conversion instead of a per-block call - see Raw ↔ Eng Conversion in the Model guide:

void CMyModel::OnRun()
{
    CLRUsProj::LRU_MyLru->Raw2Eng(); // converts every block of this LRU, raw -> eng
    // ... read the eng-side elements of any of this LRU's blocks here ...
}

1. Understand the Architecture

Drivers provide low-level I/O access to hardware. Streams translate the raw bytes drivers exchange into ICD-compliant blocks consumed by models and states. Data flows as follows:

Hardware Device → Driver → Stream → Models / States

2. Implement the Driver

A driver manages the low-level interface with the hardware device and exposes a thin, deterministic API to the simulation engine. Implement:

// driver.cpp – Sample implementation
CSampleDeviceDriver::CSampleDeviceDriver(const char* streamName)
    : CDriverBase(streamName)
{
    InitDriver();
}

void CSampleDeviceDriver::InitDriver()
{
    // Perform hardware initialization
}

CDriverBase::EIOResult CSampleDeviceDriver::Send(const uint8_t* raw, uint64_t size)
{
    // Send raw bytes to hardware
    return CDriverBase::EIOResult::eNoIO;
}

CDriverBase::EIOResult CSampleDeviceDriver::Recv(uint8_t* raw, uint64_t size)
{
    // Read raw bytes from hardware
    return CDriverBase::EIOResult::eNoIO;
}

3. Implement the Stream

Streams translate raw driver messages into structured ICD blocks — the bridge between hardware bytes and internal logic models. Implement:

// stream.cpp – Sample implementation
void CSampleDeviceStream::SetupStream(const CStreamDriver* pStreamDriver)
{
    // Configure max message sizes or block allocations here
}

bool CSampleDeviceStream::ReadMsg()
{
    auto pDriver = (CDriverBase*)pStreamDriver->pDriver;
    // Iterate ICD blocks and perform Recv() calls here
    return true;
}

4. Write the Stream Processing Loop

Poll the driver for each stream block and route results based on the I/O outcome:

for (auto& block : StreamBlocks)
{
    auto result = pDriver->Recv(block->rawPtr, block->rawSizeBytes);
    if (result > EIOResult::eNoIO)
    {
        // Successful receive
        // CallOnReceiveCB(block,...);
        // SetModelTrigger(block);
    }
    else if (result < EIOResult::eNoIO)
    {
        UpdateBlockPropertiesOnStreamError(block);
    }
}

5. Register the Driver

Register your new driver class so the engine can instantiate it:

// DriversProj.cpp
CDrivers::RegisterDriver<CSampleDeviceDriver>(CSampleDeviceDriver::getName());

6. Keep the Data Path Deterministic

Follow this checklist for time-critical driver and stream code:

Additional best practices:

7. Use Supporting Building Blocks

For lockless hand-off between threads, use a single-producer/single-consumer queue:

template <typename T, size_t N>
class SPSCQueue {
public:
    bool push(const T& v) {
        const auto next = (head_ + 1) % N;
        if (next == tail_) return false;
        buffer_[head_] = v;
        head_ = next;
        return true;
    }

    bool pop(T& out) {
        if (tail_ == head_) return false;
        out = buffer_[tail_];
        tail_ = (tail_ + 1) % N;
        return true;
    }

private:
    T buffer_[N];
    size_t head_ = 0;
    size_t tail_ = 0;
};

For running tasks at different rates from a common base tick, use a multi-rate scheduler pattern:

struct ScheduledTask {
    int rateHz;
    std::function<void()> callback;
    int accumulator = 0;
};

void RunScheduler(std::vector<ScheduledTask>& tasks, int baseHz) {
    const int step = 1000 / baseHz;
    for (auto& t : tasks) {
        t.accumulator += step;
        if (t.accumulator >= (1000 / t.rateHz)) {
            t.accumulator = 0;
            t.callback();
        }
    }
}

8. Verify the Full Flow

Confirm your driver and stream fit into the overall scheduling flow: Driver Layer (hardware I/O) → Stream Parser (validate & split) → ICD Block Models (model triggers).

9. Worked Example: The Serial Driver

A complete, real three-layer implementation lives in the serial driver: the Stream (Streams/serial/serialStream.h/.cpp), the Driver (Drivers/serial/SerialDriver.h/.cpp), and its API dynamic library (Drivers/serial/api/Default/, loaded at runtime via Drivers/serial/SerialDriverLoader.cpp). The sections below walk through each layer using this real example.

Every driver with API libraries follows the same layout (ExternalModelDriver, serial, genicam, StorageDriver, UVCGadget):

PathContents
Drivers/<Driver>/<Driver>.h/.cppThe driver (CDriverBase), compiled into simcore only when the CMake option INCLUDE_<DRIVER> is ON, together with its loader and stream.
Drivers/<Driver>/<Driver>API.hThe driver's API class, derived from IApi. Every API library implements it.
Drivers/<Driver>/<Driver>Loader.h/.cppCDriverAPIInterface wrapper: loads the library named by "interfaceAPILib" and returns the API object (InitApiWrapper).
Drivers/<Driver>/api/<Name>/CMakeLists.txtOne API implementation, a SHARED library exporting create_api(); its own CMake option adds it to the build.
Streams/<driver>/The driver's stream.
Driver (folder)Device / API class / loaderAPI libraries (api/<Name> → library)CMake options
ExternalModelDriverExternalModelDevice / IExternalModelDeviceDriver (ExternalModelDeviceDriverAPI.h) / ExternalModelDeviceLoader Matlab → MatlabDeviceAPI, Python → PythonDeviceAPIINCLUDE_EXTERNALMODEL, INCLUDE_MATLAB, INCLUDE_PYTHON
serialSerialDriver / CSerialBaseDriver (SerialDriverAPI.h) / SerialDriverLoader Default → SerialCommAPI, FTDI → SerialFTDICommAPI, MOXA → SerialMOXACommAPI, Humandata → SerialHumandataCommAPI INCLUDE_SERIAL (ON), INCLUDE_SERIALFTDI, INCLUDE_SERIALMOXA, INCLUDE_SERIALHUMANDATA
genicamgenicamDevice / IGenICamDeviceDriver (GenICamDeviceDriverAPI.h) / GenICamDeviceLoader GeneralUSB → GenICamGeneralUSBAPI, USB → GenICamUSBAPI, GigE → GenICamGigEAPI (shared code GenTL) INCLUDE_GENICAM, INCLUDE_GENICAM_GENERALUSB, INCLUDE_GENICAM_USB, INCLUDE_GENICAM_GIGE
StorageDriverStorageDriver / IStorageDriverAPI (StorageDriverAPI.h) / StorageDriverLoader Default → StorageDriverAPIINCLUDE_STORAGE (ON)
UVCGadgetUVCGadgetDevice / IUVCGadgetDeviceDriver (UVCGadgetDeviceDriverAPI.h) / UVCGadgetDeviceLoader USB2 → UVCGadgetDeviceAPI (Pi 5), USB3 → UVCGadgetAPI3 (shared code Shared), GigE → UVCGadgetGigEAPI (the board is a GigE Vision camera: GVCP control server, GVSP stream, generated GenICam XML; Linux + Windows) INCLUDE_UVCGADGET, INCLUDE_UVCGADGET_USB3, INCLUDE_UVCGADGET_GIGE

Drivers are registered by each project (Drivers/DriversProj.cpp), except StorageDriver, which CoreEngine registers itself: it is also the CoreEngine recorder (see Storage Driver).

10. How Properties Load From streams.json

Each layer implements its own FillInProperties override, and each is handed a different slice of the stream's streams.json section:

Properties are read once, at startup, before OnInit() runs - FillInProperties only populates a properties struct (e.g. CSerialProperties); it does not open any hardware itself.

11. The Runtime Read Flow: Stream → Driver → API

Once running, reading a message flows down through all three layers every time the stream is polled:

  1. CStreamBase::ReadMsg() (pure virtual, e.g. CSerialStream::ReadMsg()) - the stream's own framing logic. The serial stream reads one byte at a time via the driver until it matches a block's headerMarker byte sequence, then reads the rest of that block's payload.
  2. CDriverBase::Recv(raw, size) / Send(raw, size) (pure virtual, e.g. CSerialDriver::Recv/Send) - the driver's hardware-facing read/write. The serial driver forwards this straight to the loaded API object (serialObj->Read(...) / serialObj->Write(...)), catches serial::IOException, and records the bytes via AddToRecorder(...).
  3. The API object's own Read/Write (e.g. CSerialWinPort::Read/Write in SerialCommWin.cpp) - the actual vendor/OS calls (Win32 ReadFile/WriteFile on Windows, POSIX read/write on Linux).

Sending a block one level up (from a Model) goes through CDrivers::SendBlock("streamName", rawPtr, rawSize) as described in section 0 above - that call reaches the same CDriverBase::Send at the bottom.

12. Diagram: From streams.json to the Vendor Call

streams.json ("driver": {...}, "blocks": [...])
        |
        v
CDriverBase::FillInProperties()          CStreamBase::FillInProperties()/FillInBlockProperties()
  (driver properties struct filled)        (block list, header markers, LRU wiring filled)
        |                                          |
        +--------------------+---------------------+
                             |
                        OnInit() (driver, then stream)
                             |
                             v
              CSerialDriver::OnInit() -- loads the API library (section 13) and opens the port
                             |
                             v
              Every scheduler tick: CStreamBase::ReadMsg()  (e.g. CSerialStream::ReadMsg)
                             |                          ^
                             v                          | CDrivers::SendBlock(...) from a Model
              CDriverBase::Recv() / Send()  <-----------+
              (e.g. CSerialDriver::Recv/Send)
                             |
                             v
              API object Read()/Write()  (e.g. CSerialWinPort in SerialCommWin.cpp)
                             |
                             v
              Vendor / OS call (ReadFile/WriteFile, or POSIX read/write)

13. Dynamic API Library Loading

The API layer is not linked into CoreEngine at compile time - it is a separate shared library (.dll / .so) loaded at runtime, so the same driver and stream code can work against different vendor implementations without recompiling CoreEngine. The loading chain, using the serial driver as the concrete example:

  1. The driver's constructor passes its library name as a plain string to CDriverBase's constructor: CDriverBase(streamName, version, "SerialCommAPI", "") - stored as APIInterfaceLibName.
  2. A CDriverAPIInterface-derived wrapper (e.g. CSerialDriverAPILoader in serial/SerialDriverLoader.cpp) is constructed with that same name and calls LoadAPI(error) (defined in DriverAPIInterface.hpp).
  3. LoadAPI uses a PluginLoader (InterfaceLoader.h/.cpp) to actually load the library - LoadLibraryA("SerialCommAPI.dll") on Windows, dlopen("libSerialCommAPI.so", RTLD_LAZY) on Linux, searching the working directory then the executable's directory.
  4. Once loaded, PluginLoader::getFunction<CreateApiFunc>("create_api") resolves the library's exported factory function by name (GetProcAddress / dlsym).
  5. Calling that function returns an IApi*, cast to the driver-specific abstract interface (CSerialBaseDriver* for serial) - this is the object the driver then calls Read/Write/Open/etc. on.
The library name has no file extension or path in code - "SerialCommAPI" becomes SerialCommAPI.dll or libSerialCommAPI.so automatically, per platform, inside PluginLoader::LoadInterface.

14. The Abstract API Interface Header

The dynamic library and CoreEngine agree on a contract through a shared abstract interface header - for serial, that's serial/SerialDriverAPI.h, defining class CSerialBaseDriver : public IApi with pure virtual methods: Init, Open, Close, isOpen, Read, Write, Available, setFlowControl, SetupBuffers, setStopbits, setBaudRate, setParity, flush/flushInput/flushOutput, ReportCommPorts, SetDriverLatency, and more. Every vendor implementation (e.g. CSerialWinPort in SerialCommWin.cpp, the Linux equivalent in SerialCommUnix.cpp) implements this same interface, so CoreEngine's driver code never needs to know which one is actually loaded.

IApi itself (InterfaceAPI.h) is the universal base every API library's interface derives from - it only provides ReportMsg/SetReportCallback, so any loaded library can report back through CoreEngine's normal reporting system.

15. Implementing Your Own API Dynamic Library

  1. Define your own abstract interface header deriving from IApi, declaring the pure virtual methods your driver needs to call (model it on serial/SerialDriverAPI.h).
  2. Implement a concrete class against that interface for each platform you support (model it on SerialCommWin.cpp / SerialCommUnix.cpp).
  3. Export the required entry point so PluginLoader can find it:
    extern "C" EXPORT IApi* create_api() {
        return new CYourConcreteDriver();
    }
    EXPORT (from InterfaceAPI.h) expands to __declspec(dllexport) on Windows or the GCC/Clang default-visibility attribute elsewhere - without it, create_api won't be a resolvable symbol.
  4. Build it as a CMake SHARED library (see section 16) and give your CoreEngine-side driver's CDriverBase constructor the matching library name (no extension), the same way CSerialDriver passes "SerialCommAPI".

16. CMakeLists.txt Anatomy (API Dynamic Library)

The real serial/api/Default/CMakeLists.txt, piece by piece:

project(SerialCommAPI LANGUAGES CXX)

The project name matches the library name the driver passes to CDriverBase's constructor - this is what ties the two sides together.

if(WIN32)
    set(LIB_SOURCES ./serialLatency/serial_latency_win.c)
else()
    set(LIB_SOURCES ./serialLatency/serial_latency_linux.c)
endif()

Platform-specific sources are selected at configure time - each platform compiles only its own implementation file.

add_library(SerialCommAPI SHARED
    SerialCommUnix.cpp
    SerialCommWin.cpp
    serialLatency.cpp
    ${LIB_SOURCES}
)

SHARED is the critical part - this produces a .dll/.so, not something statically linked into CoreEngine. Note both the Unix and Windows .cpp files are compiled into the same library; each uses its own platform guards internally.

target_include_directories(SerialCommAPI PUBLIC ${COREPATH} ${CMAKE_CURRENT_SOURCE_DIR}/include)

The library includes CoreEngine's own headers (for IApi, EXPORT, etc.) via COREPATH, even though it isn't linked against CoreEngine itself.

if(WIN32)
    target_link_libraries(SerialCommAPI PUBLIC setupapi advapi32)
endif()

Platform-specific system libraries the vendor implementation needs - here, Windows' SetupAPI and registry APIs for COM port enumeration.

target_compile_features(SerialCommAPI PUBLIC cxx_std_17)
set_target_properties(SerialCommAPI PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO)

Pins the language standard for this target specifically - it does not have to match whatever standard the rest of CoreEngine builds with.

add_custom_command(TARGET SerialCommAPI POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
    $<TARGET_FILE:SerialCommAPI>
    $<TARGET_FILE_DIR:simcore>
)

This is what makes PluginLoader::LoadInterface's runtime search succeed: every build, the freshly-built .dll/.so is copied next to the main CoreEngine executable's output directory, so it's found in the executable's own directory without any manual install step.

17. OnInit and OnReset

Each layer's OnInit()/OnReset() has a distinct job - they are called separately on the driver and on the stream:

Nothing about opening hardware belongs in a Model's OnInit() - that's the driver's job, wired up automatically by the engine for every driver/stream pair declared in streams.json. A Model only calls CDrivers::SendBlock(...) to use an already-running stream (see section 0).

18. Worked Example 2: The GenICam Driver (one driver, two API libraries)

The serial driver shows one driver with one API library. The GenICam camera driver (interfaces/Drivers/genicam) shows the other common pattern: one driver layer, several interchangeable API libraries behind a single abstract interface, selected from streams.json with interfaceAPILib. GenICam is the standard camera feature model; USB3 Vision and GigE Vision are the two transports supported:

interfaces/Drivers/genicam/
 ├── genicamDevice.h/.cpp        // driver layer: CGenICamDriver (CDriverBase)
 ├── GenICamDeviceDriverAPI.h    // the abstract interface: IGenICamDeviceDriver : IApi
 ├── GenICamDeviceLoader.h/.cpp  // CGenICamDeviceAPILoader: loads the library, calls create_api()
 ├── api/GeneralUSB/             // API library 1 GenICamGeneralUSBAPI: USB3 Vision through Aravis   (AravisCamera)
 ├── api/GenTL/                  // shared GenTL consumer: GenTLCamera, CGenTLProducer, GenTLConsumer.cmake
 ├── api/USB/                    // API library 2 GenICamUSBAPI: USB3 Vision through a GenTL producer + GenApi (GenTLCamera, "U3V")
 ├── api/GigE/                   // API library 3 GenICamGigEAPI: GigE Vision through a GenTL producer + GenApi (GenTLCamera, "GEV")
 ├── aravis-main/                // third party: Aravis (built for api/GeneralUSB)
 └── GenICam_V3_5_0/             // third party: GenICam GenApi reference implementation (api/GenTL)
interfaces/Streams/genicam/
 └── genicamStream.h/.cpp        // CGenICamStream: ReadMsg() copies one frame into the input block

The driver layer

The API interface: what every transport must implement

class IGenICamDeviceDriver : public IApi {
    bool setOption(name, value, err);            // apiOptions, before open()
    vector<DeviceInfo> listDevices(err);         // discovery report
    vector<string> listPixelFormats(id, err);
    string listFeatures(id, err);                // feature tree for "?" in cameraName
    bool open(deviceId, err);
    bool init(width, height, fps, pixelFormat, waitTimeout_us, numBuffers, err);
    bool setFeature(name, value, err);           // "features"
    bool configureExternalTrigger(line, activation, err);
    bool start(err);  void stop();  void close();
    int64_t captureRaw(dst, dstSize, timestampNs); // frame size, 0 = no frame, < 0 = EGenICamIOResult
    string getLastCaptureError();                // details of the last failure
    int64_t GetRequiredFrameSize();
};

The call order used by the driver is setOption* → open → init → setFeature* → [configureExternalTrigger] → start → captureRaw* → stop → close. Each library exports create_api() returning its implementation (section 15), so the driver never knows which transport it is talking to.

GenICamGeneralUSBAPI (USB3 Vision)GenICamUSBAPI (USB3 Vision) / GenICamGigEAPI (GigE Vision)
Implementation classAravisCamera – the Aravis libraryGenTLCamera (shared, in genicam/api/GenTL) – a GenTL producer (CGenTLProducer, a loaded .cti) for transport and the GenICam GenApi runtime for feature nodes. Each library's create_api() creates it for one transport: GenTLCamera(TLTypeU3VName, ...) or GenTLCamera(TLTypeGEVName, ...)
setOption()no options; any option is an errorproducer (.cti file or folder, default: GENICAM_GENTL64_PATH), discoveryTimeoutMs
Device id (cameraName)Aravis device idGenTL device ID, serial, user name, display name or model; only devices of the library's transport
FeaturesAravis device feature nodesGenApi node map built from the camera's XML, read through the producer port
FramesAravis stream buffers, latest-frame callback when the timeout is 0GenTL data stream with buffers announced to the producer
Buildown CMakeLists (Aravis)include(../GenTL/GenTLConsumer.cmake) + genicam_gentl_api(<target> <entry .cpp>)

A GenTL producer allows one TLOpen per process, but each GenTL library has its own copy of CGenTLProducer. When a GigE stream and a USB stream load the same mixed producer, the first library to open it publishes the transport layer handle in a process environment variable (SIMD_GENTL_TL_<hash of the .cti path>) and the second library reuses it. Each library opens only the interfaces of its own transport.

Adding another transport

To support a new camera back end (for example a vendor SDK), add an api/-style library that implements IGenICamDeviceDriver, exports create_api(), builds as a SHARED CMake target named like the value users will put in interfaceAPILib, and handles its own apiOptions in setOption(). No change to the driver layer, the stream or the existing streams.json files is needed.

User-level configuration of both interfaces (all fields, examples, trigger setup): GenICam driver reference.

19. Keyboard Handling (KeyListener)

The engine reads the console keyboard on its own thread through the static KeyListener class. Each key press arrives as a KeyEvent (key, ctrl, alt, shift) in the current callback. The engine installs its built-in handler (reset, init, run, stop, record, report, terminate); a model can hook the keyboard by registering its own callback:

KeyListener::SetCallbackHandler(keyHandler);   // e.g. from OnInit()

void keyHandler(const KeyEvent& k)
{
    if (::toupper(k.key) == 'X') { /* ... */ }
}

Full explanation and example: Models – How keyboard handling works. A driver or stream that needs operator input during a test should use this hook rather than reading the console itself.

Something not working? See Troubleshooting Drivers and Streams — one page per driver with the messages, causes and fixes.