# UFP: Universal Function Protocol

Typed, self-describing RPC and events between a host and a device, over serial, TCP or any byte stream. The protocol is specified [here](docs.md) (v0.4).

This repository contains Python and Arduino implementations.

```bash
pip install -e .            # or: pip install -e ".[serial]"
python examples/demo.py     # in-process demo, no hardware needed
```

## Device

Here is a bare minimum example of an Arduino board exposing one function:

```cpp
#include <UFP.h>

#define PIN_LED_USER 25

// 256 B fits a queue_blocks call with 12 blocks (the host sends 10)
UFPDevice<256> ufp("simple_led");

void set_led(int led_val){
  digitalWrite(PIN_LED_USER, !led_val);
}

void setup() {
  pinMode(PIN_LED_USER, OUTPUT);

  ufp.add("set_led", set_led, "value:0/1", "", "Turn LED on");
  Serial.begin(115200);
  ufp.begin(Serial);
}


void loop() {
  ufp.loop();
}
```

## Host

Here is an example Python script communicating with the Arduino example provided above:

```python
import time
import ufp


def main():
    port = "COM10"
    timeout = 1.0

    dev = ufp.connect(port, timeout=timeout)

    dev.set_led(1)
    time.sleep(0.5)
    dev.set_led(0)


if __name__ == "__main__":
    main()
```

- Errors raised on the device arrive as `ufp.RemoteError` with `.code` and `.message`.
  To send your own code, raise `ufp.RemoteError(0x80, "overvoltage")` on the device.
- A call that times out raises `ufp.Timeout`. The default timeout is 1 s; set it with
  `connect(..., timeout=)` or per call with `board.read_adc.call(3, timeout=5)`.
- `ufp.connect(device)` runs a `Device` object in-process, which is handy for tests.
- Schemas are cached by hash for the life of the process.
  `board.schema.save("board.json")` writes the schema to a file, and
  `connect(..., schema="board.json")` skips discovery and checks the hash.

## Types

| Annotation                               | UFP type      | Python value     |
|------------------------------------------|---------------|------------------|
| `bool`                                   | bool          | `bool`           |
| `ufp.u8` … `ufp.u64`, `ufp.i8` … `ufp.i64` | ints        | `int`            |
| `ufp.f32`, `ufp.f64`                     | floats        | `float`          |
| `int` / `float`                          | i32 / f64     | `int` / `float`  |
| `str` / `bytes`                          | str / bytes   | `str` / `bytes`  |
| `list[T]`                                | `T[]`         | `list`           |
| `ufp.array(T, 16)`                       | `T[16]`       | `list`           |
| `Annotated[T, ufp.unit("V"), "text"]`    | adds unit and description |      |

Multiple return values come from a `NamedTuple`, or from `tuple[A, B]` with
`@board.function(returns="a, b")`.

## Command line

```bash
ufp list    tcp://localhost:9000           # or: python -m ufp ...
ufp call    COM3 read_adc 3
ufp monitor COM3                           # print every event
ufp dump    COM3 -o board.json             # JSON schema (docs.md §12.2)
```

## Layout

### Python implementation

| Path | Contents |
|------|----------|
| `ufp/wire.py` | COBS + CRC framing |
| `ufp/types.py` | Type tags, packing |
| `ufp/schema.py` | Descriptors, hash, JSON |
| `ufp/device.py` | `Device`, sessions, `serve()` |
| `ufp/host.py` | `connect()`, `Client` |
| `ufp/__main__.py` | CLI |
| `examples/` | `sensor_board.py` (device), `demo.py` (host) |
| `tests/` | docs.md test vectors + end-to-end tests: `python -m pytest tests` |


### Arduino implementation

| Path | Contents |
|------|----------|
| [`UFP/src`](arduino/UFP/README.md) | Arduino library |
| `UFP/examples` | examples |
