Using the Model API

Typical Use

In a typical project, a Simulink model reads dash channels, computes outputs and sends results back to the dash. You rarely call the CAN functions yourself: Ginmake and the runtime’s CMake helpers generate that code.

Model IPC

The CD6 has two processor cores. The dash firmware runs on the CM7 core and owns the display, inputs, logging and external CAN. Your model runs on the CM4 core. Model IPC (inter-processor communication) is the virtual CAN connection between them. It has no external connector. It is not really a CAN bus at all and operates via shared memory - but familiar CAN semantics are used for message framing and signal encoding.

  • Two DBC files define the IPC messages. Write them yourself or export them from Dash Design.
  • The dash transmits selected channel values to the model and receives model outputs as dash channels, which can then be displayed, logged or forwarded to external CAN.
  • Ginmake turns the DBCs into get/set functions and Simulink signals, so the model works with named signals rather than frames.

See Model IPC Messages for the DBC directions and the Dash Design and Ginmake steps.

Model Callbacks

The runtime runs your application through five callbacks declared in cdx_app_functions.h:

flowchart LR
    subgraph Start["Start-up (once)"]
        A["system_init"] --> B["model_period_us_get"] --> C["model_init"]
    end
    subgraph Run["Running"]
        D["can_rx_handle<br/>each IPC frame"] --> E["model_step<br/>each period"]
        E --> D
    end
    C --> D

Each name above is shown without its CDX_app_ prefix.

Callback When it runs Typical work
CDX_app_system_init Once at CM4 start-up Initialise generated IPC code and other application resources
CDX_app_model_period_us_get Once, after system initialisation Return the fixed step period in microseconds
CDX_app_model_init Once, before the model starts running Call the model’s initialise function
CDX_app_can_rx_handle For each received IPC frame, before the next step Pass the frame to the generated IPC decoder
CDX_app_model_step Once per period Refresh inputs, call the model’s step function, send outputs

Rules for every callback:

  • Callbacks run one at a time in the foreground, never from an interrupt. Do not call CDX functions from interrupts.
  • Keep each callback short and bounded. A late step is not replayed: missed periods are counted.
  • The runtime supports a single base rate. Schedule any slower rates inside the step.
  • Returning a status other than CDX_STATUS_OK faults the model. A receive handler that does not use a frame should return CDX_STATUS_MESSAGE_IGNORED (or CDX_STATUS_MULTIPLEX_IGNORED / CDX_STATUS_NO_DATA) instead.
  • Sending is unavailable during the initialisation callbacks. Send from the step.

Implementing The Callbacks

Choose one of these approaches:

  • Simulink model, no hand-written C (recommended). Call CDX_RT_configure_simulink in CMakeLists.txt with your model’s header, initialise and step functions. It generates all five callbacks. Each step refreshes the fast-I/O inputs, runs the model, sends any urgent CAN frames and then sends the IPC outputs. See Simulink Projects and the template’s CMake adapter.
  • Hand-written adapter. Implement the five callbacks yourself in main\, calling the model and the Ginmake-generated IPC functions. Use this when you need extra C code, for example to build a custom external CAN message. The project template and echo example work this way.

Most models also read the CD6 analogue inputs through the fast-I/O signals and use calibration through the generated A2L and XCP.

The advanced topics cover lower-latency physical CAN transmission and direct use of the CAN, DBC, time and memory functions in hand-written code.

API Map

Include the public headers from the template’s include directory. The API reference contains the authoritative signatures, parameters, constraints and per-function failure results.

Header Purpose
cdx_status.h Common operation results
cdx_can_bus_id.h The sole supported logical bus
cdx_can.h CAN/FD frame types, enqueue and signal readers
cdx_fast_io.h Low-latency ADC snapshots, cached input getters and physical CAN access
cdx_time.h Local clocks and wrapping deadline helpers
cdx_dbc_pack.h Pack unsigned signals into payloads
cdx_dbc_unpack.h Extract unsigned signal bits
cdx_dbc_copy.h Copy signal bits between payloads
cdx_utils.h Sign extension, byte swapping and floating-point helpers
cdx_memory.h Registered, bounded model-memory access
cdx_cal.h Ginmake identity measurements and restored model calibration access
cdx_app_functions.h Public callbacks implemented by the model

Calibration

cdx_cal.h exposes Ginmake identity measurements and access to restored model-owned calibration data. CM7 provides the XCP service on a configured external CAN interface. The model does not implement a network XCP server or gain direct hardware access through this header. Ginmake generates calibration A2L from the configured model descriptions.

See Calibration And NVM for the template’s gain/offset demo, parameter layout/defaults, A2L generation and explicit XCP save/restore workflow.

The runtime registers the restored calibration data for XCP access when a session starts. You do not need to call the memory functions for this.

Advanced Topics

The following sections are for users who need to optimise latency or write their own CAN, timing or memory handling. Ginmake-generated code already uses the CAN, DBC and time functions correctly, so most projects can skip them.

Urgent Physical CAN Transmit

Ordinary model outputs travel over Model IPC to the dash, which then forwards them to external CAN through its output configuration. When that delay matters, for example for a torque or shift request to another ECU, the model can send a frame directly on physical CAN1 or CAN2 through CM7 with CDX_can_tx_urgent_enqueue from cdx_fast_io.h. This bypasses the dash’s output processing.

The simplest way to use it is Ginmake’s urgent_tx configuration, which generates a sender with step, periodic or triggered policies. See Urgent physical CAN transmit.

To call it from hand-written code:

Argument Rule
port Physical CAN port: 0 for CAN1, 1 for CAN2. Not the logical IPC bus.
params deadline_ticks must be zero. Only the IDE, EDL and BRS flags are supported. FD lengths must match a CAN-FD DLC.
data Aligned payload, copied during the call. NULL only for a zero-length frame.
lifetime_us Maximum age, 1 to 1,000,000 microseconds, measured conservatively from the latest CM7 clock publication. Use this instead of a deadline.

It returns CDX_STATUS_OK, CDX_STATUS_BAD_PARAM, CDX_STATUS_IPC_OFFLINE or CDX_STATUS_QUEUE_FULL (the newest request is rejected).

  • Call it from model callbacks only, never from interrupts or other threads.
  • Each physical port queues up to four frames.
  • Acceptance is not delivery. Unavailable ports, expiry, bus errors, stop/reset and session changes can discard requests.
  • There is no completion callback or cancellation, and a frame already being transmitted cannot be pre-empted. The configured bus mode and CAN arbitration still apply.

Direct Model IPC CAN Access

Ginmake-generated code normally calls these functions. Use them directly only for hand-written CAN handling.

The Model IPC API provides one virtual CAN bus: CDX_CAN_BUS_ID_IPC. It exchanges frames with CM7 over Model IPC, not an external CAN controller. CDX_CAN_BUS_ID_CAN1 is a legacy alias for this same virtual bus. It does not select external CAN1. CM7 owns the external CAN interfaces for the dash and XCP. For physical CAN, see Urgent Physical CAN Transmit. Signals can be forwarded between external CAN, dash channels and Model IPC through the dash setup. See the IPC message workflow for Dash Design DBC export and Ginmake generation.

Model IPC frames follow these rules:

  • Standard identifiers are 11 bits.
  • Extended identifiers are 29 bits and require CDX_CAN_FRAME_FLAG_IDE.
  • Classic payloads are 0-8 bytes.
  • FD payloads are 0-64 bytes and require CDX_CAN_FRAME_FLAG_EDL.
  • Bit-rate switching requires both EDL and BRS.
  • Remote-request and error frames are not supported.

The runtime rejects unsupported buses, flags, identifiers and lengths.

CDX_DATA_64 provides aligned eight-byte chunks. Its u8 view follows payload byte order. Wider integer views use native-endian storage, not DBC conversions. Received data_chunks is the ceiling of length_bytes / 8.

Receive Ownership

The received frame and its data are borrowed for the receive callback only. Copy the bytes and metadata you need before returning. Do not retain the pointers. timestamp_ticks is a receiver-local arrival timestamp. error_type and hw_timestamp are zero: no physical error frame or hardware timestamp is provided.

Sending A Frame

Zero-initialize CDX_CAN_TX_PARAMS. Fill the identifier, flags and byte length, then call CDX_can_tx_enqueue_copy. Use aligned chunks for payload storage. You can reuse that storage immediately after the call. A null payload is allowed only for a zero-length frame. The call is nonblocking and copies accepted data.

For example, from a model callback:

 1#include "cdx_can.h"
 2
 3CDX_STATUS MDL_send_status(uint8_t value)
 4{
 5    CDX_CAN_TX_PARAMS params = {0};
 6    CDX_DATA_64 payload = {0};
 7
 8    params.id = 0x100u;
 9    params.length_bytes = 1u;
10    params.deadline_ticks = CDX_ticks_deadline_from_millisec(10u);
11    payload.u8[0] = value;
12
13    return CDX_can_tx_enqueue_copy(CDX_CAN_BUS_ID_IPC, &params, &payload);
14}

Handle the status returned by CDX_can_tx_enqueue_copy:

Status Meaning
CDX_STATUS_OK The runtime copied and accepted the request. This does not mean delivery.
CDX_STATUS_QUEUE_FULL The newest frame was rejected. Keep important work in bounded model-owned storage and retry on a later step.
CDX_STATUS_TIMEOUT An enabled deadline has already expired.
CDX_STATUS_IPC_OFFLINE There is no bound RUNNING session, or the session was lost.
CDX_STATUS_BAD_PARAM The bus, pointer, flags, identifier or length is invalid.

The runtime has 32-frame RX and TX queues and one in-flight TX batch. Enqueue success does not guarantee later success. Do not spin inside a callback waiting for queue space. Transport servicing also needs the foreground.

Completion And Deadlines

The API has no TX completion callbacks. Acceptance does not confirm that CM7 copied the frame, that physical CAN delivered it or that a model finished execution. Queued frames can expire before publication to the peer. An IPC fault can discard accepted queued or in-flight work.

deadline_ticks is an absolute local microsecond deadline:

  • Zero disables expiry.
  • CDX_CAN_FRAME_FLAG_DISABLE_DEADLINE also disables expiry.
  • An enabled deadline must be within CDX_MICROSEC_32_DEADLINE_MAX (0x7fffffff) microseconds of the local clock.

Published batches remain peer-owned until acknowledgement. Expiry cannot cancel them.

Time And Wrap

The time API uses local elapsed time, not synchronized CM4/CM7 clocks or calendar time. One tick is one microsecond. The 32-bit microsecond counter wraps after about 71.6 minutes. Deadline comparisons are limited to the half range, about 35.8 minutes. The foreground must poll at least once per microsecond-counter wrap to keep the extended 64-bit counter valid.

Use CDX_ticks_deadline_from_millisec to form a nonzero CAN deadline. It clamps the interval to the supported range and avoids zero because CAN treats zero as disabled expiry. In contrast, CDX_microsec_deadline_remain does not treat zero as disabled.

Convert received local timestamps with CDX_millisec_32_from_ticks only when they are less than one microsecond-counter wrap old. CDX_can_is_timed_out_ms uses wrapping millisecond subtraction. Its timestamp must be less than one millisecond-counter wrap old. A zero timeout always times out.

Registered Model Memory

Use this only to expose additional model-owned storage through the bounded memory functions.

During initialization, use CDX_memory_region_register to register model-owned storage. You can register at most eight non-overlapping regions. Each region has:

  • A logical 32-bit base address.
  • Backing storage and a byte size.
  • Write permission.

Keep the storage valid until runtime rebinding. Do not register peripherals or shared IPC buffers. Rebinding clears registrations. Model stepping does not.

Reads and writes must fit entirely inside one registered region. Address extension must be zero. Writes require a writable region.

Block operations return status and allow overlapping source/destination storage. Scalar helpers use native-endian values and need no alignment. Scalar reads return zero on failure. Use CDX_memory_read when you need to distinguish failure from a valid zero value.

Registration can return CDX_STATUS_QUEUE_FULL when all eight slots are used. Invalid storage, zero size, overlap or address overflow returns CDX_STATUS_BAD_PARAM. Check registration results before exposing memory to other model logic.

DBC Signals And Numeric Utilities

Ginmake-generated code also uses these helpers. Hand-written code can call them to pack and unpack its own frames.

Pack, unpack and copy functions support little-endian and big-endian signals up to 32 or 64 bits. Follow each function’s documented offset/bit numbering and buffer-size constraints. Do not interchange Intel and Motorola start-bit rules. Packing does not apply physical scaling or unit conversion.

Unpack functions and CDX_can_read_signal_* return raw unsigned bits, not a signed or scaled physical value. Use the matching CDX_sign_extend_* helper for a signed DBC signal, then apply the model’s scaling and offset separately. A zero unpack result can also indicate an invalid request. Validate the definition and payload size rather than treating zero as proof of a valid signal.

The numeric utilities also provide byte swaps and IEEE-754 bit reinterpretation. Reinterpretation preserves a bit pattern. It is not a numeric cast. Refer to the API’s width and floating-point constraints rather than assuming unsupported formats.