/*
 * ws2812.c
 *
 *  Created on: Mar 25, 2026
 *      Author: ewars
 */

#include <ws2812_drv.h>
#include "stm32f1xx_hal.h"
#include "tim.h"


static void set_byte(uint32_t pos, uint8_t value);

uint8_t pwm_reset[RESET_LEN] = {0};
uint8_t pwm_full = 100;

uint8_t ledStripBuffer[RESET_LEN +  LED_N * 24 + 1] = {0};

void ws2812_Init(void){

	for(uint32_t i = 0; i < LED_N * 24; i++){
		ledStripBuffer[RESET_LEN + i] = PWM_ONE;
	}

	ledStripBuffer[RESET_LEN + LED_N * 24] = pwm_full;

	ws2812_update();

}

void ws2812_update(void){
	HAL_TIM_PWM_Start_DMA(&htim2, TIM_CHANNEL_1, (const uint32_t*) ledStripBuffer, sizeof(ledStripBuffer));
}

void ws2812_set_colour(uint8_t led, uint8_t red, uint8_t green, uint8_t blue){

	if(led < LED_N){
		set_byte(RESET_LEN + 24 * led, green);
		set_byte(RESET_LEN + 24 * led + 8, red);
		set_byte(RESET_LEN + 24 * led + 16, blue);
	}

}

void ws2812_resetColour(uint8_t r, uint8_t g, uint8_t b){

	for(uint8_t i = 0; i < LED_N; i++){
		ws2812_set_colour(i, r, g, b);
	}

}

void ws2812_reset(void){
	for(uint8_t i = 0; i < LED_N; i++){
		ws2812_set_colour(i, 0, 0, 0);
	}
}

static void set_byte(uint32_t pos, uint8_t value)
{
  int i;
  for (i = 0; i < 8; i++) {
    if (value & 0x80) {
      ledStripBuffer[pos + i] = PWM_ONE;
    } else {
      ledStripBuffer[pos + i] = PWM_ZERO;
    }

    value <<= 1;
  }
}



void ws2812_wait(void){
	while(HAL_TIM_GetChannelState(&htim2, (uint32_t) TIM_CHANNEL_1)){}
}


