/*
 * uart_commands_lab.ino
 * ARGYNIX Skills (worldskills.blog), lesson "Serial commands: an interrupt-driven UART".
 * The same program as uart_commands_avr.c, as an Arduino sketch for ARGYNIX Lab and the
 * Arduino IDE on a real Uno. Save it in a folder named uart_commands_lab.
 *
 * It drives USART0 itself, so it must not use Serial: the core's own receive interrupt
 * would clash with ours. Open the serial monitor at 115200 baud, line ending "Newline".
 *
 *   LED ON  /  LED OFF    the LED on D13
 *   PWM n                 D6 duty in percent, 0 to 100
 *   ADC?                  the reading on A0, raw and in millivolts
 *   HELP                  the list
 */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define RX_SIZE 64u
#define RX_MASK (RX_SIZE - 1u)

static volatile uint8_t rx_buf[RX_SIZE];
static volatile uint8_t rx_head;     /* written only by the ISR */
static volatile uint8_t rx_tail;     /* written only by loop() */
static volatile uint8_t rx_overflow;
static volatile uint8_t rx_errors;

ISR(USART_RX_vect)
{
  uint8_t status = UCSR0A;           /* error flags first */
  uint8_t c = UDR0;
  if (status & ((1 << FE0) | (1 << DOR0))) rx_errors = 1;
  uint8_t next = (uint8_t)((rx_head + 1u) & RX_MASK);
  if (next == rx_tail) {
    rx_overflow = 1;
  } else {
    rx_buf[rx_head] = c;
    rx_head = next;
  }
}

static int rx_get(void)
{
  if (rx_tail == rx_head) return -1;
  uint8_t c = rx_buf[rx_tail];
  rx_tail = (uint8_t)((rx_tail + 1u) & RX_MASK);
  return c;
}

static void uart_init(void)
{
  UCSR0A = (1 << U2X0);
  UBRR0 = 16;                        /* 117 647 baud with U2X0: +2.1 % */
  UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
  UCSR0B = (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);
}

static void uart_putc(char c)
{
  while (!(UCSR0A & (1 << UDRE0))) {
  }
  UDR0 = (uint8_t)c;
}

static void uart_puts(const char *s)
{
  while (*s) uart_putc(*s++);
}

static void pwm_init(void)
{
  DDRD |= (1 << DDD6);
  TCCR0A = (1 << WGM01) | (1 << WGM00); /* what the core set already: millis() keeps working */
  TCCR0B = (1 << CS01) | (1 << CS00);
}

static void pwm_set_percent(uint8_t pct)
{
  if (pct == 0) {
    TCCR0A &= ~(1 << COM0A1);
    PORTD &= ~(1 << PORTD6);
    return;
  }
  OCR0A = (uint8_t)(((uint16_t)pct * 256u) / 100u - 1u);
  TCCR0A |= (1 << COM0A1);
}

static void adc_init(void)
{
  ADMUX = (1 << REFS0);
  ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
}

static uint16_t adc_read(void)
{
  ADCSRA |= (1 << ADSC);
  while (ADCSRA & (1 << ADSC)) {
  }
  return ADC;
}

#define LINE_MAX 32u

static char line[LINE_MAX];
static uint8_t line_len;
static uint8_t line_too_long;

static uint8_t line_feed(char c)
{
  if (c == '\r' || c == '\n') {
    if (line_len == 0 && !line_too_long) return 0;
    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;
  }
  return 0;
}

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

  if (line_too_long) {
    uart_puts("ERR line too long\r\n");
  } else if (strcmp(line, "LED ON") == 0) {
    PORTB |= (1 << PORTB5);
    uart_puts("OK LED ON\r\n");
  } else if (strcmp(line, "LED OFF") == 0) {
    PORTB &= ~(1 << PORTB5);
    uart_puts("OK LED OFF\r\n");
  } else if (strncmp(line, "PWM ", 4) == 0) {
    char *end;
    long pct = strtol(line + 4, &end, 10);
    if (end == line + 4 || *end != '\0' || pct < 0 || pct > 100) {
      uart_puts("ERR PWM needs a number from 0 to 100\r\n");
    } else {
      pwm_set_percent((uint8_t)pct);
      snprintf(reply, sizeof reply, "OK PWM %ld\r\n", pct);
      uart_puts(reply);
    }
  } else if (strcmp(line, "ADC?") == 0) {
    uint16_t raw = adc_read();
    uint16_t mv = (uint16_t)(((uint32_t)raw * 5000u + 512u) / 1024u);
    snprintf(reply, sizeof reply, "OK ADC %u %u mV\r\n", raw, 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;
}

static void serial_poll(void)
{
  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_errors) {
    rx_errors = 0;
    uart_puts("ERR framing or overrun: check the baud rate\r\n");
  }
}

void setup()
{
  DDRB |= (1 << DDB5);
  pwm_init();
  adc_init();
  uart_init();
  uart_puts("READY\r\n");
}

void loop()
{
  serial_poll();
}
