# Universal Function Protocol (UFP) — v0.4

The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be read as in
RFC 2119. For changes from earlier versions, see the [Changelog](#changelog).

**Contents:**
[1. Overview](#1-overview) ·
[2. Framing](#2-transport-and-framing) ·
[3. Messages](#3-message-structure) ·
[4. Types](#4-type-system) ·
[5. Enumeration](#5-enumeration) ·
[6. Sessions](#6-sessions-ordering-and-timeouts) ·
[7. Function descriptor](#7-function-descriptor) ·
[8. Call](#8-function-call) ·
[9. Errors](#9-errors) ·
[10. Events](#10-events) ·
[11. Conformance](#11-conformance) ·
[12. Bindings](#12-language-bindings-non-normative) ·
[13. Test vectors](#13-worked-example-and-test-vectors) ·
[14. Design decisions](#14-design-decisions)

> **Reading the message layouts.** Each message is shown as a table: one column
> per field, in wire order, with its size underneath. `B` = byte,
> `LE` = little-endian, `pstring` = length-prefixed string (§4.4).

## 1. Overview

UFP is a compact binary protocol for remote procedure calls and events between
a **host** (PC, phone, browser, server) and a **device** (microcontroller,
process, service) over any byte stream or packet transport: UART, USB CDC,
USB bulk/HID, SPI, I²C, BLE, TCP, WebSocket, Web Serial, …

- **Runtime discovery**: the host enumerates and inspects every function and
  event, including names, types, units and descriptions.
- **Compact invocation**: after discovery, a call carries only a function ID and
  packed arguments, with no type tags.
- **Events**: the host subscribes to device-initiated notifications. No polling.
- **Cacheable schema**: a schema hash lets hosts skip discovery on reconnect and
  lets statically generated bindings check that they match the device.
- **Small footprint**: a device needs no heap. Descriptors can live in flash.
  Receive and transmit buffers are bounded by a size the device advertises.

All multi-byte values are **little-endian**.

## 2. Transport and Framing

UFP has two transport modes. The **payload** (§3 onward) is identical in both.

### 2.1 Stream mode (UART, USB CDC, TCP, SPI/I²C byte streams, …)

Each payload is followed by a CRC, COBS-encoded, and terminated by `0x00`:

```
wire = COBS( PAYLOAD || CRC16 ) || 0x00
```

After COBS decoding, the frame body is:

| Field   | Size    | Description                                     |
|---------|---------|-------------------------------------------------|
| PAYLOAD | N bytes | The message (§3). `2 ≤ N ≤ MAX_PAYLOAD`.        |
| CRC16   | 2 B LE  | CRC-16/CCITT-FALSE over PAYLOAD.                |

**CRC-16/CCITT-FALSE** (also catalogued as CRC-16/IBM-3740): width 16,
poly `0x1021`, init `0xFFFF`, no input/output reflection, xorout `0x0000`.
Check value: `crc("123456789") = 0x29B1`.

```c
uint16_t ufp_crc16(const uint8_t *p, size_t n) {
    uint16_t crc = 0xFFFF;
    while (n--) {
        crc ^= (uint16_t)(*p++) << 8;
        for (int i = 0; i < 8; i++)
            crc = (crc & 0x8000) ? (crc << 1) ^ 0x1021 : crc << 1;
    }
    return crc;
}
```

**Senders**

- MUST terminate every frame with `0x00`.
- SHOULD send a single `0x00` after opening the transport, so the receiver
  discards any partial frame left in its buffer.

**Receivers** MUST resynchronize as follows:

1. Accumulate bytes until a `0x00` is received.
2. An empty buffer (consecutive `0x00`s) is ignored.
3. If the buffer exceeds the maximum encoded frame size, discard bytes until
   the next `0x00`. The maximum encoded size is
   `MAX_PAYLOAD + 2 + ⌈(MAX_PAYLOAD + 2) / 254⌉`.
4. COBS-decode the buffer. If the result is invalid or shorter than 4 bytes
   (2 for the header plus 2 for the CRC), discard it.
5. If the CRC does not match, discard the frame.
6. Otherwise, deliver the PAYLOAD.

Discarded frames are dropped silently, with no error response. The sender
detects the loss with a timeout (§6.3). A resync loses at most one frame and
**has no effect on session state** (subscriptions, counters).

| COBS property       | Value                                    |
|---------------------|------------------------------------------|
| Delimiter           | `0x00` is always a frame boundary        |
| Worst-case overhead | ⌈N/254⌉ bytes, +1 for the delimiter      |
| Typical overhead    | 2 bytes for frames under 254 bytes       |
| Encode / decode     | O(n), single pass, can decode in place   |

### 2.2 Packet mode (USB bulk/HID, BLE GATT, UDP, WebSocket, …)

If the transport already delivers discrete, integrity-checked packets, each
packet carries exactly **one PAYLOAD** with no COBS, CRC or delimiter.
Both sides MUST agree on the mode out of band, typically fixed per transport.
If a single transport packet is smaller than `MAX_PAYLOAD`, the transport
binding is responsible for fragmentation. That is outside this spec.

## 3. Message Structure

Every PAYLOAD starts with a 2-byte header:

| MSG_TYPE | SEQ_ID | BODY |
|:--------:|:------:|:----:|
| 1 B      | 1 B    | …    |

- **MSG_TYPE**: message kind (§3.1).
- **SEQ_ID**: chosen by the host for requests (any value 0–255). Responses and
  errors echo the request's SEQ_ID. For `EVENT_NOTIFY`, it is the device's
  notification counter (§10.6).

### 3.1 Message Types

Requests are `0x01`–`0x7E`. The response to request `R` is `R | 0x80`.
`0x7F` is the only unsolicited message and `0xFF` is the error response to any
request.

| Req  | Rsp  | Name           | Description                        | Required |
|------|------|----------------|------------------------------------|----------|
| 0x01 | 0x81 | ENUM           | Device info, counts, start session | yes      |
| 0x02 | 0x82 | DESCRIBE_FUNC  | Descriptor of function N           | yes      |
| 0x03 | 0x83 | DESCRIBE_EVENT | Descriptor of event N              | events   |
| 0x04 | 0x84 | CALL           | Invoke a function                  | yes      |
| 0x05 | 0x85 | SUBSCRIBE      | Subscribe to an event              | events   |
| 0x06 | 0x86 | UNSUBSCRIBE    | Cancel a subscription              | events   |
| 0x07 | 0x87 | PING           | Liveness check, echoes body        | yes      |
| —    | 0x7F | EVENT_NOTIFY   | Unsolicited event, device → host   | events   |
| —    | 0xFF | ERROR          | Error response to any request      | yes      |

All requests travel host → device, and all responses and `EVENT_NOTIFY` travel
device → host. A host dispatcher needs only:

```
if msg_type == 0x7F:     route to event handler
elif msg_type & 0x80:    match SEQ_ID to pending request (incl. 0xFF)
else:                    ignore (host does not accept requests)
```

## 4. Type System

Each argument, return value and event field has a 1-byte **type tag**:

```
 bit   7   6 5    4 3 2 1 0
     ┌───┬──────┬───────────┐
     │ 0 │ CONT │ BASE TYPE │
     └───┴──────┴───────────┘
```

- **CONT**: `00` scalar, `01` fixed array `T[N]`, `10` dynamic array `T[]`, `11` reserved.
- **Bit 7**: reserved, MUST be 0.

### 4.1 Base Types

| Code      | Name  | Wire encoding                     | Notes                      |
|-----------|-------|-----------------------------------|----------------------------|
| 0x00      | —     | invalid                           | catches zeroed memory      |
| 0x01      | bool  | 1 byte: `0x00` false, `0x01` true | other values → malformed   |
| 0x02      | u8    | 1 byte                            |                            |
| 0x03      | i8    | 1 byte, two's complement          |                            |
| 0x04      | u16   | 2 bytes LE                        |                            |
| 0x05      | i16   | 2 bytes LE                        |                            |
| 0x06      | u32   | 4 bytes LE                        |                            |
| 0x07      | i32   | 4 bytes LE                        |                            |
| 0x08      | u64   | 8 bytes LE                        |                            |
| 0x09      | i64   | 8 bytes LE                        |                            |
| 0x0A      | f32   | 4 bytes LE, IEEE 754 binary32     |                            |
| 0x0B      | f64   | 8 bytes LE, IEEE 754 binary64     |                            |
| 0x0C      | str   | u16 LE byte length + UTF-8 bytes  | no terminator; scalar only |
| 0x0D      | bytes | u16 LE byte length + raw bytes    | scalar only                |
| 0x0E–0x1F | —     | reserved                          |                            |

### 4.2 Containers

| CONT | Tag         | Descriptor                         | Wire encoding               |
|------|-------------|------------------------------------|-----------------------------|
| 00   | `T`         | tag                                | one value                   |
| 01   | `0x20 \| T` | tag + **u16 LE N** (element count) | N values back to back       |
| 10   | `0x40 \| T` | tag                                | u16 LE count + count values |

In v0.4, containers are allowed only for base types `0x01`–`0x0B` (fixed-size
scalars). Arrays of `str`/`bytes` are reserved. Elements are packed with no
padding, so on a little-endian device a `f32[]` is a direct `memcpy` of a
`float` array.

Examples: `f32[]` = `0x4A`, `u8[16]` = `0x22` followed by `10 00`.

### 4.3 Packing Rules

Argument, return and event data are packed **back to back, with no type tags,
padding or alignment**, in descriptor order. Both sides know the layout from
discovery. A receiver MUST reject data that is too short or has trailing bytes
(error `MALFORMED`).

### 4.4 Strings in Descriptors (pstring) and Names

A **pstring** is `[u8 byte length][UTF-8 bytes]`. The prefix counts bytes, not
characters, so the maximum is 255 bytes. Length 0 means empty or omitted.

Function, event, argument, return and field **names** MUST match
`[A-Za-z_][A-Za-z0-9_]*`. They MUST be 1–63 bytes long and MUST be unique
within their scope: functions among functions, events among events, and
entries within one descriptor. This lets bindings expose them directly as
identifiers (`dev.read_adc(channel=3)`).

## 5. Enumeration

### 5.1 ENUM_REQ (0x01)

| 0x01 | SEQ_ID |
|:----:|:------:|
| 1 B  | 1 B    |

No body. Receiving ENUM_REQ **starts a new session** (§6).

### 5.2 ENUM_RSP (0x81)

| Field        | Size    | Description                                                              |
|--------------|---------|--------------------------------------------------------------------------|
| `0x81`       | 1 B     | MSG_TYPE                                                                 |
| SEQ_ID       | 1 B     |                                                                          |
| VERSION      | 1 B     | Protocol version, `0x04` for this document. A host MUST NOT proceed past ENUM if it does not support the version. |
| NFUNC        | 1 B     | Number of functions; IDs are `0 … NFUNC-1`.                              |
| NEVT         | 1 B     | Number of events; IDs are `0 … NEVT-1`. `0` if events are not supported. |
| MAX_PAYLOAD  | u16 LE  | Largest PAYLOAD (§2) the device can receive **and** will send. MUST be ≥ 64. Every response the device sends, including descriptors, MUST fit. |
| MAX_INFLIGHT | 1 B     | Maximum number of requests the host may have outstanding (≥ 1).         |
| BOOT_ID      | u32 LE  | Changes every time the device boots (random or incrementing counter). A change tells the host the device reset. |
| SCHEMA_HASH  | u32 LE  | CRC-32 of the device's schema (§5.3).                                    |
| DEVICE_NAME  | pstring | Human-readable device name (any UTF-8, not restricted to an identifier). |

### 5.3 Schema Hash

`SCHEMA_HASH` is the CRC-32 (IEEE 802.3: the same as `zlib.crc32`, Python
`binascii.crc32`, check value `crc32("123456789") = 0xCBF43926`) over the
concatenation of:

```
   DESCRIBE_FUNC_RSP[0].body  || … || DESCRIBE_FUNC_RSP[NFUNC-1].body
|| DESCRIBE_EVENT_RSP[0].body || … || DESCRIBE_EVENT_RSP[NEVT-1].body
```

Here `body` is the payload without its 2-byte header (MSG_TYPE, SEQ_ID), i.e.
starting at the ID byte. `DEVICE_NAME` is not included. The device can compute
it at build time or once at boot.

Uses:

- **Caching**: a host that has seen this hash before MAY skip DESCRIBE
  requests and reuse its cached schema.
- **Static bindings**: code generated from a schema file (§12) checks the hash
  at connect time, so a firmware update that renumbers or retypes functions
  fails loudly instead of corrupting calls.

## 6. Sessions, Ordering and Timeouts

### 6.1 Sessions

A session is the device's per-connection state: active subscriptions and the
`EVENT_NOTIFY` counter.

- A session **starts** when the device receives `ENUM_REQ`. All subscriptions
  are cleared and the notification counter resets to 0.
- A session **ends** when the transport closes, when the device reboots, or
  when the next `ENUM_REQ` arrives.
- Framing errors and resynchronization (§2.1) do **not** affect the session.
- A device MAY accept other requests before the first `ENUM_REQ`, but it MUST
  NOT send `EVENT_NOTIFY` outside a session.
- On a transport that supports multiple simultaneous hosts (e.g. TCP), each
  connection has its own session.

A host SHOULD send `ENUM_REQ` first on every connection. If `BOOT_ID` differs
from the previous connection, the device has rebooted, and the host MUST
re-subscribe to any events it needs. Because `ENUM_REQ` resets the session,
use `PING_REQ` for liveness checks.

### 6.2 Ordering and Pipelining

- The host MUST NOT have more than `MAX_INFLIGHT` requests outstanding.
  Before ENUM_RSP is received, assume 1.
- The device MUST send exactly one response (`R|0x80` or `ERROR`) for every
  request it receives intact, and MUST respond in the order requests arrived.
- If the device receives more requests than it can queue, it SHOULD reply
  with `ERROR BUSY`.
- `EVENT_NOTIFY` frames MAY be interleaved between responses at any point.
- SEQ_IDs of outstanding requests SHOULD be distinct. The usual host
  implementation is a wrapping counter.

### 6.3 Timeouts and Retries

Lost frames are detected only by a timeout. Hosts SHOULD use a default
response timeout of **1000 ms** and allow per-call overrides for slow functions.
A host MAY retry ENUM, DESCRIBE_*, SUBSCRIBE, UNSUBSCRIBE and PING freely,
since they are idempotent. A CALL MUST NOT be retried automatically unless the
application declares that function idempotent. After a timeout, a late
response with a stale SEQ_ID MUST be ignored.

### 6.4 PING_REQ (0x07) / PING_RSP (0x87)

| 0x07 | SEQ_ID | DATA        |
|:----:|:------:|:-----------:|
| 1 B  | 1 B    | 0–8 bytes   |

The device replies with `0x87`, the same SEQ_ID and the same DATA bytes.
PING has no side effects.

## 7. Function Descriptor

### 7.1 DESCRIBE_FUNC_REQ (0x02)

| 0x02 | SEQ_ID | FUNC_ID |
|:----:|:------:|:-------:|
| 1 B  | 1 B    | 1 B     |

### 7.2 DESCRIBE_FUNC_RSP (0x82)

| 0x82 | SEQ_ID | FUNC_ID | FUNC_NAME | FUNC_DESC | NUM_ARGS | ARG… | NUM_RETS | RET… |
|:----:|:------:|:-------:|:---------:|:---------:|:--------:|:----:|:--------:|:----:|
| 1 B  | 1 B    | 1 B     | pstring   | pstring   | 1 B      | entries | 1 B   | entries |

### 7.3 Entry Format (shared by arguments, returns and event fields)

| Field | Size    | Description                                                         |
|-------|---------|---------------------------------------------------------------------|
| TYPE  | 1 B     | Type tag (§4).                                                      |
| N     | u16 LE  | Present **only** when `CONT = 01`: element count of the fixed array. |
| NAME  | pstring | Identifier (§4.4), e.g. `voltage`.                                  |
| DESC  | pstring | Free-text description; empty to omit.                               |
| UNIT  | pstring | Physical unit, e.g. `V`, `mA`, `°C`, `Hz`; empty if none. SHOULD use SI / UCUM symbols. |

A function with no return values has `NUM_RETS = 0`, and its CALL_RSP has an
empty body. Multiple return values are allowed. Bindings SHOULD expose them as
a named structure (§12).

## 8. Function Call

### 8.1 CALL_REQ (0x04)

| 0x04 | SEQ_ID | FUNC_ID | ARG_DATA…        |
|:----:|:------:|:-------:|:----------------:|
| 1 B  | 1 B    | 1 B     | packed per §4.3  |

### 8.2 CALL_RSP (0x84)

| 0x84 | SEQ_ID | FUNC_ID | RET_DATA…        |
|:----:|:------:|:-------:|:----------------:|
| 1 B  | 1 B    | 1 B     | packed per §4.3  |

## 9. Errors

### 9.1 ERROR_RSP (0xFF)

| 0xFF | SEQ_ID | REQ_TYPE | ERROR_CODE | ERROR_MSG |
|:----:|:------:|:--------:|:----------:|:---------:|
| 1 B  | 1 B    | 1 B      | 1 B        | pstring   |

`ERROR_RSP` may be sent in reply to any request. `SEQ_ID` and `REQ_TYPE` echo
the failing request. `ERROR_MSG` is optional human-readable detail, and an
empty pstring is allowed.

| Code      | Name          | Meaning                                                 |
|-----------|---------------|---------------------------------------------------------|
| 0x01      | UNKNOWN_MSG   | MSG_TYPE not recognised or not implemented              |
| 0x02      | UNKNOWN_FUNC  | FUNC_ID ≥ NFUNC                                         |
| 0x03      | UNKNOWN_EVENT | EVENT_ID ≥ NEVT (also used when events are unsupported) |
| 0x04      | MALFORMED     | Body too short, trailing bytes, invalid bool/UTF-8, …   |
| 0x05      | TOO_LARGE     | Request or would-be response exceeds MAX_PAYLOAD        |
| 0x06      | BUSY          | Temporarily unable to process; host MAY retry later     |
| 0x07      | NO_RESOURCES  | E.g. no room for another subscription                   |
| 0x08      | EXEC_FAILED   | Function ran and failed (generic)                       |
| 0x09–0x7F | —             | Reserved for future protocol use                        |
| 0x80–0xFE | APP_ERROR     | Application-defined, meaning documented per device      |
| 0xFF      | UNSPECIFIED   | Generic error                                           |

Bindings SHOULD raise an exception (or return `Err`) that carries the code,
name and message.

## 10. Events

Events are device-initiated, asynchronous notifications, such as a threshold
crossed, a button pressed or a buffer filled. Event IDs are a separate
namespace from function IDs. Event support is optional (§11).

**Lifecycle**: `ENUM` → `DESCRIBE_EVENT` → `SUBSCRIBE` → `EVENT_NOTIFY`… →
`UNSUBSCRIBE` (or session end).

### 10.1 DESCRIBE_EVENT_REQ (0x03)

| 0x03 | SEQ_ID | EVENT_ID |
|:----:|:------:|:--------:|
| 1 B  | 1 B    | 1 B      |

### 10.2 DESCRIBE_EVENT_RSP (0x83)

| 0x83 | SEQ_ID | EVENT_ID | EVENT_NAME | EVENT_DESC | NUM_FIELDS | FIELD… |
|:----:|:------:|:--------:|:----------:|:----------:|:----------:|:------:|
| 1 B  | 1 B    | 1 B      | pstring    | pstring    | 1 B        | entries |

FIELD entries use the format in §7.3.

### 10.3 SUBSCRIBE_REQ (0x05) / SUBSCRIBE_RSP (0x85)

| 0x05 / 0x85 | SEQ_ID | EVENT_ID |
|:-----------:|:------:|:--------:|
| 1 B         | 1 B    | 1 B      |

Subscribing is **idempotent**. Subscribing to an event that is already
subscribed succeeds with no effect. The response echoes `EVENT_ID`. The device
MUST NOT send a notification for that event before sending SUBSCRIBE_RSP.

### 10.4 UNSUBSCRIBE_REQ (0x06) / UNSUBSCRIBE_RSP (0x86)

| 0x06 / 0x86 | SEQ_ID | EVENT_ID |
|:-----------:|:------:|:--------:|
| 1 B         | 1 B    | 1 B      |

Unsubscribing is **idempotent**. Unsubscribing from an event that is not
subscribed succeeds. The device MUST NOT send notifications for that event
after sending UNSUBSCRIBE_RSP.

### 10.5 EVENT_NOTIFY (0x7F)

| 0x7F | NSEQ | EVENT_ID | EVENT_DATA…      |
|:----:|:----:|:--------:|:----------------:|
| 1 B  | 1 B  | 1 B      | packed per §4.3  |

### 10.6 Notification Counter

`NSEQ` is a per-session counter shared by all events. It starts at 0 when the
session starts, increments by 1 (mod 256) for every `EVENT_NOTIFY` that the
device *intends* to send, including any it drops because its transmit buffer
is full. A gap in `NSEQ` therefore tells the host that notifications were
lost. Bindings SHOULD report it, e.g. as a `dropped` count.

### 10.7 Standard Events (convention)

These are discovered by name like any other event; they have no reserved IDs.
Hosts and tools SHOULD recognise them:

| Name  | Fields                | Purpose                                                                                                                       |
|-------|-----------------------|-------------------------------------------------------------------------------------------------------------------------------|
| `log` | `u8 level`, `str msg` | Device log output. Levels: 0 error, 1 warn, 2 info, 3 debug. Lets firmware print over the same link without breaking framing. |

## 11. Conformance

| Profile    | MUST implement                                                                                       |
|------------|------------------------------------------------------------------------------------------------------|
| **Core**   | Stream or packet framing, ENUM, DESCRIBE_FUNC, CALL, PING, ERROR (`UNKNOWN_MSG` for anything else). |
| **Events** | Core + DESCRIBE_EVENT, SUBSCRIBE, UNSUBSCRIBE, EVENT_NOTIFY.                                         |

A Core-only device reports `NEVT = 0` and answers the event requests with
`UNKNOWN_EVENT` or `UNKNOWN_MSG`.

A host implementation MUST support both profiles and every type in §4.

## 12. Language Bindings (non-normative)

### 12.1 Type Mapping

| UFP     | C / C++                                          | Rust                                 | Python                    | JS / TS                  |
|---------|--------------------------------------------------|--------------------------------------|---------------------------|--------------------------|
| bool    | `bool`                                           | `bool`                               | `bool`                    | `boolean`                |
| u8…u32  | `uint*_t`                                        | `u8…u32`                             | `int`                     | `number`                 |
| i8…i32  | `int*_t`                                         | `i8…i32`                             | `int`                     | `number`                 |
| u64/i64 | `(u)int64_t`                                     | `u64`/`i64`                          | `int`                     | `bigint`                 |
| f32/f64 | `float`/`double`                                 | `f32`/`f64`                          | `float`                   | `number`                 |
| str     | `const char*` + len / `std::string_view`         | `&str` / `String`                    | `str`                     | `string`                 |
| bytes   | `const uint8_t*` + len / `std::span<const uint8_t>` | `&[u8]` / `Vec<u8>`               | `bytes`                   | `Uint8Array`             |
| T[N]    | `T[N]` / `std::array<T,N>`                       | `[T; N]`                             | `list` or `numpy.ndarray` | `TypedArray` (e.g. `Float32Array`) |
| T[]     | ptr + count / `std::span<T>`                     | `&[T]` / `Vec<T>` / `heapless::Vec`  | `list` or `numpy.ndarray` | `TypedArray`             |
| returns | out-params / struct                              | tuple or struct                      | `namedtuple`              | object `{raw, voltage}`  |

`bool[]` uses one byte per element and maps to `Uint8Array` in JS.

### 12.2 Canonical JSON Schema

Tools SHOULD use this format for caching, code generation, mocks and UIs
(`ufp dump PORT > board.json`):

```json
{
  "ufp": 4,
  "device": "SensorBoard",
  "schema_hash": "0x9E87149B",
  "functions": [
    { "id": 0, "name": "read_adc", "desc": "Read one ADC channel",
      "args": [ { "name": "channel", "type": "u8" } ],
      "rets": [ { "name": "raw", "type": "u16" },
                { "name": "voltage", "type": "f32", "unit": "V" } ] }
  ],
  "events": [
    { "id": 0, "name": "threshold_exceeded",
      "fields": [ { "name": "channel", "type": "u8" },
                  { "name": "voltage", "type": "f32", "unit": "V" } ] }
  ]
}
```

Type strings: base names from §4.1, `"f32[]"` for dynamic arrays and `"u8[16]"`
for fixed arrays. Omitted `desc` or `unit` means an empty string.

### 12.3 Recommended API Shapes

**Device, C (core library)**: no heap and no global state. The application
feeds received bytes in and supplies a transmit callback. Descriptor tables are
`const`, so they go in flash (`PROGMEM` on AVR).

```c
static const ufp_entry_t adc_args[] = { UFP_ARG(UFP_U8, "channel") };
static const ufp_entry_t adc_rets[] = { UFP_ARG(UFP_U16, "raw"), UFP_ARG_U(UFP_F32, "voltage", "V") };
static const ufp_func_t funcs[] = { UFP_FUNC(read_adc, "Read one ADC channel", adc_args, adc_rets) };
// in the main loop / UART ISR:
ufp_feed(&ctx, byte);           // dispatches complete frames, calls tx()
ufp_notify(&ctx, EVT_THRESHOLD, &payload, sizeof payload);
```

**Device, C++ / Arduino**: types are inferred from the function signature.

```cpp
std::tuple<uint16_t, float> read_adc(uint8_t channel);
ufp.add("read_adc", read_adc, {"channel"}, {"raw", "voltage:V"});
```

**Device, Rust**: `no_std`, `heapless`, attribute macro.

```rust
#[ufp::export(desc = "Read one ADC channel", rets(raw, voltage(unit = "V")))]
fn read_adc(channel: u8) -> (u16, f32) { … }
```

**Host, Python**: sync and asyncio variants, with dynamic attributes built
from discovery.

```python
dev = ufp.connect("/dev/ttyACM0")            # ENUM + DESCRIBE (cached by schema hash)
raw, v = dev.read_adc(channel=3)             # namedtuple(raw, voltage)
@dev.on("threshold_exceeded")
def _(channel, voltage): ...
```

**Host, JS/TS**: Web Serial / WebUSB / WebSocket, with Promises and async
iterators.

```ts
const dev = await ufp.connect(await navigator.serial.requestPort());
const { raw, voltage } = await dev.call.read_adc(3);
for await (const e of dev.events("threshold_exceeded")) { … }
```

**Host, Rust**: dynamic client plus a `build.rs` code generator that reads
`board.json` and emits a typed client which checks `SCHEMA_HASH` on connect.

**CLI**: `ufp list | describe | call FN ARGS… | monitor | dump`.

## 13. Worked Example and Test Vectors

All vectors are exact and were generated by a reference encoder. **Payload** is
the message. **Wire** is the stream-mode encoding (§2.1): `COBS(payload ||
crc16_le) 00`. In packet mode (§2.2), only the payload is sent.

### 13.1 Device

```c
// func 0: read_adc(u8 channel) -> (u16 raw, f32 voltage [V])   "Read one ADC channel"
// func 1: set_led(u8 id, bool state) -> ()
// func 2: read_samples(u8 channel, u16 count) -> (f32[] samples [V])   "Burst-read samples"
// event 0: threshold_exceeded(u8 channel, f32 voltage [V])
// MAX_PAYLOAD = 128, MAX_INFLIGHT = 1, BOOT_ID = 0x1234ABCD, name "SensorBoard"
// SCHEMA_HASH = 0x9E87149B
```

### 13.2 Enumeration

ENUM_REQ:
```
payload: 01 01
wire:    05 01 01 1F 3E 00
```

ENUM_RSP:
```
payload: 81 01 04 03 01 80 00 01 CD AB 34 12 9B 14 87 9E 0B 53 65 6E 73 6F 72 42 6F 61 72 64
         │  │  │  │  │  └─┬─┘ │  └────┬────┘ └────┬────┘ └──────────── "SensorBoard" ─────┘
         │  │  │  │  │    │   │       │           └─ SCHEMA_HASH = 0x9E87149B
         │  │  │  │  │    │   │       └─ BOOT_ID = 0x1234ABCD
         │  │  │  │  │    │   └─ MAX_INFLIGHT = 1
         │  │  │  │  │    └─ MAX_PAYLOAD = 128
         │  │  │  │  └─ NEVT = 1
         │  │  │  └─ NFUNC = 3
         │  │  └─ VERSION = 4
         │  └─ SEQ = 1
         └─ ENUM_RSP
wire:    07 81 01 04 03 01 80 18 01 CD AB 34 12 9B 14 87 9E 0B 53 65 6E 73 6F 72 42 6F 61 72 64 3A 51 00
```

### 13.3 Function Discovery

DESCRIBE_FUNC_REQ for function 0:
```
payload: 02 02 00
wire:    03 02 02 03 9E C4 00
```

DESCRIBE_FUNC_RSP for `read_adc` (65 bytes):
```
payload: 82 02 00                               header, FUNC_ID=0
         08 72 65 61 64 5F 61 64 63             NAME "read_adc"
         14 52 65 61 64 20 6F 6E 65 20 41 44    DESC "Read one ADC channel"
            43 20 63 68 61 6E 6E 65 6C
         01                                     NUM_ARGS=1
         02 07 63 68 61 6E 6E 65 6C 00 00       u8  "channel"  desc=""  unit=""
         02                                     NUM_RETS=2
         04 03 72 61 77 00 00                   u16 "raw"      desc=""  unit=""
         0A 07 76 6F 6C 74 61 67 65 00 01 56    f32 "voltage"  desc=""  unit="V"
wire:    03 82 02 29 08 72 65 61 64 5F 61 64 63 14 52 65 61 64 20 6F 6E 65 20 41
         44 43 20 63 68 61 6E 6E 65 6C 01 02 07 63 68 61 6E 6E 65 6C 01 07 02 04
         03 72 61 77 01 0A 0A 07 76 6F 6C 74 61 67 65 05 01 56 1A 28 00
```

DESCRIBE_FUNC_RSP for `read_samples` (SEQ=4), showing a dynamic array:
```
payload: 82 04 02                               header, FUNC_ID=2
         0C 72 65 61 64 5F 73 61 6D 70 6C 65 73 NAME "read_samples"
         12 42 75 72 73 74 2D 72 65 61 64 20    DESC "Burst-read samples"
            73 61 6D 70 6C 65 73
         02                                     NUM_ARGS=2
         02 07 63 68 61 6E 6E 65 6C 00 00       u8  "channel"
         04 05 63 6F 75 6E 74 00 00             u16 "count"
         01                                     NUM_RETS=1
         4A 07 73 61 6D 70 6C 65 73 00 01 56    f32[] "samples" unit="V"
wire:    2E 82 04 02 0C 72 65 61 64 5F 73 61 6D 70 6C 65 73 12 42 75 72 73 74 2D
         72 65 61 64 20 73 61 6D 70 6C 65 73 02 02 07 63 68 61 6E 6E 65 6C 01 08
         04 05 63 6F 75 6E 74 01 0B 01 4A 07 73 61 6D 70 6C 65 73 05 01 56 C1 37
         00
```

### 13.4 Event Discovery

DESCRIBE_EVENT_RSP for `threshold_exceeded` (SEQ=5):
```
payload: 83 05 00                               header, EVENT_ID=0
         12 74 68 72 65 73 68 6F 6C 64 5F 65    NAME "threshold_exceeded"
            78 63 65 65 64 65 64
         00                                     DESC ""
         02                                     NUM_FIELDS=2
         02 07 63 68 61 6E 6E 65 6C 00 00       u8  "channel"
         0A 07 76 6F 6C 74 61 67 65 00 01 56    f32 "voltage" unit="V"
wire:    03 83 05 14 12 74 68 72 65 73 68 6F 6C 64 5F 65 78 63 65 65 64 65 64 0B
         02 02 07 63 68 61 6E 6E 65 6C 01 0A 0A 07 76 6F 6C 74 61 67 65 05 01 56
         51 4E 00
```

### 13.5 Subscribe

```
SUBSCRIBE_REQ  payload: 05 06 00     wire: 03 05 06 03 CA 8D 00
SUBSCRIBE_RSP  payload: 85 06 00     wire: 03 85 06 03 90 B6 00
```

### 13.6 Calls

`read_adc(3)` → `(2765, 3.325)`:
```
CALL_REQ  payload: 04 07 00 03
          wire:    03 04 07 04 03 C2 FB 00
CALL_RSP  payload: 84 07 00 CD 0A CD CC 54 40
                   │  │  │  └─┬─┘ └───┬───┘
                   │  │  │    │       └─ voltage = 3.325 (f32 LE, 0x4054CCCD)
                   │  │  │    └─ raw = 2765 (u16 LE, 0x0ACD)
                   │  │  └─ FUNC_ID = 0
                   │  └─ SEQ = 7
                   └─ CALL_RSP
          wire:    03 84 07 09 CD 0A CD CC 54 40 E1 19 00
```

`set_led(0, true)` → `()`:
```
CALL_REQ  payload: 04 08 01 00 01        wire: 04 04 08 01 04 01 D8 3A 00
CALL_RSP  payload: 84 08 01              wire: 06 84 08 01 8E B2 00
```

`read_samples(3, 2)` → `([1.5, -0.25])`:
```
CALL_REQ  payload: 04 09 02 03 02 00
          wire:    06 04 09 02 03 02 03 97 72 00
CALL_RSP  payload: 84 09 02 02 00 00 00 C0 3F 00 00 80 BE
                            └─┬─┘ └───┬───┘ └───┬───┘
                              │       │         └─ -0.25
                              │       └─ 1.5
                              └─ count = 2
          wire:    05 84 09 02 02 01 01 03 C0 3F 01 05 80 BE 4F 74 00
```

### 13.7 Event Notification

First notification of the session (NSEQ=0): channel 3 at 3.325 V.
```
payload: 7F 00 00 03 CD CC 54 40
         │  │  │  │  └───┬───┘
         │  │  │  │      └─ voltage = 3.325
         │  │  │  └─ channel = 3
         │  │  └─ EVENT_ID = 0
         │  └─ NSEQ = 0
         └─ EVENT_NOTIFY
wire:    02 7F 01 08 03 CD CC 54 40 29 E5 00
```

### 13.8 Error

CALL_REQ with an unknown FUNC_ID, answered with UNKNOWN_FUNC:
```
payload: FF 0A 04 02 10 75 6E 6B 6E 6F 77 6E 20 66 75 6E 63 74 69 6F 6E
         │  │  │  │  └──────────────── "unknown function" ───────────────┘
         │  │  │  └─ ERROR_CODE = 0x02 UNKNOWN_FUNC
         │  │  └─ REQ_TYPE = 0x04 CALL_REQ
         │  └─ SEQ = 10
         └─ ERROR_RSP
wire:    18 FF 0A 04 02 10 75 6E 6B 6E 6F 77 6E 20 66 75 6E 63 74 69 6F 6E B2 AF 00
```

### 13.9 Ping

```
PING_REQ  payload: 07 0B DE AD     wire: 07 07 0B DE AD 73 77 00
PING_RSP  payload: 87 0B DE AD     wire: 07 87 0B DE AD 4B AA 00
```

### 13.10 Flow

```
HOST                                          DEVICE
  │── ENUM_REQ ───────────────────────────────>│  session starts
  │<── ENUM_RSP (3 funcs, 1 evt, hash) ────────│
  │    hash cached? ── yes → skip DESCRIBE     │
  │── DESCRIBE_FUNC_REQ (0, 1, 2) ────────────>│
  │<── DESCRIBE_FUNC_RSP × 3 ──────────────────│
  │── DESCRIBE_EVENT_REQ (0) ─────────────────>│
  │<── DESCRIBE_EVENT_RSP ─────────────────────│
  │── SUBSCRIBE_REQ (0) ──────────────────────>│
  │<── SUBSCRIBE_RSP (0) ──────────────────────│
  │── CALL_REQ read_adc(3) ───────────────────>│
  │<═══ EVENT_NOTIFY (nseq=0) ═════════════════│  may interleave
  │<── CALL_RSP (2765, 3.325) ─────────────────│
  │── PING_REQ ───────────────────────────────>│  liveness, no side effects
  │<── PING_RSP ───────────────────────────────│
  │── UNSUBSCRIBE_REQ (0) ────────────────────>│
  │<── UNSUBSCRIBE_RSP (0) ────────────────────│
```


## 14. Design Decisions

| Choice                                  | Rationale                                                                 |
|-----------------------------------------|---------------------------------------------------------------------------|
| Little-endian                           | Native on virtually all MCUs (Cortex-M, ESP32, RISC-V, AVR) and hosts (x86, ARM). No byte swapping, and arrays are a direct `memcpy`. |
| COBS + CRC-16 framing (stream mode)     | `0x00` is always a frame boundary; overhead is deterministic and resync is trivial. |
| Packet mode                             | Transports that already frame and check packets don't pay for COBS/CRC twice. |
| Response = request \| 0x80              | Generic dispatch with no lookup table; new message types get response codes for free. |
| No tags in CALL / EVENT data            | Both sides know the layout from discovery, which keeps payloads small.   |
| Composable type tag                     | Arrays of any scalar with no separate code range; decoders are a 2-level switch. |
| Identifier-only names                   | Names map 1:1 to Python, Rust, JS and C++ identifiers, with no mangling. |
| `UNIT` in descriptors                   | Generated UIs and plots are useful without extra configuration.          |
| `SCHEMA_HASH`                           | Discovery can be cached, and static codegen is checked at connect time.  |
| `BOOT_ID`                               | Host detects device resets and restores subscriptions.                   |
| `MAX_PAYLOAD`, `MAX_INFLIGHT`           | Embedded devices declare their real buffer limits; hosts don't guess.    |
| Explicit session (ENUM starts it)       | Session state no longer depends on framing noise; behaviour is predictable. |
| Idempotent subscribe/unsubscribe        | Reconnect logic is "subscribe to what I want", with no error handling.   |
| Per-session NSEQ, counts drops          | Host detects lost notifications without acknowledgements.                |
| 1-byte IDs and SEQ                      | 255 functions/events per device, and pipelining depth is far below 256.  |
| `log` as a standard event               | Firmware gets printf over the same link without a separate channel or protocol. |

## Changelog

**v0.4** (wire `VERSION = 0x04`). Breaking changes; v0.4 cannot talk to v0.3 or earlier.

- All multi-byte values are now **little-endian**.
- CRC is named precisely: CRC-16/CCITT-FALSE, sent little-endian.
- Message codes are renumbered: response = request | `0x80`, `EVENT_NOTIFY` = `0x7F`,
  `ERROR_RSP` = `0xFF`.
- `PING_REQ`/`PING_RSP` added.
- ENUM_RSP gained `MAX_PAYLOAD`, `MAX_INFLIGHT`, `BOOT_ID` and `SCHEMA_HASH`.
- Sessions are defined explicitly (§6): `ENUM_REQ` starts one. Framing resync no
  longer affects subscriptions.
- The type tag is composable (base type + container bits). Fixed and dynamic
  arrays of scalars are now supported. `char`, `void`, `u128` and `i128` are removed.
- Descriptor entries gained a `UNIT` string.
- Names are restricted to identifiers (§4.4).
- SUBSCRIBE/UNSUBSCRIBE are idempotent. The errors "already subscribed" and
  "not subscribed" are removed.
- Error codes are renumbered. `ERROR_RSP` echoes the request's `MSG_TYPE`.
  `0x80`–`0xFE` is reserved for application errors.
- Added a packet transport mode, a conformance section, a canonical JSON schema,
  language mappings and full wire-level test vectors.

**v0.3**: events (`EVENT_COUNT`, DESCRIBE_EVENT, SUBSCRIBE, UNSUBSCRIBE, EVENT_NOTIFY).
