# UFP for Arduino

Device side of the Universal Function Protocol ([`docs.md`](../../docs.md), v0.4),
stream mode (COBS + CRC-16), over any Arduino `Stream`: usually USB serial.
Pairs with the Python host in this repo (`ufp.connect("COM3")`).

Installation: copy or link this `UFP` folder into your Arduino `libraries` folder
(e.g. `Documents/Arduino/libraries/UFP`), or pass `--library path/to/UFP` to `arduino-cli`.

## Example

```cpp
#include <UFP.h>

UFPDevice<128> ufp("SensorBoard");          // MAX_PAYLOAD = 128 bytes
UFPEvent<uint8_t, float> threshold;

uint16_t read_adc(uint8_t channel, float& voltage) {    // T& parameters are extra returns
  uint16_t raw = analogRead(channel);
  voltage = raw * 3.3f / 1023;
  return raw;
}

void setup() {
  Serial.begin(115200);
  ufp.add("read_adc", read_adc, "channel", "raw, voltage:V", "Read one ADC channel");
  threshold = ufp.event<uint8_t, float>("threshold_exceeded", "channel, voltage:V");
  ufp.enableLog();
  ufp.begin(Serial);
}

void loop() {
  ufp.loop();                                   // call often
  if (analogRead(0) > 930) threshold.emit(0, 3.0f);   // sent only if the host subscribed
}
```

```python
import ufp
board = ufp.connect("COM3")
raw, volts = board.read_adc(0)
board.on("threshold_exceeded", lambda channel, voltage: print(channel, voltage))
```

See `examples/SensorBoard` for the device from docs.md §13.

## API

`UFPDevice<MaxPayload = 128, MaxFunctions = 16, MaxEvents = 4, TxBuffer = 2 frames> dev("name")`

| Call | Description |
|------|-------------|
| `dev.add(name, fn, args, rets, desc)` | Register a function (or a captureless lambda). Returns false if the table is full. |
| `dev.event<T...>(name, fields, desc)` | Register an event; returns a `UFPEvent<T...>` handle. |
| `ev.emit(values...)` | Send if subscribed. False if not subscribed or the transmit buffer is full (counted in NSEQ and `droppedEvents()`). |
| `dev.enableLog()`, `dev.log(level, msg)`, `dev.logPrintf(level, fmt, ...)` | Standard `log` event (`UFP_LOG_ERROR` … `UFP_LOG_DEBUG`). |
| `dev.begin(Serial)` | Start serving. The stream must already be begun. |
| `dev.loop()` | Read requests, run functions, send replies. Non-blocking. |
| `dev.fail(code, msg)` | From inside a function: reply with ERROR instead of the return values. `UFP_ERR_EXEC_FAILED` or an application code `0x80`–`0xFE`. |
| `dev.setBootId(id)`, `dev.setMaxInflight(n)` | Override the random boot ID; allow host pipelining. |
| `dev.inSession()`, `dev.subscribed(id)`, `dev.schemaHash()` | State. |

**Names** (`args`, `rets`, `fields`) are comma-separated, one per entry, each
`name`, `name:unit` or `name:unit:description` (`"current::0-1 of full scale"`
has no unit). Missing names become `arg0`, `ret0`, … Names must be identifiers.

**Parameters**: by value or `const T&` are arguments, in order. Non-const `T&`
are return values, after the C++ return value if it is not `void`.

| C++ | UFP |
|-----|-----|
| `bool` | bool |
| integer types | u8 … i64, by size and signedness (`char` is not allowed: use `uint8_t`/`int8_t`) |
| `float`, `double` | f32, f64 (`double` is f32 on AVR) |
| `UFPStr` | str. As an argument it is **not** null-terminated: use `.len` or `.copyTo(buf, size)` |
| `const char*` | str, return values only |
| `UFPBytes` | bytes |
| `UFPSpan<T>` | `T[]`. Arguments point into the receive buffer; read elements with `[i]` (handles misalignment) |
| `UFPArray<T, N>` | `T[N]` |

Spans returned from a function must point to memory that is still valid after
it returns (a global or `static` array).

## Notes

- Events must be emitted from the main loop, not from interrupts.
- The session ends on the next `ENUM`, or when the USB port closes (DTR drops) on
  cores where that check is cheap (not on AVR/SAMD, whose check calls `delay(10)`).
- Strings stay in RAM (no `PROGMEM`); on AVR use `UFPDevice<64, 8, 2>` and short descriptions.
- Invalid UTF-8 in `str` arguments is not rejected.
- Requests are served one at a time; USB flow control holds the rest, so
  `setMaxInflight(n)` is safe on USB CDC.

## Tests

The library is tested on a PC against the docs.md §13 wire vectors (byte for
byte, including the schema hash) and end to end with the Python host, under
AddressSanitizer and UBSan.
