/***********************************************************************
 * Copyright (c)  2017 - 2020, Unicmicro Co.,Ltd .
 * All rights reserved.
 * Filename    : app.c
 * Description : app driver source file
 * Author(s)   : wanyi
 * version     : V1.0
 * Modify date : 2020-07-27
 ***********************************************************************/
#include  "system_um800x.h"
#include  "app.h"
#include  "config.h"
#include  "common.h"
#include  "uart0.h"
#include  "i2c.h"

volatile uint8_t rx_flag ;
volatile uint8_t uart0_rx_buf[32];
volatile uint8_t uart0_tx_buf[32];
volatile uint16_t rx_count = 0;
volatile uint16_t tx_count = 0;
/************************************************************************
 * function   : uart0_rec_pro
 * Description: uart0_rec_pro 串口接收处理回调函数
 * input : none
 * return: none
 ************************************************************************/
void uart0_rec_pro(void)
{
	uart0_rx_buf[rx_count++]= uart0_recv_byte();
	rx_flag = 1;	
}

/************************************************************************
 * function   : uart_init
 * Description: uart_init 串口初始化
 * input : none
 * return: none
 ************************************************************************/
void uart_init(void)
{
	rx_flag = 0;
	uart0_init(UART0_BAUD_RATE);
    uart0_irq_init(UART0_IRQ_ENABLE,uart0_rec_pro);
}

void i2c_test(void)
{
	i2c_slave_test();
}

void i2c_slave_test(void)
{
	i2c_slave_read_test();
//	i2c_slave_write_test();
}

void i2c_slave_write_test(void)
{
	uint8_t xdata i;
	uint8_t xdata len;
	uint8_t xdata i2c_slave_send_data[20];
	for(i=0 ; i<8; i++)
	{
		i2c_slave_send_data[i] = i+0xa0;
	
	}
	
	printfS("i2c slave write test start\r\n");
	i2c_slave_init();							//从机初始化
	i2c_set_slave_addr1(I2C_SLAVE_ADDR);		//设置从机地址
	
	while(1)
	{	
		if(i2c_slave_is_match_addr1()) 			//maas1匹配
		{				
			len = i2c_slave_write_data(i2c_slave_send_data);
			printfS("match addr1,i2c slave send\n");				
		}
		if(i2c_slave_is_match_addr2()) 			//maas2匹配
		{				
			len = i2c_slave_write_data(i2c_slave_send_data);
			printfS("match addr2,i2c slave send\n");				
		}
		
	}


}


void i2c_slave_read_test(void)
{
	uint8_t xdata len;
	uint8_t xdata i2c_slave_recv_data[20];
	uint16_t count=0;
	printfS("i2c slave read test start\r\n");
	
	i2c_slave_init();							//从机初始化
	i2c_set_slave_addr1(I2C_SLAVE_ADDR);		//设置从机地址
	i2c_ack();									//使能应答ACK
	while(1)
	{	
		if(i2c_slave_is_match_addr1()) 			//maas1匹配
		{	
			len = i2c_slave_read_data(i2c_slave_recv_data);
			printfS("match addr1,i2c slave receive\n");
			printfS("count：%d\n",count++);
			printfB8(i2c_slave_recv_data,len);
		}
		if(i2c_slave_is_match_addr2()) 			//maas2匹配
		{	
			len = i2c_slave_read_data(i2c_slave_recv_data);
			printfS("match addr2,i2c slave receive\n");
			printfB8(i2c_slave_recv_data,len);
		}
		
	}

}
