// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Dreiym Engineering PLLC
//
// dzhw/1 protocol core for small boards (Arduino Uno/Nano/Mega, UNO R4, ESP32, RP2040 under Arduino).
// Header only, no heap, no JSON library. Replies are streamed byte by byte with a running CRC, so a capture needs
// only its sample buffer in RAM. The board file (dzhw_serial.ino) supplies the hal_* functions below.
#pragma once
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#ifndef DZ_VREF
#define DZ_VREF 5.0f
#endif
#ifndef DZ_ADC_BITS
#define DZ_ADC_BITS 10
#endif
#ifndef DZ_NAIN
#define DZ_NAIN 4
#endif
#ifndef DZ_CAP_RATE
#define DZ_CAP_RATE 8000
#endif
#ifndef DZ_CAP_TOTAL
#define DZ_CAP_TOTAL 400      // samples in RAM for one capture, all inputs together (2 bytes each)
#endif
#ifndef DZ_LINE
#define DZ_LINE 200
#endif
#ifndef DZ_MODEL
#define DZ_MODEL "Arduino bench"
#endif
#define DZ_FW "arduino 1.0.1"
#define DZ_WATCHDOG_MS 3000UL

// ---- supplied by the board file
uint16_t hal_adc(uint8_t ch);              // raw code 0 .. 2^DZ_ADC_BITS - 1
void hal_pwm(float frac);                  // 0..1 duty on the filtered PWM pin
void hal_relay(uint8_t ch, bool on);       // ch 0, 1
uint32_t hal_us();
uint32_t hal_ms();
void hal_write(uint8_t b);
void hal_flush();

namespace dz {
static char line[DZ_LINE + 1];
static uint16_t len = 0;
static bool overflow = false;
static uint16_t crc = 0xffff;
static uint32_t lastHeard = 0;
static bool outsOn = false;
static uint16_t cap[DZ_CAP_TOTAL];

static uint16_t crcByte(uint16_t c, uint8_t x) {
  c ^= (uint16_t)x << 8;
  for (uint8_t i = 0; i < 8; i++) c = (c & 0x8000) ? (uint16_t)((c << 1) ^ 0x1021) : (uint16_t)(c << 1);
  return c;
}
static uint16_t crcStr(const char* s, uint16_t n) { uint16_t c = 0xffff; for (uint16_t i = 0; i < n; i++) c = crcByte(c, (uint8_t)s[i]); return c; }
// ---- streamed reply
static void w(char ch) { crc = crcByte(crc, (uint8_t)ch); hal_write((uint8_t)ch); }
static void ws(const char* s) { while (*s) w(*s++); }
static void wf(float v) {
  char b[44];
  if (v != v || v > 1e30f || v < -1e30f) { ws("null"); return; }
  long ip; float a = v < 0 ? -v : v; if (v < 0) w('-');
  ip = (long)a; float fr = a - (float)ip; long f5 = (long)(fr * 100000.0f + 0.5f); if (f5 >= 100000) { ip++; f5 -= 100000; }
  snprintf(b, sizeof b, "%ld.%05ld", ip, f5); ws(b);
}
static void wl(long v) { char b[14]; snprintf(b, sizeof b, "%ld", v); ws(b); }
static void begin(long id) { crc = 0xffff; ws("{\"id\":"); wl(id); }
static void end() { static const char* H = "0123456789ABCDEF"; w('}'); uint16_t c = crc; hal_write('~'); hal_write(H[(c >> 12) & 15]); hal_write(H[(c >> 8) & 15]); hal_write(H[(c >> 4) & 15]); hal_write(H[c & 15]); hal_write('\n'); hal_flush(); }
static void fail(long id, const char* code, const char* msg) { begin(id); ws(",\"ok\":false,\"err\":\""); ws(code); ws("\",\"msg\":\""); ws(msg); ws("\""); end(); }

// ---- tiny JSON reader: find a key at the top level of an object span [s, e)
static const char* skipWs(const char* p, const char* e) { while (p < e && (*p == ' ' || *p == '\t')) p++; return p; }
static const char* skipVal(const char* p, const char* e) {
  int depth = 0; bool str = false;
  for (; p < e; p++) {
    char c = *p;
    if (str) { if (c == '\\') p++; else if (c == '"') { str = false; if (!depth) return p + 1; } continue; }
    if (c == '"') { str = true; continue; }
    if (c == '{' || c == '[') depth++;
    else if (c == '}' || c == ']') { if (!depth) return p; depth--; if (!depth) return p + 1; }
    else if (!depth && (c == ',')) return p;
  }
  return p;
}
static const char* find(const char* s, const char* e, const char* key, const char** ve) {
  const char* p = skipWs(s, e); size_t kl = strlen(key);
  if (p >= e || *p != '{') return 0;
  p++;
  while (p < e) {
    p = skipWs(p, e);
    if (p >= e || *p == '}') return 0;
    if (*p != '"') return 0;
    const char* k = p + 1; const char* q = k; while (q < e && *q != '"') { if (*q == '\\') q++; q++; }
    bool hit = (size_t)(q - k) == kl && !strncmp(k, key, kl);
    p = skipWs(q + 1, e); if (p >= e || *p != ':') return 0; p = skipWs(p + 1, e);
    const char* v = p; const char* vend = skipVal(p, e);
    if (hit) { if (ve) *ve = vend; return v; }
    p = skipWs(vend, e); if (p < e && *p == ',') p++;
  }
  return 0;
}
static bool getNum(const char* s, const char* e, const char* key, float* out) {
  const char* v = find(s, e, key, 0); if (!v || !((*v >= '0' && *v <= '9') || *v == '-' || *v == '.')) return false;
  *out = (float)strtod(v, 0); return true;
}
static bool isKey(const char* s, const char* e, const char* key, const char* want) {
  const char* v = find(s, e, key, 0); size_t n = strlen(want);
  return v && *v == '"' && !strncmp(v + 1, want, n) && v[n + 1] == '"';
}
static bool isTrue(const char* s, const char* e, const char* key) { const char* v = find(s, e, key, 0); return v && !strncmp(v, "true", 4); }
// "ch":[0,2] -> list of valid input numbers; returns count, 0 on any bad entry
static uint8_t getChs(const char* s, const char* e, uint8_t* out, uint8_t max) {
  const char* ve; const char* v = find(s, e, "ch", &ve); uint8_t n = 0;
  if (!v || *v != '[') return 0;
  v++;
  while (v < ve) {
    v = skipWs(v, ve); if (*v == ']') break;
    if (*v < '0' || *v > '9') return 0;
    long c = strtol(v, (char**)&v, 10); if (c < 0 || c >= DZ_NAIN || n >= max) return 0;
    out[n++] = (uint8_t)c; v = skipWs(v, ve); if (*v == ',') v++;
  }
  return n;
}
static float volts(uint16_t code) { return code * DZ_VREF / (float)((1UL << DZ_ADC_BITS) - 1); }

static void safe() { hal_pwm(0); hal_relay(0, false); hal_relay(1, false); outsOn = false; }

static void opHello(long id) {
  begin(id);
  ws(",\"ok\":true,\"proto\":1,\"dev\":{\"vendor\":\"Arduino\",\"model\":\"" DZ_MODEL "\",\"fw\":\"" DZ_FW "\",\"serial\":\"\",\"bench\":\"\",\"transport\":\"usb-serial\"},\"caps\":{\"ain\":[");
  for (uint8_t i = 0; i < DZ_NAIN; i++) { if (i) w(','); ws("{\"ch\":"); wl(i); ws(",\"name\":\"A"); wl(i); ws("\",\"min\":0,\"max\":"); wf(DZ_VREF); ws(",\"bits\":"); wl(DZ_ADC_BITS); ws(",\"rate\":"); wl(DZ_CAP_RATE); w('}'); }
  ws("],\"aout\":[{\"ch\":0,\"name\":\"PWM\",\"min\":0,\"max\":"); wf(DZ_VREF);
  ws(",\"bits\":8,\"shapes\":[\"dc\"],\"fmax\":0}],\"dout\":[],\"relay\":[{\"ch\":0,\"name\":\"K1\",\"maxV\":12,\"maxA\":1},{\"ch\":1,\"name\":\"K2\",\"maxV\":12,\"maxA\":1}],");
  ws("\"capture\":{\"rate\":"); wl(DZ_CAP_RATE); ws(",\"n\":"); wl(DZ_CAP_TOTAL); ws(",\"trig\":true,\"shared\":true},\"stream\":null,\"calStore\":false,\"selftest\":true},\"safety\":{\"maxIn\":"); wf(DZ_VREF);
  ws(",\"outMax\":"); wf(DZ_VREF); ws(",\"note\":\"board logic level\"}"); end();
}
static void opRead(long id, const char* s, const char* e) {
  uint8_t ch[DZ_NAIN]; uint8_t n = getChs(s, e, ch, DZ_NAIN); float fn = 64, win = 0;
  if (!n) { fail(id, "badarg", "ch"); return; }
  getNum(s, e, "n", &fn); getNum(s, e, "win", &win);
  uint16_t ns = fn < 1 ? 1 : fn > 256 ? 256 : (uint16_t)fn;
  uint32_t dt = (win > 0 && win <= 1) ? (uint32_t)(win * 1e6f / ns) : 0;
  float sum[DZ_NAIN], sq[DZ_NAIN], mn[DZ_NAIN], mx[DZ_NAIN];
  for (uint8_t k = 0; k < n; k++) { sum[k] = sq[k] = 0; mn[k] = 1e9f; mx[k] = -1e9f; }
  uint32_t t = hal_us();
  for (uint16_t i = 0; i < ns; i++) {
    if (dt) { while ((int32_t)(hal_us() - t) < 0) {} t += dt; }
    for (uint8_t k = 0; k < n; k++) { float v = volts(hal_adc(ch[k])); sum[k] += v; sq[k] += v * v; if (v < mn[k]) mn[k] = v; if (v > mx[k]) mx[k] = v; }
  }
  begin(id); ws(",\"ok\":true,\"n\":"); wl(ns); ws(",\"rate\":"); wf(dt ? ns / win : 0);
  const char* K[4] = { ",\"mean\":[", ",\"rms\":[", ",\"min\":[", ",\"max\":[" };
  for (uint8_t q = 0; q < 4; q++) { ws(K[q]); for (uint8_t k = 0; k < n; k++) { if (k) w(','); wf(q == 0 ? sum[k] / ns : q == 1 ? (float)sqrt(sq[k] / ns) : q == 2 ? mn[k] : mx[k]); } w(']'); }
  end();
}
static void opCapture(long id, const char* s, const char* e) {
  uint8_t ch[DZ_NAIN]; uint8_t nc = getChs(s, e, ch, DZ_NAIN); float fn = 200, rate = 1000;
  if (!nc) { fail(id, "badarg", "ch"); return; }
  getNum(s, e, "n", &fn); getNum(s, e, "rate", &rate);
  if (rate <= 0 || rate * nc > DZ_CAP_RATE) { fail(id, "range", "rate"); return; }
  const char* te; const char* tr = find(s, e, "trig", &te); if (tr && *tr != '{') tr = 0;
  uint16_t total = DZ_CAP_TOTAL / nc;               // samples per input that fit
  uint16_t n = (uint16_t)fn; if (tr) { if (n > total / 2) n = total / 2; } else if (n > total) n = total; if (n < 8) n = 8;
  uint16_t take = tr ? 2 * n : n;
  uint32_t dt = (uint32_t)(1e6f / rate), t = hal_us(), t0 = t;
  for (uint16_t i = 0; i < take; i++) { while ((int32_t)(hal_us() - t) < 0) {} t += dt; for (uint8_t k = 0; k < nc; k++) cap[i * nc + k] = hal_adc(ch[k]); }
  float real = take * 1e6f / (float)(hal_us() - t0 ? hal_us() - t0 : 1);
  uint16_t start = 0, pre = 0; const char* trig = "none";
  if (tr) {
    float pf = 0.1f, lv = 0, tch = -1; getNum(tr, te, "pre", &pf); getNum(tr, te, "level", &lv); getNum(tr, te, "ch", &tch);
    if (pf < 0) { pf = 0; }
    if (pf > 0.9f) { pf = 0.9f; }
    pre = (uint16_t)(pf * n); trig = "auto";
    bool rise = !isKey(tr, te, "edge", "fall"); int col = -1;
    for (uint8_t k = 0; k < nc; k++) if (ch[k] == (uint8_t)tch) col = k;
    uint16_t lvl = (uint16_t)(lv < 0 ? 0 : lv / DZ_VREF * ((1UL << DZ_ADC_BITS) - 1));
    if (col >= 0) for (uint16_t i = pre > 0 ? pre : 1; i < 2 * n - (n - pre); i++) {
      uint16_t a = cap[(i - 1) * nc + col], b = cap[i * nc + col];
      if (rise ? (a < lvl && b >= lvl) : (a > lvl && b <= lvl)) { start = i - pre; trig = "ok"; break; }
    }
    if (trig[0] == 'a') pre = 0;
  }
  begin(id); ws(",\"ok\":true,\"rate\":"); wf(real); ws(",\"n\":"); wl(n); ws(",\"pre\":"); wl(pre); ws(",\"trig\":\""); ws(trig); ws("\",\"enc\":\"f\",\"v\":[");
  for (uint8_t k = 0; k < nc; k++) { if (k) w(','); w('['); for (uint16_t i = 0; i < n; i++) { if (i) w(','); wf(volts(cap[(start + i) * nc + k])); } w(']'); }
  ws("]"); end();
}
static void opOut(long id, const char* s, const char* e) {
  float ch = -1, v = 0; getNum(s, e, "ch", &ch);
  if (ch != 0) { fail(id, "badarg", "ch"); return; }
  if (isTrue(s, e, "off")) { hal_pwm(0); begin(id); ws(",\"ok\":true,\"set\":{\"off\":true}"); end(); return; }
  if (find(s, e, "wave", 0)) { fail(id, "nocap", "DC only"); return; }
  if (!getNum(s, e, "dc", &v)) { fail(id, "badarg", "out"); return; }
  if (v < 0 || v > DZ_VREF) { fail(id, "range", "dc"); return; }
  hal_pwm(v / DZ_VREF); if (v > 0) outsOn = true;
  begin(id); ws(",\"ok\":true,\"set\":{\"dc\":"); wf(v); ws("}"); end();
}
static void handle(const char* s, const char* e) {
  float fid = 0; long id;
  if (!getNum(s, e, "id", &fid)) return;   // events or junk: no reply
  id = (long)fid;
  const char* op = find(s, e, "op", 0);
  if (!op || *op != '"') { fail(id, "badarg", "op"); return; }
  if (isKey(s, e, "op", "hello")) opHello(id);
  else if (isKey(s, e, "op", "ping")) { begin(id); ws(",\"ok\":true,\"t\":"); wl((long)hal_ms()); end(); }
  else if (isKey(s, e, "op", "read")) opRead(id, s, e);
  else if (isKey(s, e, "op", "capture")) opCapture(id, s, e);
  else if (isKey(s, e, "op", "out")) opOut(id, s, e);
  else if (isKey(s, e, "op", "dout")) {
    float ch = -1; getNum(s, e, "ch", &ch); bool on = false; float v = 0; if (getNum(s, e, "v", &v)) on = v > 0; else on = isTrue(s, e, "v");
    if (ch != 0 && ch != 1) { fail(id, "badarg", "ch"); return; }
    hal_relay((uint8_t)ch, on); if (on) outsOn = true; begin(id); ws(",\"ok\":true"); end();
  }
  else if (isKey(s, e, "op", "safe") || isKey(s, e, "op", "stop")) { if (isKey(s, e, "op", "safe")) safe(); begin(id); ws(",\"ok\":true"); end(); }
  else if (isKey(s, e, "op", "selftest")) {
    hal_pwm(0.4f); uint32_t t = hal_ms(); while (hal_ms() - t < 800) {}
    float sum = 0; for (uint8_t i = 0; i < 32; i++) sum += volts(hal_adc(0)); sum /= 32; hal_pwm(0);
    float want = 0.4f * DZ_VREF; bool ok = sum > want - 0.2f && sum < want + 0.2f;
    begin(id); ws(",\"ok\":true,\"tests\":[{\"name\":\"PWM to A0 (needs the loop jumper)\",\"ok\":"); ws(ok ? "true" : "false"); ws(",\"v\":"); wf(sum); ws(",\"want\":"); wf(want); ws("}]"); end();
  }
  else fail(id, "badop", "op");
}
// feed one received byte
static void feed(uint8_t b) {
  if (b == '\r') return;
  if (b != '\n') { if (len < DZ_LINE) line[len++] = (char)b; else overflow = true; return; }
  line[len] = 0;
  uint16_t n = len; len = 0;
  if (overflow) { overflow = false; return; }
  if (n < 6) return;
  lastHeard = hal_ms();
  const char* t = line + n - 5;
  if (*t != '~') return;
  uint16_t want = (uint16_t)strtol(t + 1, 0, 16);
  if (crcStr(line, n - 5) != want) return;
  handle(line, line + n - 5);
}
static void tick() { if (outsOn && hal_ms() - lastHeard > DZ_WATCHDOG_MS) safe(); }
}  // namespace dz
