#include <string.h>
#include <inttypes.h>
#include "uart.h"
#include "serial.h"

extern void uart_send_buf(uint8_t * buf, uint8_t len);

/*!
*  Serialize a cmd_msg structure with its variable payload size
*  specified by \em payloadlen and copy it into \em buf.
*/
int serialize_msg(cmd_msg_t *p_msg, uint8_t *buf, int payloadlen)
{
	buf[0] = p_msg->header.type;
	buf[1] = p_msg->header.cmd;
	memcpy(&buf[2], p_msg->payload, payloadlen);
	return payloadlen + 2;
}

/*! 
*  Send a uart cmd_msg to turn on the LCD's led.
*/
void led_on(){
    cmd_msg_t cmd_msg;
	cmd_msg.header.type = LED;
	cmd_msg.header.cmd = ON;
	uart_send_buf((uint8_t *) &cmd_msg.header, sizeof(cmd_msg.header));
}

/*! 
*  Send a uart cmd_msg to turn off the LCD's led.
*/
void led_off(){
    cmd_msg_t cmd_msg;
	cmd_msg.header.type = LED;
	cmd_msg.header.cmd = OFF;
	uart_send_buf((uint8_t *) &cmd_msg.header, sizeof(cmd_msg.header));
}

/*! 
*  Send a uart cmd_msg to sample temperature using Raven's 
*  on-board temperature sensor.  The temperature value will
*  be shown on the LCD.
*/
void sample_temp(){
    cmd_msg_t cmd_msg;
	cmd_msg.header.type = LCD;
	cmd_msg.header.cmd = DISPLAY_TEMP;
	uart_send_buf((uint8_t *) &cmd_msg.header, sizeof(cmd_msg.header));
}

/*!
*  Display the string on the LCD's display.
*/
void print_msg(const char * buf, int len)
{
    cmd_msg_t cmd_msg;
	int buflen;
	uint8_t s_buf[80];

	cmd_msg.header.type = LCD;
	cmd_msg.header.cmd = DISPLAY_MSG;
	cmd_msg.payload = (uint8_t *) buf;
	buflen = serialize_msg(&cmd_msg, s_buf, len);
	uart_send_buf(s_buf, buflen);
}

/*!
*  Display a number on the LCD's display.
*/
void print_num(int num){
    cmd_msg_t cmd_msg;
	int buflen;
	uint8_t s_buf[80];

	cmd_msg.header.type = LCD;
	cmd_msg.header.cmd = DISPLAY_NUM;
	cmd_msg.payload = (uint8_t *) &num;
	buflen = serialize_msg(&cmd_msg, s_buf, 2);
	uart_send_buf(s_buf, buflen);
}
