/*
 * app.c
 *
 *  Created on: Feb 27, 2025
 *      Author: gca76
 */
#include "globals.h"
#include "app.h"

#include "gpio.h"
#include "rgb.h"
#include "buttons.h"
#include "adc.h"
#include "pwm.h"

#include "task_blinky.h"
#include "task_buttons.h"
#include "task_joystick.h"
#include "task_display.h"
#include "task_led.h"

#include "ssd1306.h"
#include "ssd1306_fonts.h"
#include "tim.h"
#include "imu_accel.h"
#include "filter.h"

// Scheduler task timing
static uint32_t blinkyTaskNextRun = 0;
static uint32_t buttonTaskNextRun = 0;
static uint32_t joystickTaskNextRun = 0;
static uint32_t displayTaskNextRun = 0;
static uint32_t ledTaskNextRun = 0;


void app_main(void)
{

	buttons_init();
	rgb_colour_all_on(); // sets all power lines to low
	ssd1306_Init();
	HAL_TIM_Base_Init(&htim2); // sets timer for pwm
	HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3);
	pwm_setDutyCycle(&htim2, TIM_CHANNEL_3, 0); // start with 0% duty cycle
	imu_accel_init(); // Initialize IMU accelerometer
	init_filter(&x_filter);
	init_filter(&y_filter);
	init_filter(&z_filter);


	blinkyTaskNextRun = HAL_GetTick() + BLINKY_TASK_PERIOD_TICKS;
	buttonTaskNextRun = HAL_GetTick() + BUTTON_TASK_PERIOD_TICKS;
	joystickTaskNextRun = HAL_GetTick() + JOYSTICK_TASK_PERIOD_TICKS;
	displayTaskNextRun = HAL_GetTick() + DISPLAY_TASK_PERIOD_TICKS;
	ledTaskNextRun = HAL_GetTick() + LED_TASK_PERIOD_TICKS;

	while (1)
	{
	  uint32_t ticks = HAL_GetTick();
	  buttons_update(); // Update buttons state at each iteration of the while loop

	  if(ticks > blinkyTaskNextRun)
	  {
		  blinky_task_execute();

		  blinkyTaskNextRun += BLINKY_TASK_PERIOD_TICKS;
	  }

	  if (ticks > buttonTaskNextRun)
	  {
		  button_task_execute();
		  buttonTaskNextRun += BUTTON_TASK_PERIOD_TICKS;
	  }

	  if (ticks > joystickTaskNextRun)
	  {
		  joystick_task_execute();
		  joystickTaskNextRun += JOYSTICK_TASK_PERIOD_TICKS;
	  }

	  if (ticks > displayTaskNextRun)
	  {
		  display_task_execute();
		  displayTaskNextRun += DISPLAY_TASK_PERIOD_TICKS;
	  }

	  if (ticks > ledTaskNextRun)
	  {
		  led_task_execute();
		  ledTaskNextRun += LED_TASK_PERIOD_TICKS;
	  }
	}
}
