#include "stm32l1xx_hal.h"
#include "stm32l1xx_hal_gpio.h"

unsigned int blinkLed = 0;
unsigned int blinkTxLed = 0;

// Interface function to blink the green LED
void blinkTheLED() {
  blinkLed++;
}

// Interface function to blink the blue LED
void blinkTheTxLED() {
  blinkTxLed++;
}

enum {
  MODE_INACTIVE,
  MODE_ON,
  MODE_OFF,
  MODE_SWITCH,   // Just have been off
};

void rxLed() {
  static unsigned long timer = 0;
  static int mode = MODE_INACTIVE;

  switch( mode ) {

  case   MODE_INACTIVE:
    if( blinkLed > 0 ) {
      blinkLed--;
      mode = MODE_ON;
      timer = 1;
      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,(GPIO_PinState)1);
    }
    break;

  case MODE_ON:
    timer--;
    if( timer == 0 ) {
      mode = MODE_OFF;
      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,(GPIO_PinState)0);
      timer = 1;
    }
    break;

  case MODE_OFF:
    timer--;
    if( timer == 0 ) {
      mode = MODE_INACTIVE;
      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,(GPIO_PinState)0);
      break;

    }
  }
}

void txLed() {
  static unsigned long timer = 0;
  static int mode = MODE_INACTIVE;

  switch( mode ) {

  case   MODE_INACTIVE:
    if( blinkTxLed > 0 ) {
      blinkTxLed--;
      mode = MODE_ON;
      timer = 1;
      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,(GPIO_PinState)1);
    }
    break;

  case MODE_ON:
    timer--;
    if( timer == 0 ) {
      mode = MODE_OFF;
      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,(GPIO_PinState)0);
      timer = 1;
    }
    break;

  case MODE_OFF:
    timer--;
    if( timer == 0 ) {
      mode = MODE_INACTIVE;
      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_6,(GPIO_PinState)0);
      break;

    }
  }
}

// 10Hz timer interrupt function
void led_interrupt(){

  rxLed();
  txLed();
}

