/*
 * uart_commands_user_code.c
 * ARGYNIX Skills (worldskills.blog), lesson "Serial commands: an interrupt-driven UART".
 * Board: NUCLEO-F103RB (STM32F103RB, ST-LINK built in), system clock 72 MHz.
 *
 * 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 uart_commands_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.
 *
 * USART2 (PA2 TX, PA3 RX) reaches the PC through the ST-LINK's USB as a virtual COM
 * port. Open it in a terminal at 115200 baud, 8N1. Commands, one per line, ended by
 * CR, LF or both, in upper or lower case:
 *   LED ON  /  LED OFF    LD2, the green LED on PA5
 *   PWM n                 PA0 (TIM2_CH1, 1 kHz) duty in percent, 0 to 100
 *   ADC?                  the knob on PA1, raw and in millivolts
 *   HELP                  the list
 * Every reply starts with OK or ERR, so a person or a test script can check it.
 */

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

/* USER CODE BEGIN PD */
#define RX_SIZE 64u /* a power of two, so the index wraps with a mask */
#define RX_MASK (RX_SIZE - 1u)
#define LINE_MAX 32u /* 31 characters and the closing '\0' */
/* USER CODE END PD */

/* USER CODE BEGIN PV */
static volatile uint8_t rx_buf[RX_SIZE];
static volatile uint16_t rx_head;      /* written only in the receive callback */
static volatile uint16_t rx_tail;      /* written only by the main loop */
static volatile uint8_t rx_overflow;   /* set when the ring was full */
static volatile uint8_t rx_error;      /* set by the error callback */
static uint8_t rx_byte;                /* the HAL receives into this, one byte at a time */

static char line[LINE_MAX];
static uint8_t line_len;
static uint8_t line_too_long;
/* USER CODE END PV */

/* USER CODE BEGIN 0 */
/* The HAL calls this from the USART2 interrupt when the byte has arrived.
 * Store it and ask for the next one at once: nothing else happens here. */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  if (huart->Instance == USART2)
  {
    uint16_t next = (uint16_t)((rx_head + 1u) & RX_MASK);
    if (next == rx_tail)
    {
      rx_overflow = 1; /* full: this byte is lost, and the main loop will say so */
    }
    else
    {
      rx_buf[rx_head] = rx_byte;
      rx_head = next;
    }
    HAL_UART_Receive_IT(&huart2, &rx_byte, 1);
  }
}

/* A framing, noise or overrun error. After an overrun the HAL may have stopped
 * receiving, so start again here, or the board goes deaf. If reception is still
 * running, HAL_UART_Receive_IT just returns HAL_BUSY and changes nothing. */
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
  if (huart->Instance == USART2)
  {
    rx_error = 1;
    __HAL_UART_CLEAR_OREFLAG(huart); /* reads SR, then DR: clears the error flags */
    HAL_UART_Receive_IT(&huart2, &rx_byte, 1);
  }
}

/* One byte from the ring, or -1 when it is empty. A 16-bit read is one instruction on
 * the Cortex-M3, so the callback cannot change rx_head halfway through it. */
static int rx_get(void)
{
  if (rx_tail == rx_head)
  {
    return -1;
  }
  uint8_t c = rx_buf[rx_tail];
  rx_tail = (uint16_t)((rx_tail + 1u) & RX_MASK);
  return c;
}

/* Blocking send. It returns when the last byte has left: about 87 us a byte at
 * 115200 baud, so 1.7 ms for a 20-character reply. Short replies only. */
static void uart_puts(const char *s)
{
  HAL_UART_Transmit(&huart2, (uint8_t *)s, (uint16_t)strlen(s), 100);
}

/* Builds a line from the bytes. Returns 1 when a whole line is ready in line[]. */
static uint8_t line_feed(char c)
{
  if (c == '\r' || c == '\n')
  {
    if (line_len == 0u && !line_too_long)
    {
      return 0; /* an empty line, or the LF after a CR: not a command */
    }
    line[line_len] = '\0';
    return 1;
  }
  if (line_len < LINE_MAX - 1u)
  {
    line[line_len++] = (char)toupper((unsigned char)c);
  }
  else
  {
    line_too_long = 1; /* refuse the whole line later; never run a cut one */
  }
  return 0;
}

/* duty in percent to CCR1, rounded: duty = CCR1 / (ARR + 1). */
static void pwm_set_percent(uint32_t percent)
{
  uint32_t steps = __HAL_TIM_GET_AUTORELOAD(&htim2) + 1u; /* 1000 at 1 kHz */
  __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, (percent * steps + 50u) / 100u);
}

static uint32_t adc_read(void)
{
  uint32_t raw = 0;
  HAL_ADC_Start(&hadc1);
  if (HAL_ADC_PollForConversion(&hadc1, 2) == HAL_OK)
  {
    raw = HAL_ADC_GetValue(&hadc1);
  }
  HAL_ADC_Stop(&hadc1);
  return raw;
}

static void handle_line(void)
{
  char reply[48];

  if (line_too_long)
  {
    uart_puts("ERR line too long\r\n");
  }
  else if (strcmp(line, "LED ON") == 0)
  {
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
    uart_puts("OK LED ON\r\n");
  }
  else if (strcmp(line, "LED OFF") == 0)
  {
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
    uart_puts("OK LED OFF\r\n");
  }
  else if (strncmp(line, "PWM", 3) == 0 && (line[3] == ' ' || line[3] == '\0'))
  {
    char *end;
    long n = strtol(&line[3], &end, 10);
    /* end == &line[3]: no number at all. *end != '\0': something after it, like "4O". */
    if (end == &line[3] || *end != '\0' || n < 0 || n > 100)
    {
      uart_puts("ERR PWM needs a number from 0 to 100\r\n");
    }
    else
    {
      pwm_set_percent((uint32_t)n);
      snprintf(reply, sizeof reply, "OK PWM %ld\r\n", n);
      uart_puts(reply);
    }
  }
  else if (strcmp(line, "ADC?") == 0)
  {
    uint32_t raw = adc_read();
    uint32_t mv = (raw * 3300u + 2048u) / 4096u; /* 3.3 V reference, rounded */
    snprintf(reply, sizeof reply, "OK ADC %lu %lu mV\r\n", (unsigned long)raw, (unsigned long)mv);
    uart_puts(reply);
  }
  else if (strcmp(line, "HELP") == 0)
  {
    uart_puts("OK LED ON, LED OFF, PWM n, ADC?, HELP\r\n");
  }
  else
  {
    uart_puts("ERR unknown command\r\n");
  }
  line_len = 0;
  line_too_long = 0;
}
/* USER CODE END 0 */

/* USER CODE BEGIN 2 */
  HAL_ADCEx_Calibration_Start(&hadc1);
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
  HAL_UART_Receive_IT(&huart2, &rx_byte, 1); /* the first byte; the callback asks for the rest */
  uart_puts("READY\r\n");
/* USER CODE END 2 */

/* USER CODE BEGIN 3 */
    int c;
    while ((c = rx_get()) >= 0)
    {
      if (line_feed((char)c))
      {
        handle_line();
      }
    }
    if (rx_overflow)
    {
      rx_overflow = 0;
      uart_puts("ERR input lost: buffer full\r\n");
    }
    if (rx_error)
    {
      rx_error = 0;
      uart_puts("ERR framing or overrun: check the baud rate\r\n");
    }
/* USER CODE END 3 */
