// UFP: Universal Function Protocol (v0.4) for Arduino. See ../../docs.md.
//
// Stream mode (COBS + CRC-16 framing) over any Arduino Stream, typically USB
// CDC serial. Functions are registered with their C++ signature; UFP types are
// inferred from the parameter and return types:
//
//   #include <UFP.h>
//   UFPDevice<128> ufp("SensorBoard");             // MAX_PAYLOAD = 128 bytes
//
//   uint16_t read_adc(uint8_t channel, float& voltage) {   // T& = extra return
//     uint16_t raw = analogRead(channel);
//     voltage = raw * 3.3f / 4095;
//     return raw;
//   }
//   UFPEvent<uint8_t, float> threshold;
//
//   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.begin(Serial);
//   }
//   void loop() {
//     ufp.loop();                      // non-blocking: call it often
//     threshold.emit(3, 3.1f);         // sent only if the host subscribed
//   }
//
// Parameters:   by value or const T&  -> argument
//               non-const T&          -> return value (after the C++ return value, if any)
// Types:        bool, u8..u64, i8..i64 (any integer type, mapped by size), float, double,
//               UFPStr (str), UFPBytes (bytes), UFPSpan<T> (T[]), UFPArray<T, N> (T[N]),
//               const char* (str, return only)
// Name lists:   comma-separated, one entry per argument / return / field:
//               "name", "name:unit" or "name:unit:description" (no commas in descriptions)

#ifndef UFP_ARDUINO_H_
#define UFP_ARDUINO_H_

#include <Arduino.h>
#include <stdarg.h>
#include <ctype.h>
#include <stdint.h>
#include <string.h>

#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
#error "UFP for Arduino assumes a little-endian CPU"
#endif

#define UFP_PROTOCOL_VERSION 0x04

// Largest encoded frame for a payload of p bytes: COBS(payload || crc16) + delimiter.
#define UFP_FRAME_MAX(p) ((p) + 2 + ((p) + 2) / 254 + 2)
// Receive buffer: encoded frame without the delimiter.
#define UFP_RX_MAX(p) ((p) + 2 + ((p) + 2) / 254 + 1)

enum UFPErrorCode : uint8_t {
  UFP_OK = 0x00,
  UFP_ERR_UNKNOWN_MSG = 0x01,
  UFP_ERR_UNKNOWN_FUNC = 0x02,
  UFP_ERR_UNKNOWN_EVENT = 0x03,
  UFP_ERR_MALFORMED = 0x04,
  UFP_ERR_TOO_LARGE = 0x05,
  UFP_ERR_BUSY = 0x06,
  UFP_ERR_NO_RESOURCES = 0x07,
  UFP_ERR_EXEC_FAILED = 0x08,
  UFP_ERR_APP = 0x80,           // 0x80-0xFE: application-defined
  UFP_ERR_UNSPECIFIED = 0xFF,
};

enum UFPLogLevel : uint8_t { UFP_LOG_ERROR = 0, UFP_LOG_WARN = 1, UFP_LOG_INFO = 2, UFP_LOG_DEBUG = 3 };

// ---------------------------------------------------------------------------
// Value types
// ---------------------------------------------------------------------------

// UFP `str`: UTF-8 bytes, NOT null-terminated when received as an argument.
struct UFPStr {
  const char* data;
  uint16_t len;
  UFPStr() : data(""), len(0) {}
  UFPStr(const char* s) : data(s ? s : ""), len(0) {
    while (len < 0xFFFF && data[len]) len++;
  }
  UFPStr(const char* s, uint16_t n) : data(s), len(n) {}
  bool equals(const char* s) const { return strlen(s) == len && memcmp(s, data, len) == 0; }
  // copy into buf as a null-terminated string (truncated to size-1); returns the copied length
  size_t copyTo(char* buf, size_t size) const {
    if (!size) return 0;
    size_t n = len < size - 1 ? len : size - 1;
    memcpy(buf, data, n);
    buf[n] = 0;
    return n;
  }
};

// UFP `bytes`
struct UFPBytes {
  const uint8_t* data;
  uint16_t len;
  UFPBytes() : data(0), len(0) {}
  UFPBytes(const void* p, uint16_t n) : data((const uint8_t*)p), len(n) {}
};

// UFP dynamic array `T[]`. As an argument it points into the receive buffer,
// which may be unaligned, so elements are read by value with operator[].
// As a return value, construct it from your own (live) array.
template <class T>
class UFPSpan {
 public:
  UFPSpan() : p_(0), n_(0) {}
  UFPSpan(const T* data, uint16_t count) : p_(data), n_(count) {}
  uint16_t size() const { return n_; }
  T operator[](uint16_t i) const {
    T v;
    memcpy(&v, (const uint8_t*)p_ + (size_t)i * sizeof(T), sizeof(T));
    return v;
  }
  // copy up to max elements into dst; returns the number copied
  uint16_t copyTo(T* dst, uint16_t max) const {
    uint16_t n = n_ < max ? n_ : max;
    memcpy(dst, p_, (size_t)n * sizeof(T));
    return n;
  }
  const void* raw() const { return p_; }

 private:
  const void* p_;
  uint16_t n_;
};

// UFP fixed array `T[N]`
template <class T, uint16_t N>
struct UFPArray {
  static_assert(N > 0, "UFPArray needs at least one element");
  T v[N];
  T& operator[](uint16_t i) { return v[i]; }
  const T& operator[](uint16_t i) const { return v[i]; }
  static uint16_t size() { return N; }
};

template <class... T>
class UFPEvent;
class UFPBase;

// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------

namespace ufp_detail {

enum : uint8_t {
  T_BOOL = 0x01, T_U8, T_I8, T_U16, T_I16, T_U32, T_I32, T_U64, T_I64, T_F32, T_F64, T_STR, T_BYTES,
};
enum : uint8_t { C_FIXED = 0x20, C_DYNAMIC = 0x40, C_MASK = 0x60 };

uint16_t crc16(uint16_t crc, uint8_t b);
uint32_t crc32(uint32_t crc, uint8_t b);

// Cursor over a received payload; every read is bounds-checked.
class Reader {
 public:
  Reader(const uint8_t* p, uint16_t n) : p_(p), n_(n), pos_(0) {}
  const uint8_t* take(uint32_t k) {
    if (k > (uint32_t)(n_ - pos_)) return 0;
    const uint8_t* r = p_ + pos_;
    pos_ += k;
    return r;
  }
  bool get(void* dst, uint16_t k) {
    const uint8_t* s = take(k);
    if (!s) return false;
    memcpy(dst, s, k);
    return true;
  }
  uint16_t remaining() const { return n_ - pos_; }
  bool atEnd() const { return pos_ == n_; }

 private:
  const uint8_t* p_;
  uint16_t n_, pos_;
};

struct Ring {
  uint8_t* buf;
  uint16_t size, head, tail, used;
};

// Byte sink: a linear buffer, a CRC-32 (schema hash) or a COBS frame streamed
// into the transmit ring. Writes past `limit` payload bytes set tooLarge().
class Writer {
 public:
  void toBuffer(uint8_t* buf, uint16_t limit);
  void toCrc32();
  void toFrame(Ring* ring, uint16_t limit, uint16_t reserve);

  void put(uint8_t b);
  void write(const void* p, uint16_t n) {
    const uint8_t* s = (const uint8_t*)p;
    while (n--) put(*s++);
  }
  void u8(uint8_t v) { put(v); }
  void u16(uint16_t v) { write(&v, 2); }
  void u32(uint32_t v) { write(&v, 4); }
  void pstr(const char* s, uint16_t n) {
    if (n > 255) n = 255;
    put((uint8_t)n);
    write(s, n);
  }
  void pstr(const char* s) { pstr(s, s ? strlen(s) : 0); }

  // FRAME mode: append CRC + delimiter; on any overflow, roll the ring back. True if queued.
  bool finish();
  void abort();
  uint16_t count() const { return count_; }
  bool tooLarge() const { return tooLarge_; }
  uint32_t crc32() const { return crc_ ^ 0xFFFFFFFFUL; }

 private:
  enum Mode : uint8_t { BUFFER, CRC32, FRAME };
  void cobs(uint8_t b);
  void push(uint8_t b);
  Mode mode_;
  bool tooLarge_, noRoom_;
  uint16_t count_, limit_;
  uint32_t crc_;
  uint8_t* buf_;
  Ring* ring_;
  uint16_t reserve_, startHead_, startUsed_, codeIdx_;
  uint8_t code_;
};

template <bool B, class T = void> struct EnableIf {};
template <class T> struct EnableIf<true, T> { typedef T type; };
template <class T> struct RemoveCV { typedef T type; };
template <class T> struct RemoveCV<const T> { typedef T type; };
template <class T> struct RemoveCV<volatile T> { typedef T type; };
template <class T> struct RemoveCV<const volatile T> { typedef T type; };
template <class T> struct Decay { typedef typename RemoveCV<T>::type type; };
template <class T> struct Decay<T&> { typedef typename RemoveCV<T>::type type; };
template <class T> struct AlwaysFalse { enum { value = 0 }; };

template <class T> struct IntInfo { enum { is = 0, sign = 0 }; };
#define UFP_INT_(T, S) \
  template <> struct IntInfo<T> { enum { is = 1, sign = S }; };
UFP_INT_(unsigned char, 0)
UFP_INT_(signed char, 1)
UFP_INT_(unsigned short, 0)
UFP_INT_(short, 1)
UFP_INT_(unsigned int, 0)
UFP_INT_(int, 1)
UFP_INT_(unsigned long, 0)
UFP_INT_(long, 1)
UFP_INT_(unsigned long long, 0)
UFP_INT_(long long, 1)
#undef UFP_INT_

template <unsigned Size, bool Signed> struct IntTag;
template <> struct IntTag<1, false> { enum { tag = T_U8 }; };
template <> struct IntTag<1, true> { enum { tag = T_I8 }; };
template <> struct IntTag<2, false> { enum { tag = T_U16 }; };
template <> struct IntTag<2, true> { enum { tag = T_I16 }; };
template <> struct IntTag<4, false> { enum { tag = T_U32 }; };
template <> struct IntTag<4, true> { enum { tag = T_I32 }; };
template <> struct IntTag<8, false> { enum { tag = T_U64 }; };
template <> struct IntTag<8, true> { enum { tag = T_I64 }; };

// Codec<T>: type tag, fixed-array length, wire read and write.
template <class T, class Enable = void>
struct Codec {
  static_assert(AlwaysFalse<T>::value,
                "UFP: unsupported type. Use bool, integers, float, double, UFPStr, UFPBytes, "
                "UFPSpan<T>, UFPArray<T, N> (or const char* as a return value)");
};

// fixed-size scalars, memcpy'd little-endian
template <class T, uint8_t Tag>
struct ScalarCodec {
  enum { tag = Tag, n = 0, scalar = 1 };
  static bool read(Reader& r, T& v) { return r.get(&v, sizeof(T)); }
  static void write(Writer& w, const T& v) { w.write(&v, sizeof(T)); }
};

template <class T>
struct Codec<T, typename EnableIf<IntInfo<T>::is>::type>
    : ScalarCodec<T, IntTag<sizeof(T), IntInfo<T>::sign>::tag> {};

template <> struct Codec<float> : ScalarCodec<float, T_F32> {};
// double is 32-bit on AVR
template <> struct Codec<double> : ScalarCodec<double, sizeof(double) == 8 ? T_F64 : T_F32> {};

template <>
struct Codec<bool> {
  enum { tag = T_BOOL, n = 0, scalar = 1 };
  static bool read(Reader& r, bool& v) {
    const uint8_t* p = r.take(1);
    if (!p || *p > 1) return false;
    v = *p;
    return true;
  }
  static void write(Writer& w, const bool& v) { w.put(v ? 1 : 0); }
};

template <>
struct Codec<UFPStr> {
  enum { tag = T_STR, n = 0, scalar = 0 };
  static bool read(Reader& r, UFPStr& v) {
    uint16_t len;
    if (!r.get(&len, 2)) return false;
    const uint8_t* p = r.take(len);
    if (!p) return false;
    v = UFPStr((const char*)p, len);
    return true;
  }
  static void write(Writer& w, const UFPStr& v) {
    w.u16(v.len);
    w.write(v.data, v.len);
  }
};

template <>
struct Codec<UFPBytes> {
  enum { tag = T_BYTES, n = 0, scalar = 0 };
  static bool read(Reader& r, UFPBytes& v) {
    uint16_t len;
    if (!r.get(&len, 2)) return false;
    const uint8_t* p = r.take(len);
    if (!p) return false;
    v = UFPBytes(p, len);
    return true;
  }
  static void write(Writer& w, const UFPBytes& v) {
    w.u16(v.len);
    w.write(v.data, v.len);
  }
};

template <>
struct Codec<const char*> {
  enum { tag = T_STR, n = 0, scalar = 0 };
  template <class X = void>
  static bool read(Reader&, const char*&) {
    static_assert(AlwaysFalse<X>::value, "UFP: use UFPStr for string arguments");
    return false;
  }
  static void write(Writer& w, const char* const& v) { Codec<UFPStr>::write(w, UFPStr(v)); }
};

template <class T>
struct Codec<UFPSpan<T> > {
  static_assert(Codec<T>::scalar, "UFP: arrays are only allowed for bool, integer and float elements");
  enum { tag = (int)C_DYNAMIC | (int)Codec<T>::tag, n = 0, scalar = 0 };
  static bool read(Reader& r, UFPSpan<T>& v) {
    uint16_t count;
    if (!r.get(&count, 2)) return false;
    const uint8_t* p = r.take((uint32_t)count * sizeof(T));
    if (!p) return false;
    if ((int)Codec<T>::tag == (int)T_BOOL)
      for (uint16_t i = 0; i < count; i++)
        if (p[i] > 1) return false;
    v = UFPSpan<T>((const T*)p, count);
    return true;
  }
  static void write(Writer& w, const UFPSpan<T>& v) {
    w.u16(v.size());
    if ((int)Codec<T>::tag == (int)T_BOOL) {
      for (uint16_t i = 0; i < v.size(); i++) w.put(v[i] ? 1 : 0);
    } else {
      w.write(v.raw(), (uint16_t)(v.size() * sizeof(T)));
    }
  }
};

template <class T, uint16_t N>
struct Codec<UFPArray<T, N> > {
  static_assert(Codec<T>::scalar, "UFP: arrays are only allowed for bool, integer and float elements");
  enum { tag = (int)C_FIXED | (int)Codec<T>::tag, n = N, scalar = 0 };
  static bool read(Reader& r, UFPArray<T, N>& v) {
    for (uint16_t i = 0; i < N; i++)
      if (!Codec<T>::read(r, v.v[i])) return false;
    return true;
  }
  static void write(Writer& w, const UFPArray<T, N>& v) {
    for (uint16_t i = 0; i < N; i++) Codec<T>::write(w, v.v[i]);
  }
};

// One parameter / return / field slot in a descriptor.
struct TypeInfo {
  uint8_t tag;
  uint8_t out;   // 1: non-const reference parameter, i.e. a return value
  uint16_t n;    // fixed-array length
};

// Parameter kinds: by value or const& are arguments, non-const & are outputs.
template <class P> struct Param { typedef typename RemoveCV<P>::type V; enum { out = 0 }; };
template <class T> struct Param<const T&> { typedef typename RemoveCV<T>::type V; enum { out = 0 }; };
template <class T> struct Param<T&> { typedef T V; enum { out = 1 }; };

template <class... P>
struct ParamTable {
  static const TypeInfo list[sizeof...(P) + 1];
};
template <class... P>
const TypeInfo ParamTable<P...>::list[sizeof...(P) + 1] = {
    {(uint8_t)Codec<typename Param<P>::V>::tag, (uint8_t)Param<P>::out,
     (uint16_t)Codec<typename Param<P>::V>::n}...,
    {0, 0, 0}};

template <class R> struct RetInfo {
  static TypeInfo get() {
    typedef typename Decay<R>::type V;
    TypeInfo t = {(uint8_t)Codec<V>::tag, 1, (uint16_t)Codec<V>::n};
    return t;
  }
};
template <> struct RetInfo<void> {
  static TypeInfo get() {
    TypeInfo t = {0, 0, 0};
    return t;
  }
};

// Argument / output storage for one call.
template <class P, bool Out = Param<P>::out>
struct Slot;
template <class P>
struct Slot<P, false> {
  typename Param<P>::V v;
  bool read(Reader& r) { return Codec<typename Param<P>::V>::read(r, v); }
  typename Param<P>::V& pass() { return v; }
  void write(Writer&) {}
};
template <class P>
struct Slot<P, true> {
  typename Param<P>::V v = typename Param<P>::V();
  bool read(Reader&) { return true; }
  typename Param<P>::V& pass() { return v; }
  void write(Writer& w) { Codec<typename Param<P>::V>::write(w, v); }
};

template <unsigned...> struct Seq {};
template <unsigned N, unsigned... I> struct MakeSeq : MakeSeq<N - 1, N - 1, I...> {};
template <unsigned... I> struct MakeSeq<0, I...> { typedef Seq<I...> type; };

template <unsigned I, class P> struct Leaf { Slot<P> s; };
template <class S, class... P> struct Store;
template <unsigned... I, class... P>
struct Store<Seq<I...>, P...> : Leaf<I, P>... {};
template <unsigned I, class P>
Slot<P>& getSlot(Leaf<I, P>& l) { return l.s; }

typedef void (*AnyFn)();
typedef uint8_t (*Invoker)(AnyFn fn, Reader& r, Writer& w);

template <class R>
struct Caller {
  template <class F, class... X>
  static void call(F f, Writer& w, X&... x) {
    typename Decay<R>::type ret = f(x...);
    Codec<typename Decay<R>::type>::write(w, ret);
  }
};
template <>
struct Caller<void> {
  template <class F, class... X>
  static void call(F f, Writer&, X&... x) { f(x...); }
};

template <class R, class... P>
struct Invoke {
  typedef R (*Fn)(P...);
  template <unsigned... I>
  static uint8_t run(Seq<I...>, AnyFn any, Reader& r, Writer& w) {
    Store<Seq<I...>, P...> st;
    (void)st;
    bool ok = true;
    int d1[] = {0, (ok = ok && getSlot<I>(st).read(r), 0)...};
    (void)d1;
    if (!ok || !r.atEnd()) return UFP_ERR_MALFORMED;
    Caller<R>::call(reinterpret_cast<Fn>(any), w, getSlot<I>(st).pass()...);
    int d2[] = {0, (getSlot<I>(st).write(w), 0)...};
    (void)d2;
    return UFP_OK;
  }
  static uint8_t invoke(AnyFn any, Reader& r, Writer& w) {
    return run(typename MakeSeq<sizeof...(P)>::type(), any, r, w);
  }
};

struct FuncEntry {
  const char *name, *desc, *args, *rets;
  const TypeInfo* params;   // all C++ parameters, in order
  TypeInfo ret;             // C++ return value (tag 0 if void)
  uint8_t nparams;
  AnyFn fn;
  Invoker invoke;
};

struct EventEntry {
  const char *name, *desc, *fields;
  const TypeInfo* types;
  uint8_t n;
};

}  // namespace ufp_detail

// ---------------------------------------------------------------------------
// Device
// ---------------------------------------------------------------------------

class UFPBase {
 public:
  // Register a function. args / rets: comma-separated names ("name[:unit[:desc]]").
  // Returns false if the function table is full.
  template <class R, class... P>
  bool add(const char* name, R (*fn)(P...), const char* args = "", const char* rets = "",
           const char* desc = "") {
    if (nfunc_ >= maxFunc_) return false;
    ufp_detail::FuncEntry& f = funcs_[nfunc_++];
    f.name = name;
    f.desc = desc ? desc : "";
    f.args = args ? args : "";
    f.rets = rets ? rets : "";
    f.params = ufp_detail::ParamTable<P...>::list;
    f.nparams = sizeof...(P);
    f.ret = ufp_detail::RetInfo<R>::get();
    f.fn = reinterpret_cast<ufp_detail::AnyFn>(fn);
    f.invoke = &ufp_detail::Invoke<R, P...>::invoke;
    hashValid_ = false;
    return true;
  }
  // captureless lambdas
  template <class F>
  bool add(const char* name, F f, const char* args = "", const char* rets = "", const char* desc = "") {
    return add(name, +f, args, rets, desc);
  }

  // Register an event with field types T...; keep the handle and call emit() on it.
  template <class... T>
  UFPEvent<T...> event(const char* name, const char* fields = "", const char* desc = "");

  // Register the standard `log` event (u8 level, str msg); then use log() / logPrintf().
  bool enableLog();
  bool log(uint8_t level, const char* msg);
  bool logPrintf(uint8_t level, const char* fmt, ...)
#if defined(__GNUC__)
      __attribute__((format(printf, 3, 4)))
#endif
      ;

  // Start serving on a stream (e.g. Serial, already begun). If the stream type
  // has operator bool (USB CDC: host has the port open), the session ends when
  // it goes false.
  template <class S>
  void begin(S& port) {
    beginStream(&port, connCheck<S>(0));
  }
  // Process received requests and transmit pending bytes. Non-blocking.
  void loop();

  // From inside a registered function: make the call return ERROR_RSP
  // (UFP_ERR_EXEC_FAILED or an application code 0x80-0xFE) instead of its values.
  void fail(uint8_t code, const char* msg = "");

  void setBootId(uint32_t id) { bootId_ = id; bootIdSet_ = true; }
  void setMaxInflight(uint8_t n) { maxInflight_ = n ? n : 1; }
  bool inSession() const { return session_; }
  bool subscribed(uint8_t eventId) const;
  uint32_t schemaHash();
  uint32_t droppedEvents() const { return dropped_; }
  uint32_t frameErrors() const { return frameErrors_; }
  uint8_t functionCount() const { return nfunc_; }
  uint8_t eventCount() const { return nevt_; }

  // used by UFPEvent
  bool notifyBegin(uint8_t id, ufp_detail::Writer& w);
  bool notifyEnd(ufp_detail::Writer& w);

 protected:
  UFPBase(const char* name, uint16_t maxPayload, uint8_t* rx, uint16_t rxCap, uint8_t* tx,
          uint16_t txCap, uint8_t* scratch, ufp_detail::FuncEntry* funcs, uint8_t maxFunc,
          ufp_detail::EventEntry* events, uint8_t maxEvt);

 private:
  typedef bool (*ConnFn)(Stream*);
  template <class S>
  struct Conn {
    static bool check(Stream* s) { return static_cast<bool>(*static_cast<S*>(s)); }
  };
  template <class S>
  static auto connCheck(int) -> decltype(static_cast<bool>(*(S*)0), ConnFn()) {
    return &Conn<S>::check;
  }
  template <class S>
  static ConnFn connCheck(...) { return 0; }

  void beginStream(Stream* s, ConnFn conn);
  void endSession();
  void flush();
  void readInput();
  bool tryHandle();
  void handle(const uint8_t* p, uint16_t n);
  bool describeFunction(ufp_detail::Writer& w, uint8_t id);
  bool describeEvent(ufp_detail::Writer& w, uint8_t id);
  void entry(ufp_detail::Writer& w, const ufp_detail::TypeInfo& t, const char* spec, uint8_t index,
             const char* fallback);
  uint8_t addEvent(const char* name, const char* fields, const char* desc,
                   const ufp_detail::TypeInfo* types, uint8_t n);
  uint16_t frameMax() const { return UFP_FRAME_MAX(maxPayload_); }

  const char* name_;
  Stream* port_;
  ConnFn conn_;
  bool connected_;
  uint32_t lastConnCheck_;
  uint16_t maxPayload_;
  uint8_t maxInflight_;
  uint8_t *rx_, *scratch_;
  uint16_t rxCap_, rxLen_;
  bool rxReady_, rxSkip_;
  ufp_detail::Ring ring_;
  ufp_detail::FuncEntry* funcs_;
  ufp_detail::EventEntry* events_;
  uint8_t maxFunc_, maxEvt_, nfunc_, nevt_;
  bool session_, handling_;
  uint32_t subs_;
  uint8_t nseq_;
  uint32_t bootId_;
  bool bootIdSet_;
  uint32_t hash_;
  bool hashValid_;
  uint8_t failCode_;
  char failMsg_[48];
  uint8_t logEvent_;
  uint32_t dropped_, frameErrors_;
};

// MaxPayload: largest message in either direction (>= 64). MaxFunctions,
// MaxEvents (<= 32): table sizes. TxBuffer: transmit ring, at least one frame.
// RAM use is roughly 3 * MaxPayload + TxBuffer extra + 24 bytes per function.
template <uint16_t MaxPayload = 128, uint8_t MaxFunctions = 16, uint8_t MaxEvents = 4,
          uint16_t TxBuffer = 2 * UFP_FRAME_MAX(MaxPayload)>
class UFPDevice : public UFPBase {
  static_assert(MaxPayload >= 64, "UFP: MaxPayload must be at least 64");
  static_assert(MaxEvents <= 32, "UFP: at most 32 events");
  static_assert(TxBuffer > UFP_FRAME_MAX(MaxPayload), "UFP: TxBuffer must hold one full frame");

 public:
  explicit UFPDevice(const char* name)
      : UFPBase(name, MaxPayload, rxBuf_, sizeof(rxBuf_), txBuf_, TxBuffer, scratch_, funcs_,
                MaxFunctions, events_, MaxEvents) {}

 private:
  uint8_t rxBuf_[UFP_RX_MAX(MaxPayload)];
  uint8_t txBuf_[TxBuffer];
  uint8_t scratch_[MaxPayload];
  ufp_detail::FuncEntry funcs_[MaxFunctions];
  ufp_detail::EventEntry events_[MaxEvents ? MaxEvents : 1];
};

// Handle to a registered event. Default-constructed handles do nothing.
template <class... T>
class UFPEvent {
 public:
  UFPEvent() : dev_(0), id_(0xFF) {}
  UFPEvent(UFPBase* dev, uint8_t id) : dev_(dev), id_(id) {}
  // Send the event if the host is subscribed. Returns true if it was queued;
  // false if not subscribed or the transmit buffer is full (counted as dropped).
  bool emit(const T&... values) const {
    ufp_detail::Writer w;
    if (!dev_ || !dev_->notifyBegin(id_, w)) return false;
    int d[] = {0, (ufp_detail::Codec<T>::write(w, values), 0)...};
    (void)d;
    return dev_->notifyEnd(w);
  }
  bool subscribed() const { return dev_ && dev_->subscribed(id_); }
  bool valid() const { return dev_ != 0; }
  uint8_t id() const { return id_; }

 private:
  UFPBase* dev_;
  uint8_t id_;
};

template <class... T>
UFPEvent<T...> UFPBase::event(const char* name, const char* fields, const char* desc) {
  uint8_t id = addEvent(name, fields, desc, ufp_detail::ParamTable<T...>::list, sizeof...(T));
  return id == 0xFF ? UFPEvent<T...>() : UFPEvent<T...>(this, id);
}

#endif
