/*
 * pump_controller_lab.ino
 * ARGYNIX Skills (worldskills.blog), lesson "Firmware that does not hang".
 * The pump controller from pump_controller_avr.c as an Arduino sketch, for ARGYNIX Lab and
 * the Arduino IDE. Save it in a folder named pump_controller_lab.
 *
 * LAB_SIM is 1 for ARGYNIX Lab: the Lab's Uno does not model the watchdog or the EEPROM,
 * so those parts are left out, and the run limits are 5, 10 and 20 s so a fault shows in
 * a short run. Set LAB_SIM to 0 on a real Uno: watchdog, EEPROM and 30, 60, 120 s.
 *
 *   D2  button to GND: short press starts or stops; long press (2 s) clears a fault,
 *       or, when idle, changes the run limit (1 to 3 quick flashes show which).
 *   D3  level switch to GND: closed = tank full.
 *   D7  pump (LED).   D13 status: off idle, on running, 4 Hz blink fault.
 *   Serial at 115200: each change of state.
 */
#define LAB_SIM 1

#include <util/atomic.h>
#if !LAB_SIM
#include <avr/eeprom.h>
#include <avr/wdt.h>

uint8_t mcusr_copy __attribute__((section(".noinit")));
void save_reset_cause(void) __attribute__((naked, used, section(".init3")));
void save_reset_cause(void)
{
  mcusr_copy = MCUSR;  /* the reset cause, kept before anything clears it */
  MCUSR = 0;
  wdt_disable();       /* after a watchdog reset the watchdog is still running */
}
#endif

#define DEBOUNCE_MS 20u
#define LONG_PRESS_MS 2000u

typedef struct {
  uint8_t count;   /* 0 to DEBOUNCE_MS */
  uint8_t stable;  /* 1 = pressed (pin LOW) */
} debounce_t;

static volatile uint32_t ms_ticks;
static volatile debounce_t btn, lvl;

static void debounce_step(volatile debounce_t *d, uint8_t raw_pressed)
{
  if (raw_pressed) {
    if (d->count < DEBOUNCE_MS) d->count++;
  } else {
    if (d->count > 0) d->count--;
  }
  if (d->count == DEBOUNCE_MS) d->stable = 1;
  else if (d->count == 0) d->stable = 0;
}

ISR(TIMER2_COMPA_vect)
{
  ms_ticks++;
  debounce_step(&btn, !(PIND & (1 << PIND2)));
  debounce_step(&lvl, !(PIND & (1 << PIND3)));
}

static void tick_init(void)
{
  TCCR2A = (1 << WGM21);
  TCCR2B = (1 << CS22);
  OCR2A = 249;
  TIMSK2 = (1 << OCIE2A);
}

static uint32_t ticks_now(void)
{
  uint32_t t;
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
  {
    t = ms_ticks;
  }
  return t;
}

#define SETTINGS_VERSION 1u

typedef struct {
  uint8_t version;
  uint8_t limit_index;
  uint8_t check;
} settings_t;

#if LAB_SIM
static const uint16_t LIMIT_S[3] = { 5u, 10u, 20u };
#else
static const uint16_t LIMIT_S[3] = { 30u, 60u, 120u };
static settings_t EEMEM ee_settings;
#endif
static settings_t settings;

static uint8_t settings_check(const settings_t *s)
{
  return (uint8_t)~(uint8_t)(s->version + s->limit_index);
}

static void settings_load(void)
{
#if !LAB_SIM
  eeprom_read_block(&settings, &ee_settings, sizeof settings);
#endif
  if (settings.version != SETTINGS_VERSION || settings.limit_index > 2u ||
      settings.check != settings_check(&settings)) {
    settings.version = SETTINGS_VERSION;
    settings.limit_index = 0u;
  }
}

static void settings_save(void)
{
  settings.check = settings_check(&settings);
#if !LAB_SIM
  eeprom_update_block(&settings, &ee_settings, sizeof settings);
#endif
}

typedef enum { EV_NONE, EV_SHORT, EV_LONG } button_event_t;

static button_event_t button_event(uint32_t now)
{
  static uint8_t was_pressed;
  static uint32_t pressed_at;
  static uint8_t long_sent;
  uint8_t pressed = btn.stable;
  button_event_t ev = EV_NONE;

  if (pressed && !was_pressed) {
    pressed_at = now;
    long_sent = 0;
  } else if (pressed && !long_sent && now - pressed_at >= LONG_PRESS_MS) {
    long_sent = 1;
    ev = EV_LONG;
  } else if (!pressed && was_pressed && !long_sent) {
    ev = EV_SHORT;
  }
  was_pressed = pressed;
  return ev;
}

typedef enum { ST_IDLE, ST_RUNNING, ST_FAULT } state_t;

static const char *const STATE_NAME[] = { "IDLE", "RUNNING", "FAULT" };

static state_t state;
static uint32_t state_since;
static uint8_t flashes_left;
static uint32_t flash_since;

static void pump(uint8_t on)
{
  if (on) PORTD |= (1 << PORTD7);
  else PORTD &= ~(1 << PORTD7);
}

static void status_led(uint8_t on)
{
  if (on) PORTB |= (1 << PORTB5);
  else PORTB &= ~(1 << PORTB5);
}

static void enter(state_t s, uint32_t now)
{
  state = s;
  state_since = now;
  pump(s == ST_RUNNING);
  Serial.print(now);
  Serial.print(F(" ms: "));
  Serial.println(STATE_NAME[s]);
}

static void run_state_machine(uint32_t now, button_event_t ev)
{
  uint8_t full = lvl.stable;

  switch (state) {
    case ST_IDLE:
      if (ev == EV_SHORT && !full) {
        enter(ST_RUNNING, now);
      } else if (ev == EV_LONG) {
        settings.limit_index = (uint8_t)((settings.limit_index + 1u) % 3u);
        settings_save();
        flashes_left = (uint8_t)(settings.limit_index + 1u);
        flash_since = now;
        Serial.print(F("run limit "));
        Serial.print(LIMIT_S[settings.limit_index]);
        Serial.println(F(" s"));
      }
      break;

    case ST_RUNNING:
      if (ev == EV_SHORT || full) {
        enter(ST_IDLE, now);
      } else if (now - state_since >= (uint32_t)LIMIT_S[settings.limit_index] * 1000u) {
        enter(ST_FAULT, now);
      }
      break;

    case ST_FAULT:
      if (ev == EV_LONG) enter(ST_IDLE, now);
      break;
  }

  if (flashes_left) {
    uint32_t t = now - flash_since;
    status_led(t < 150u);
    if (t >= 300u) {
      flashes_left--;
      flash_since = now;
    }
  } else if (state == ST_RUNNING) {
    status_led(1);
  } else if (state == ST_FAULT) {
    status_led(((now - state_since) / 125u) & 1u);
  } else {
    status_led(0);
  }
}

void setup()
{
  Serial.begin(115200);
  DDRD &= ~((1 << DDD2) | (1 << DDD3));
  PORTD |= (1 << PORTD2) | (1 << PORTD3);
  DDRD |= (1 << DDD7);
  DDRB |= (1 << DDB5);

  settings_load();
  tick_init();
#if LAB_SIM
  enter(ST_IDLE, ticks_now());
#else
  enter((mcusr_copy & (1 << WDRF)) ? ST_FAULT : ST_IDLE, ticks_now());
  wdt_enable(WDTO_250MS);
#endif
}

void loop()
{
  static uint32_t last;
  uint32_t now = ticks_now();
  if (now != last) {
    last = now;
    run_state_machine(now, button_event(now));
  }
#if !LAB_SIM
  wdt_reset();
#endif
}
