#include "serial.h"
#include "usb_start.h"

#define MAX_PRINTF_BUFFER (64)

static uint8_t printf_buffer[MAX_PRINTF_BUFFER];
static volatile bool b_usb_ready = false;

static bool usb_cb_state_c(usb_cdc_control_signal_t state)
{
	if(state.rs232.DTR == 1)
	{
		b_usb_ready = true;
	}
	else
	{
		b_usb_ready = false;
	}
	return false;
}

void arc_serial_init()
{
	memset(printf_buffer, '\0', MAX_PRINTF_BUFFER);
	usb_init();
	while(!cdcdf_acm_is_enabled()){}
	cdcdf_acm_register_callback(CDCDF_ACM_CB_STATE_C, (FUNC_PTR)usb_cb_state_c);
	while(!b_usb_ready);
	delay_ms(2000);
}

uint8_t arc_printf(const char* fmt, ...)
{
	while(!b_usb_ready){}
	va_list args;
	va_start(args, fmt);
	vsprintf(printf_buffer, fmt, args);
	va_end(args);
	volatile int32_t ret = cdcdf_acm_write(printf_buffer, (uint32_t)(strlen((const char*)printf_buffer)));
	return 0;
}

