/*
 * pump_controller_user_code.c
 * ARGYNIX Skills (worldskills.blog), lesson "Firmware that does not hang".
 * Board: NUCLEO-F103RB (STM32F103RB, ST-LINK built in), system clock 72 MHz.
 * A practice brief written by ARGYNIX.
 *
 * This is not a whole program. It is what you type into the main.c that STM32CubeMX
 * generates:
 *   1. Set the project up in STM32CubeMX with pump_controller_cubemx.md and generate the code.
 *   2. Import it into STM32CubeIDE and open Core/Src/main.c.
 *   3. Copy each block below between the two comments of the same name in main.c.
 *      Block 3 goes after "USER CODE BEGIN 3", before the closing brace of while (1).
 * Code outside the USER CODE blocks is deleted when CubeMX generates the code again.
 *
 * Inputs:
 *   PC13  B1, the blue user button (LOW when pressed; the board has the pull-up).
 *         A short press starts or stops the pump. A long press (2 s) clears a fault,
 *         or, when idle, changes the run limit.
 *   PA10  the level switch, to GND, internal pull-up: closed (LOW) when the tank is full.
 * Outputs:
 *   PA8   the pump (an LED with a resistor, or a relay through a transistor).
 *   PA5   LD2, status: off = idle, on = running, 4 Hz blink = fault,
 *         1 to 3 quick flashes = the run limit just chosen.
 *   USART2 (the ST-LINK virtual COM port, 115200 baud): each change of state, with its time.
 *
 * The pump stops by itself when the tank is full, or after the run limit (a dry-run guard:
 * then it is a fault and a person must clear it). The run limit is saved in the last page
 * of flash. The independent watchdog (IWDG) resets the chip if the main loop ever stops,
 * and a watchdog reset starts in FAULT, so the pump never restarts on its own after a crash.
 *
 * TIM3 gives a 1 ms interrupt for the debounce: PSC = 71, ARR = 999 at a 72 MHz timer clock.
 * The IWDG: prescaler 8, reload 1249, so 8 x 1250 / 40 kHz = 250 ms with a typical LSI.
 */

/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.h>
/* USER CODE END Includes */

/* USER CODE BEGIN PTD */
typedef struct
{
  uint8_t count;  /* 0 to DEBOUNCE_MS: how long the input has agreed with "active" */
  uint8_t stable; /* the debounced state: 1 = pressed, or 1 = tank full */
} debounce_t;

typedef enum { EV_NONE, EV_SHORT, EV_LONG } button_event_t;
typedef enum { ST_IDLE, ST_RUNNING, ST_FAULT } state_t;

typedef struct
{
  uint16_t version;     /* SETTINGS_VERSION: a new layout gets a new number */
  uint16_t limit_index; /* 0, 1 or 2 */
  uint16_t check;       /* the two fields above added up, then inverted */
} settings_t;
/* USER CODE END PTD */

/* USER CODE BEGIN PD */
#define QUICK_LIMITS 0     /* 1: limits of 5, 10 and 20 s, to test the table quickly */
#define TEST_WATCHDOG 0    /* 1: a long press while RUNNING hangs the program on purpose */

#define DEBOUNCE_MS 20u
#define LONG_PRESS_MS 2000u

/* The last 1 KB page of the STM32F103RB's 128 KB flash. On a 64 KB STM32F103C8 it is
 * 0x0800FC00. Check in the Build Analyzer that your program ends well below it. */
#define SETTINGS_ADDR 0x0801FC00u
#define SETTINGS_VERSION 1u
/* USER CODE END PD */

/* USER CODE BEGIN PV */
static volatile debounce_t btn, lvl;

#if QUICK_LIMITS
static const uint32_t LIMIT_S[3] = { 5u, 10u, 20u };
#else
static const uint32_t LIMIT_S[3] = { 30u, 60u, 120u };
#endif

static settings_t settings;
static state_t state;
static uint32_t state_since;  /* when the present state began, in ms */
static uint8_t flashes_left;  /* quick flashes still to show the new limit */
static uint32_t flash_since;
static uint8_t started_by_watchdog;
/* USER CODE END PV */

/* USER CODE BEGIN 0 */
/* ------------------------------------------------------------- debounce, in the 1 ms tick */

/* An integrator: each millisecond the count moves one step toward the raw input.
 * The stable state changes only when the count reaches an end, so the input must
 * agree for 20 ms in total before it counts. Contact bounce never gets that far. */
static void debounce_step(volatile debounce_t *d, uint8_t raw_active)
{
  if (raw_active)
  {
    if (d->count < DEBOUNCE_MS) d->count++;
  }
  else
  {
    if (d->count > 0u) d->count--;
  }
  if (d->count == DEBOUNCE_MS)
  {
    d->stable = 1;
  }
  else if (d->count == 0u)
  {
    d->stable = 0;
  }
}

/* TIM3 update interrupt, every 1 ms. Short work only. */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Instance == TIM3)
  {
    debounce_step(&btn, HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13) == GPIO_PIN_RESET);
    debounce_step(&lvl, HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_10) == GPIO_PIN_RESET);
  }
}

/* ------------------------------------------------------------- settings in flash */

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

static void settings_load(void)
{
  const settings_t *stored = (const settings_t *)SETTINGS_ADDR;

  settings = *stored;
  /* Erased flash reads 0xFFFF everywhere: the version and the check catch it. */
  if (settings.version != SETTINGS_VERSION || settings.limit_index > 2u ||
      settings.check != settings_check(&settings))
  {
    settings.version = SETTINGS_VERSION;
    settings.limit_index = 0u; /* the shortest limit is the safe default */
    settings.check = settings_check(&settings);
  }
}

/* Saves only when something changed. Flash is erased a whole page at a time, takes
 * 20 to 40 ms to erase, and is rated for about 10 000 erase cycles: save on a change,
 * never on a timer. While it erases, the CPU waits, so do it when nothing else must run. */
static HAL_StatusTypeDef settings_save(void)
{
  const settings_t *stored = (const settings_t *)SETTINGS_ADDR;
  FLASH_EraseInitTypeDef erase = {0};
  uint32_t page_error = 0;
  HAL_StatusTypeDef status;

  settings.check = settings_check(&settings);
  if (memcmp(stored, &settings, sizeof settings) == 0)
  {
    return HAL_OK; /* the same as what is saved: no erase, no wear */
  }

  const uint16_t words[3] = { settings.version, settings.limit_index, settings.check };

  erase.TypeErase = FLASH_TYPEERASE_PAGES;
  erase.PageAddress = SETTINGS_ADDR;
  erase.NbPages = 1;

  HAL_FLASH_Unlock();
  status = HAL_FLASHEx_Erase(&erase, &page_error);
  for (uint32_t i = 0; status == HAL_OK && i < 3u; i++)
  {
    status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, SETTINGS_ADDR + 2u * i, words[i]);
  }
  HAL_FLASH_Lock();
  return status;
}

/* ------------------------------------------------------------- serial log */

static void log_state(const char *name, uint32_t now)
{
  char msg[40];
  int n = snprintf(msg, sizeof msg, "%lu ms: %s\r\n", (unsigned long)now, name);
  if (n > 0)
  {
    HAL_UART_Transmit(&huart2, (uint8_t *)msg, (uint16_t)strlen(msg), 20);
  }
}

/* ------------------------------------------------------------- button events */

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; /* the press edge */
    long_sent = 0;
  }
  else if (pressed && !long_sent && now - pressed_at >= LONG_PRESS_MS)
  {
    long_sent = 1;    /* fires once, while the button is still held */
    ev = EV_LONG;
  }
  else if (!pressed && was_pressed && !long_sent)
  {
    ev = EV_SHORT;    /* released before it became long */
  }
  was_pressed = pressed;
  return ev;
}

/* ------------------------------------------------------------- the state machine */

static void enter(state_t s, uint32_t now)
{
  static const char *const NAMES[3] = { "IDLE", "RUNNING", "FAULT" };

  state = s;
  state_since = now;
  /* The only place the pump is switched. */
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, (s == ST_RUNNING) ? GPIO_PIN_SET : GPIO_PIN_RESET);
  log_state(NAMES[s], now);
}

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 = (uint16_t)((settings.limit_index + 1u) % 3u);
        settings_save();
        flashes_left = (uint8_t)(settings.limit_index + 1u);
        flash_since = now;
      }
      break;

    case ST_RUNNING:
      if (ev == EV_SHORT || full)
      {
        enter(ST_IDLE, now);
      }
      else if (now - state_since >= LIMIT_S[settings.limit_index] * 1000u)
      {
        enter(ST_FAULT, now); /* ran too long without filling: dry run, or a blocked pipe */
      }
#if TEST_WATCHDOG
      else if (ev == EV_LONG)
      {
        for (;;)
        {
          /* a hang on purpose: the watchdog must rescue us */
        }
      }
#endif
      break;

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

  /* The status LED is worked out from the state on every pass, never toggled blindly. */
  GPIO_PinState led;
  if (flashes_left)
  {
    uint32_t t = now - flash_since; /* 150 ms on, 150 ms off */
    led = (t < 150u) ? GPIO_PIN_SET : GPIO_PIN_RESET;
    if (t >= 300u)
    {
      flashes_left--;
      flash_since = now;
    }
  }
  else if (state == ST_RUNNING)
  {
    led = GPIO_PIN_SET;
  }
  else if (state == ST_FAULT)
  {
    led = (((now - state_since) / 125u) & 1u) ? GPIO_PIN_SET : GPIO_PIN_RESET; /* 4 Hz */
  }
  else
  {
    led = GPIO_PIN_RESET;
  }
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, led);
}
/* USER CODE END 0 */

/* USER CODE BEGIN 1 */
  /* The reset flags in RCC->CSR survive the reset. Read them first, then clear them,
   * or the next reset will look like this one. */
  started_by_watchdog = (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST) != 0u) ? 1u : 0u;
  __HAL_RCC_CLEAR_RESET_FLAGS();
/* USER CODE END 1 */

/* USER CODE BEGIN SysInit */
  /* Stop the watchdog while a breakpoint halts the core, or it resets the chip under
   * the debugger. It changes nothing when no debugger halts the core. */
  __HAL_DBGMCU_FREEZE_IWDG();
/* USER CODE END SysInit */

/* USER CODE BEGIN 2 */
  settings_load();
  HAL_TIM_Base_Start_IT(&htim3); /* the 1 ms debounce tick */

  /* A watchdog reset is a fault, not a normal start. */
  enter(started_by_watchdog ? ST_FAULT : ST_IDLE, HAL_GetTick());

  uint32_t last = HAL_GetTick();
/* USER CODE END 2 */

/* USER CODE BEGIN 3 */
    uint32_t now = HAL_GetTick();
    if (now != last)
    {
      last = now; /* once a millisecond */
      run_state_machine(now, button_event(now));
    }
    /* Fed here only: this line is reached only while the loop really runs.
     * MX_IWDG_Init() started the watchdog before USER CODE 2. */
    HAL_IWDG_Refresh(&hiwdg);
/* USER CODE END 3 */
