/*
 * souffle-starter-hal.c
 *
 * Same starting point as souffle-starter.c but with the HAL, so you can
 * generate a project in CubeMX and drop this straight in as your main.c. It
 * reads the nine buttons, lights the matching LEDs, and beeps if you hold
 * ENTER. Thats it, the rest is yours.
 *
 * WHAT TO DO IN CUBEMX
 *
 *   Board: STM32F103C8Tx, LQFP48.
 *
 *   Pinout:
 *     PA15                 GPIO_Output   LED1
 *     PB4 PB5 PB6 PB7      GPIO_Output   LED2..LED5
 *     PB8 PB9 PB10 PB11    GPIO_Output   LED6, LED7, LED8, status
 *     PA1..PA7             GPIO_Input    BTN1..BTN7   (pull-up)
 *     PB0 PB1              GPIO_Input    BTN8, ENTER  (pull-up)
 *     PA0                  TIM2_CH1      buzzer
 *     PA9 PA10             USART1        serial pads
 *     PA11 PA12            USB           the USB-C socket
 *     PA13 PA14 PB3        SYS           SWDIO, SWCLK, SWO
 *     PD0 PD1              RCC           the 8 MHz crystal
 *
 *   System Core > SYS > Debug: "Trace Asynchronous SW".
 *     This defaults to Disable, which leaves JTAG switched on, which means
 *     PA15 and PB4 arent GPIOs and LED1 and LED2 just dont work. Setting it
 *     to Trace Asynchronous SW frees both and gives you SWO on PB3 so you can
 *     printf into the debugger. Plain "Serial Wire" works for the LEDs too,
 *     you just dont get the trace pin.
 *
 *   Clock Configuration tab: HSE 8 MHz, PLLMul x9, SYSCLK 72 MHz,
 *     APB1 /2 (36 MHz, its maximum), APB2 /1 (72 MHz), USB prescaler /1.5
 *     (48 MHz). Thats the only combination that lands on exactly 48 MHz for
 *     USB, which is the whole reason the crystal is 8 MHz. CubeMX opens on
 *     the internal oscillator so you have to go and set this yourself.
 *
 * If you cant be bothered with CubeMX at all, souffle-starter.c does the same
 * thing in about a hundred lines of plain register writes.
 */

#include "main.h"

/* ------------------------------------------------------------- the board */
/* left to right, as they sit on the front of the card */
static GPIO_TypeDef *const led_port[9] = {
  GPIOA, GPIOB, GPIOB, GPIOB, GPIOB, GPIOB, GPIOB, GPIOB, GPIOB
};
static const uint16_t led_pin[9] = {
  GPIO_PIN_15, GPIO_PIN_4, GPIO_PIN_5, GPIO_PIN_6, GPIO_PIN_7,
  GPIO_PIN_8,  GPIO_PIN_9, GPIO_PIN_10, GPIO_PIN_11
};

static GPIO_TypeDef *const btn_port[9] = {
  GPIOA, GPIOA, GPIOA, GPIOA, GPIOA, GPIOA, GPIOA, GPIOB, GPIOB
};
static const uint16_t btn_pin[9] = {
  GPIO_PIN_1, GPIO_PIN_2, GPIO_PIN_3, GPIO_PIN_4, GPIO_PIN_5,
  GPIO_PIN_6, GPIO_PIN_7, GPIO_PIN_0, GPIO_PIN_1
};
/* index 8 is the offset button, the one labelled ENTER */

static TIM_HandleTypeDef htim2;

/* The LEDs sink to light. Anode on 3V3, cathode through 120R to the pin, so
   pin LOW is on. Thats why this looks backwards. */
static void led(uint32_t i, int on)
{
  HAL_GPIO_WritePin(led_port[i], led_pin[i], on ? GPIO_PIN_RESET : GPIO_PIN_SET);
}

/* Active low against the internal pull-up. */
static int button(uint32_t i)
{
  return HAL_GPIO_ReadPin(btn_port[i], btn_pin[i]) == GPIO_PIN_RESET;
}

/* PA0 is TIM2_CH1, so the buzzer is one of the only things on here that gets
   real hardware PWM. Prescale to 1 MHz and the reload is just 1e6/Hz - 1.

   Its a piezo, so its sharply resonant. Loudest around 2.7 kHz and basically
   silent below 1 kHz, so transpose whatever you write up into 1 to 3 kHz or
   you wont hear it. Keep the duty well under half, 25 to 35 percent is
   already loud in a quiet room. Also give notes at least 140 ms below
   resonance, coz the element needs time to ring up and anything shorter just
   comes out as a click. */
static void buzzer(uint32_t hz, uint32_t duty_pct)
{
  if (hz < 50u || hz > 20000u) {
    HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1);
    return;
  }
  uint32_t arr = (1000000u / hz) - 1u;
  __HAL_TIM_SET_AUTORELOAD(&htim2, arr);
  __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, ((arr + 1u) * duty_pct) / 100u);
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
}

/* ------------------------------------------------------------------ init */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef osc = {0};
  RCC_ClkInitTypeDef clk = {0};
  RCC_PeriphCLKInitTypeDef pclk = {0};

  osc.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  osc.HSEState       = RCC_HSE_ON;
  osc.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  osc.PLL.PLLState   = RCC_PLL_ON;
  osc.PLL.PLLSource  = RCC_PLLSOURCE_HSE;
  osc.PLL.PLLMUL     = RCC_PLL_MUL9;        /* 8 MHz x 9 = 72 MHz */

  /* Actually check this return value. If the crystal doesnt start, HAL gives
     up and leaves you on the internal oscillator, and everything still looks
     fine. LEDs work, timers work, and then USB silently wont enumerate and
     you lose an afternoon. The code CubeMX generates ignores it. */
  if (HAL_RCC_OscConfig(&osc) != HAL_OK) {
    Error_Handler();
  }

  clk.ClockType      = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK |
                       RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  clk.SYSCLKSource   = RCC_SYSCLKSOURCE_PLLCLK;
  clk.AHBCLKDivider  = RCC_SYSCLK_DIV1;     /* HCLK  72 MHz */
  clk.APB1CLKDivider = RCC_HCLK_DIV2;       /* PCLK1 36 MHz, its maximum */
  clk.APB2CLKDivider = RCC_HCLK_DIV1;       /* PCLK2 72 MHz */

  /* FLASH_LATENCY_2 is two wait states, which is what 72 MHz needs. Dont
     grab FLASH_ACR_LATENCY_2 from the CMSIS header instead, thats bit 2 of
     the field (so, 0x4) and a completely different number. Ask me how i
     know. */
  if (HAL_RCC_ClockConfig(&clk, FLASH_LATENCY_2) != HAL_OK) {
    Error_Handler();
  }

  pclk.PeriphClockSelection = RCC_PERIPHCLK_USB;
  pclk.UsbClockSelection    = RCC_USBCLKSOURCE_PLL_DIV1_5;   /* 72/1.5 = 48 */
  if (HAL_RCCEx_PeriphCLKConfig(&pclk) != HAL_OK) {
    Error_Handler();
  }
}

static void gpio_init(void)
{
  GPIO_InitTypeDef g = {0};

  __HAL_RCC_AFIO_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();

  /* This has to happen first, before you configure any pins. PA15 comes out
     of reset as JTDI and isnt a GPIO at all until JTAG is released. This
     frees PA15, PB3 and PB4 and leaves SWD alone so you keep the debugger. */
  __HAL_AFIO_REMAP_SWJ_NOJTAG();

  /* Write them off before making them outputs so nothing flashes on boot.
     HIGH is off, remember. */
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_SET);
  HAL_GPIO_WritePin(GPIOB, 0x0FF0, GPIO_PIN_SET);      /* PB4..PB11 */

  g.Mode  = GPIO_MODE_OUTPUT_PP;
  g.Pull  = GPIO_NOPULL;
  g.Speed = GPIO_SPEED_FREQ_LOW;
  g.Pin   = GPIO_PIN_15;
  HAL_GPIO_Init(GPIOA, &g);
  g.Pin   = 0x0FF0;                                    /* PB4..PB11 */
  HAL_GPIO_Init(GPIOB, &g);

  g.Mode = GPIO_MODE_INPUT;
  g.Pull = GPIO_PULLUP;
  g.Pin  = 0x00FE;                                     /* PA1..PA7 */
  HAL_GPIO_Init(GPIOA, &g);
  g.Pin  = 0x0003;                                     /* PB0, PB1 */
  HAL_GPIO_Init(GPIOB, &g);

  /* PB2 is BOOT1. Leave it alone. */
}

static void buzzer_init(void)
{
  GPIO_InitTypeDef g = {0};
  TIM_OC_InitTypeDef oc = {0};

  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_TIM2_CLK_ENABLE();

  g.Pin   = GPIO_PIN_0;
  g.Mode  = GPIO_MODE_AF_PP;
  g.Pull  = GPIO_NOPULL;
  g.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &g);

  /* APB1 is 36 MHz, but if the APB prescaler isnt 1 the timer clock gets
     doubled, so TIM2 actually counts at 72 MHz. Thats why its 72 - 1 for a
     1 MHz tick and not 36 - 1. Catches everyone once. */
  htim2.Instance               = TIM2;
  htim2.Init.Prescaler         = 72u - 1u;
  htim2.Init.CounterMode       = TIM_COUNTERMODE_UP;
  htim2.Init.Period            = 1000u - 1u;
  htim2.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
  HAL_TIM_PWM_Init(&htim2);

  oc.OCMode     = TIM_OCMODE_PWM1;
  oc.Pulse      = 0;
  oc.OCPolarity = TIM_OCPOLARITY_HIGH;
  oc.OCFastMode = TIM_OCFAST_DISABLE;
  HAL_TIM_PWM_ConfigChannel(&htim2, &oc, TIM_CHANNEL_1);
}

/* ------------------------------------------------------------------ main */
int main(void)
{
  HAL_Init();
  SystemClock_Config();
  gpio_init();
  buzzer_init();

  for (;;) {
    for (uint32_t i = 0; i < 9u; i++) {
      led(i, button(i));
    }

    /* hold ENTER for a tone, at the frequency this buzzer likes best */
    if (button(8)) {
      buzzer(2700u, 30u);
    } else {
      buzzer(0u, 0u);
    }

    HAL_Delay(1);
  }
}

void Error_Handler(void)
{
  /* All nine on and stop. Makes a failure obvious from across the room
     instead of looking like the board is just idle. */
  __disable_irq();
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIOB, 0x0FF0, GPIO_PIN_RESET);
  for (;;) { }
}

/*
 * WHERE TO GO NEXT
 *
 * Brightness. None of the LED pins are on timer channels so hardware PWM
 * cant reach them, you have to run a timer interrupt and flip the pins
 * yourself. The naive way is to count 0..255 every frame, which is 256
 * interrupts per frame and eats the CPU. What this firmware does instead is
 * binary code modulation: eight slots with lengths weighted 1,2,4..128, and
 * you light the pin during the slots whose bit is set. Same 8-bit
 * brightness, 8 interrupts a frame instead of 256. Write the whole port in
 * one BSRR store and the ISR stays short enough to live under USB.
 *
 * Gamma. Your eyes arent linear, so a straight 0..255 ramp looks like it
 * does nothing for ages and then jumps at the top. Run the value through a
 * gamma 2.2 table first and it actually looks like a fade.
 *
 * USB. Turn on USB_DEVICE in CubeMX as a CDC class and you get a serial port
 * for free. One catch, the D+ pull-up is on PA8 instead of being hardwired,
 * so the computer sees nothing until you raise it. Drop PA8, wait 20 ms,
 * bring the USB stack up, then raise it. Thats annoying once and then quite
 * nice, coz it means you can detach and reattach in software without
 * touching the cable.
 *
 * Anyway, go break it.
 *   - Josh
 */
