#include <rtthread.h>
#include "flash.h"
#include "buffer.h"
#include "usart.h"
#include "plan.h"
#include "weight.h"
#include "display.h"

rt_sem_t thread_init_sem = RT_NULL;
void init_usart(void)
{	
		__HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE); //使能IDLE中断
		HAL_UART_Receive_DMA(&huart1, rx_buffer1, BUFFER_SIZE);

		__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE); //使能IDLE中断
		HAL_UART_Receive_DMA(&huart2, rx_buffer2, BUFFER_SIZE);

		__HAL_UART_ENABLE_IT(&huart3, UART_IT_IDLE); //使能IDLE中断
		HAL_UART_Receive_DMA(&huart3, rx_buffer3, BUFFER_SIZE);

		__HAL_UART_ENABLE_IT(&huart4, UART_IT_IDLE); //使能IDLE中断
		HAL_UART_Receive_DMA(&huart4, rx_buffer4, BUFFER_SIZE);
}

static void init_entry(void *parameter)
{	
	  RB_init();		
		onbordflash_init();
	  init_usart();			
		rt_sem_release(thread_init_sem);
}

#define THREAD_PRIORITY         3
#define THREAD_STACK_SIZE       800
#define THREAD_TIMESLICE        5
static  rt_thread_t tid1 = RT_NULL;

void thread_init(void)
{
    thread_init_sem = rt_sem_create("thread_init_sem", 0, RT_IPC_FLAG_FIFO);
	  pop_product_sem = rt_sem_create("pop_product_sem", 0, RT_IPC_FLAG_FIFO);	
  	delay_key_sem = rt_sem_create("delay_key_sem", 0, RT_IPC_FLAG_FIFO);
	
		weight_lock = rt_sem_create("weight_lock", 1, RT_IPC_FLAG_FIFO);
	  display_lock = rt_sem_create("display_lock", 1, RT_IPC_FLAG_FIFO); 
	  rt_event_init(&display_event, "display_event", RT_IPC_FLAG_FIFO);	
	  
    uart1_lock = rt_sem_create("uart1_lock", 1, RT_IPC_FLAG_FIFO);
    uart2_lock = rt_sem_create("uart2_lock", 1, RT_IPC_FLAG_FIFO);
    uart3_lock = rt_sem_create("uart3_lock", 1, RT_IPC_FLAG_FIFO);
    uart4_lock = rt_sem_create("uart4_lock", 1, RT_IPC_FLAG_FIFO);
    uart5_lock = rt_sem_create("uart5_lock", 1, RT_IPC_FLAG_FIFO);
	
	  thread_EmptyBuffer_sem = rt_sem_create("thread_EmptyBuffer_sem", 0, RT_IPC_FLAG_FIFO);
	 
    tid1 = rt_thread_create("init_entry",
                            init_entry, RT_NULL,
                            THREAD_STACK_SIZE,
                            THREAD_PRIORITY, THREAD_TIMESLICE);

    /* 如果获得线程控制块，启动这个线程 */
    if (tid1 != RT_NULL)
        rt_thread_startup(tid1);
}
