/*
 * switches.c
 *
 *  Created on: May 31, 2017
 *      Author: wn
 */


#include <hmi.h>
#include "stm32f1xx_hal.h"
#include "switches.h"



volatile uint32_t lastEvent = 0;


void switch_interrupt() {
  static uint8_t state = 0;
  uint32_t currentEvent = HAL_GetTick();

  GPIO_PinState line = HAL_GPIO_ReadPin(SWITCH_GPIO_Port, SWITCH_Pin);

  switch (state) {
  case 0:
    if (line == GPIO_PIN_RESET) {
      lastEvent = currentEvent;
      state = 1;
    }
    break;
  case 1:
    if (line != GPIO_PIN_RESET) {
      if (lastEvent + LONG_BUTTON_TIME + DEBOUNCING_DEAD_TIME < currentEvent) {
        lastEvent = currentEvent;
        buttonLong();
        state = 0;
      } else if (lastEvent + DEBOUNCING_DEAD_TIME < currentEvent) {
        lastEvent = currentEvent;
        buttonShort();
        state = 0;
      }
    }
    break;
  default:
    state = 0;
  }
}

int myDigitalRead(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) {
  int16_t r = 0;
  for (uint32_t i = 0; i < DEBOUNCING_REPEAT; i++) {
    if (HAL_GPIO_ReadPin(GPIOx, GPIO_Pin) != GPIO_PIN_RESET) {
      r++;
    } else {
      r--;
    }
  }
  int res = -1;
  if (r >= (((int32_t)DEBOUNCING_REPEAT) / 2)) {
    res = 1;
  } else if (r <= -1 * (((int32_t)DEBOUNCING_REPEAT) / 2)) {
    res = 0;
  }
  return res;
}


void rotary_a_interrupt() {
  uint32_t currentEvent = HAL_GetTick();

  if ((lastEvent == 0) || (lastEvent + DEBOUNCING_DEAD_TIME < currentEvent)) {
    lastEvent = currentEvent;

    int a = myDigitalRead(ROTARY_A_GPIO_Port, ROTARY_A_Pin);;
    int b = myDigitalRead(ROTARY_B_GPIO_Port, ROTARY_B_Pin);;

    if (((a != -1) && (b != -1))) {
      if (a == b) {
        displayIncValue();
      } else {
        displayDecValue();
      }
    }
  }
}

void rotary_b_interrupt() {
  uint32_t currentEvent = HAL_GetTick();

  if ((lastEvent == 0) || (lastEvent + DEBOUNCING_DEAD_TIME < currentEvent)) {
    lastEvent = currentEvent;

    int a = myDigitalRead(ROTARY_A_GPIO_Port, ROTARY_A_Pin);;
    int b = myDigitalRead(ROTARY_B_GPIO_Port, ROTARY_B_Pin);;

    if (((a != -1) && (b != -1))) {
      if (a == b) {
        displayDecValue();
      } else {
        displayIncValue();
      }
    }
  }
}


void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
  if (GPIO_Pin == GPIO_PIN_5) {
    switch_interrupt();
  }
  if (GPIO_Pin == GPIO_PIN_3) {
    rotary_a_interrupt();
  }
  if (GPIO_Pin == GPIO_PIN_4) {
    // rotary_b_interrupt();
  }
}

