/*
 * Torqheart Lab — board in the loop (hil-balance)
 * https://torqheart.com/workshops/lab/board-in-the-loop
 *
 * Your browser simulates a falling pole on a cart. This board is its
 * controller: every 20 ms the browser sends the pole's state, the board
 * answers with a force. Change the control law below, upload, and watch
 * your own code hold (or drop) the pole.
 *
 * Boards
 *   ESP32 / ESP32-C3 / ESP32-S3   USB cable (Web Serial) or Bluetooth LE (Web Bluetooth)
 *   Arduino Uno / Nano / any      USB cable (Web Serial) only
 * Arduino IDE: pick your board, 115200 baud, upload. Nothing else to install
 * (BLE uses the BLE library that ships with the ESP32 core).
 *
 * Protocol: one ASCII line each way, '\n' terminated.
 *   browser -> board  S,<seq>,<theta mrad>,<omega mrad/s>,<x mm>,<v mm/s>
 *   board -> browser  F,<seq>,<force in deci-newtons>
 *   browser -> board  K,<kp>,<kd>,<ki>,<kx>,<kv>       (new gains)
 *   board -> browser  OK,K
 *   browser -> board  ?                                 board -> HELLO,<name>,<version>
 *
 * The part between "CONTROL LAW" and "END CONTROL LAW" has no Arduino calls,
 * so the site's test suite compiles this same file on a PC (-DHOST_TEST) and
 * checks it answers exactly like the in-page virtual board.
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>

#define HIL_NAME "hil-balance"
#define HIL_VERSION "1"

/* ============================== CONTROL LAW ============================== */

// Gains (SI units). θ in rad, ω in rad/s, x in m, v in m/s, force in N.
// Same signs as the site's balance workshop: push the cart under the falling pole,
// and gently bring the cart back to the middle of the track.
static double kp = 60, kd = 12, ki = 0, kx = 1.5, kv = 3;
static double integral = 0;

static double clampd(double v, double lo, double hi) { return v < lo ? lo : v > hi ? hi : v; }

// TRY THIS: change the law. Ideas: a dead band, a slower loop (answer every
// other line), a filter on omega, or saturate the force to see a weak motor.
static double control_law(double theta, double omega, double x, double v, double dt) {
  integral = clampd(integral + theta * clampd(dt, 0, 0.1), -1, 1);
  return kp * theta + kd * omega + ki * integral + kx * x + kv * v;
}

// Handles one line from the browser. Writes the answer (without '\n') into
// `out` and returns 1, or returns 0 when there is nothing to answer.
// `dt` = seconds since the previous state line (the sketch measures it).
static int handle_line(const char *line, double dt, char *out, size_t outlen) {
  if (line[0] == 'S' && line[1] == ',') {
    long seq, th, w, x, v;
    if (sscanf(line + 2, "%ld,%ld,%ld,%ld,%ld", &seq, &th, &w, &x, &v) != 5) return 0;
    double f = control_law(th / 1000.0, w / 1000.0, x / 1000.0, v / 1000.0, dt);
    // round half up, exactly like JavaScript's Math.round (the in-page virtual board)
    double dn = f * 10.0;
    long r = (long)floor(dn + 0.5);
    snprintf(out, outlen, "F,%ld,%ld", seq, r);
    return 1;
  }
  if (line[0] == 'K' && line[1] == ',') {
    double a, b, c, d, e;
    if (sscanf(line + 2, "%lf,%lf,%lf,%lf,%lf", &a, &b, &c, &d, &e) != 5) return 0;
    kp = a; kd = b; ki = c; kx = d; kv = e;
    integral = 0;
    snprintf(out, outlen, "OK,K");
    return 1;
  }
  if (line[0] == '?') {
    snprintf(out, outlen, "HELLO,%s,%s", HIL_NAME, HIL_VERSION);
    return 1;
  }
  return 0;
}

/* ============================ END CONTROL LAW ============================ */

#ifdef HOST_TEST
// PC build for the site's tests: lines on stdin, answers on stdout, 50 Hz assumed.
int main() {
  char line[160], out[64];
  while (fgets(line, sizeof line, stdin)) {
    line[strcspn(line, "\r\n")] = 0;
    if (handle_line(line, 0.02, out, sizeof out)) printf("%s\n", out);
  }
  return 0;
}
#else

#include <Arduino.h>

#if defined(ESP32)
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLE2902.h>
// Nordic UART Service: the de-facto "serial over BLE"
#define NUS_SERVICE "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
#define NUS_RX      "6e400002-b5a3-f393-e0a9-e50e24dcca9e"  // browser writes here
#define NUS_TX      "6e400003-b5a3-f393-e0a9-e50e24dcca9e"  // board notifies here
static BLECharacteristic *txChar = nullptr;
static volatile bool bleConnected = false;
static char bleBuf[160];
static size_t bleLen = 0;
static char bleLine[160];
static volatile bool bleLineReady = false;

class ServerCb : public BLEServerCallbacks {
  void onConnect(BLEServer *) override { bleConnected = true; }
  void onDisconnect(BLEServer *s) override { bleConnected = false; s->getAdvertising()->start(); }
};
class RxCb : public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *c) override {
    String v = c->getValue();  // ESP32 Arduino core 3.x returns String
    for (size_t i = 0; i < v.length(); i++) {
      char ch = v[i];
      if (ch == '\n') {
        bleBuf[bleLen] = 0;
        if (!bleLineReady) { memcpy(bleLine, bleBuf, bleLen + 1); bleLineReady = true; }
        bleLen = 0;
      } else if (ch != '\r' && bleLen < sizeof bleBuf - 1) {
        bleBuf[bleLen++] = ch;
      }
    }
  }
};
#endif

static char serBuf[160];
static size_t serLen = 0;
static unsigned long lastStateUs = 0;

static void answer(const char *line, bool viaBle) {
  unsigned long now = micros();
  double dt = lastStateUs ? (now - lastStateUs) / 1e6 : 0.02;
  if (line[0] == 'S') lastStateUs = now;
  char out[64];
  if (!handle_line(line, dt, out, sizeof out)) return;
#if defined(ESP32)
  if (viaBle && txChar) {
    strcat(out, "\n");
    txChar->setValue((uint8_t *)out, strlen(out));
    txChar->notify();
    return;
  }
#endif
  (void)viaBle;
  Serial.println(out);
}

void setup() {
  Serial.begin(115200);
#if defined(ESP32)
  BLEDevice::init("Torqheart HIL");
  BLEServer *server = BLEDevice::createServer();
  server->setCallbacks(new ServerCb());
  BLEService *svc = server->createService(NUS_SERVICE);
  txChar = svc->createCharacteristic(NUS_TX, BLECharacteristic::PROPERTY_NOTIFY);
  txChar->addDescriptor(new BLE2902());
  BLECharacteristic *rx = svc->createCharacteristic(NUS_RX, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
  rx->setCallbacks(new RxCb());
  svc->start();
  BLEAdvertising *adv = BLEDevice::getAdvertising();
  adv->addServiceUUID(NUS_SERVICE);
  adv->start();
#endif
  Serial.println("HELLO," HIL_NAME "," HIL_VERSION);
}

void loop() {
  while (Serial.available()) {
    char ch = (char)Serial.read();
    if (ch == '\n') {
      serBuf[serLen] = 0;
      answer(serBuf, false);
      serLen = 0;
    } else if (ch != '\r' && serLen < sizeof serBuf - 1) {
      serBuf[serLen++] = ch;
    }
  }
#if defined(ESP32)
  if (bleLineReady) {
    char line[160];
    memcpy(line, bleLine, sizeof line);
    bleLineReady = false;
    answer(line, true);
  }
#endif
}
#endif
