/******************************************************************************
 * @file rf_debug.c
 * @brief Remote Serial Transmitter for TDxxxx RF modules.
 * @author Telecom Design S.A.
 * @version 1.0
 ******************************************************************************
 * @section License
 * <b>(C) Copyright 2012-2015 Telecom Design S.A., http://www.telecomdesign.fr</b>
 ******************************************************************************
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 *
 * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Telecom Design SA has no
 * obligation to support this Software. Telecom Design SA is providing the
 * Software "AS IS", with no express or implied warranties of any kind,
 * including, but not limited to, any implied warranties of merchantability
 * or fitness for any particular purpose or warranties against infringement
 * of any proprietary rights of a third party.
 *
 * Telecom Design SA will not be liable for any consequential, incidental, or
 * special damages, or any other relief, or for any claim by any third party,
 * arising from your use of this Software.
 *
  ******************************************************************************/
  

#include <td_lan.h>
#include <td_printf.h>
#include <stdarg.h>

#include "rf_debug.h"


//Array to store data
static uint8_t DebugBuffer[17];

// Data counter
static uint8_t DebugCount = 0;

// Send current data and pad with 0
static void Send()
{
	 TD_LAN_frame_t TX;
	 TX.header = 0;

	 //copy data
	 memcpy(&TX.payload[0],DebugBuffer,DebugCount);

	 //fill remaining with 0
	 memset(&TX.payload[DebugCount],0,17-DebugCount);

	 //send data as single frame
	 TD_LAN_SendFrame(1, &TX, 0);

	 //reset counter
	 DebugCount = 0;
}

// Called by printf each time a new char should be outputed
// just save char and force output if maximum frame size is reached
static void Putc(void *p, char c)
{
	//add char to buffer
	DebugBuffer[DebugCount] = c;

	//if reaches frame size force transmission
	if(++DebugCount == 17)
	{
		Send();
	}
}


// Init lan
void RF_Debug_Init(uint32_t freq, int16_t level)
{
    TD_LAN_Init(true, 0, 0);
    TD_LAN_SetFrequencyLevel(freq, level);
}

// Make use of tfp_format to mimic printf
void rf_printf(char *fmt, ...)
{
	va_list va;

	va_start(va, fmt);
	tfp_format(0, Putc, fmt, va);
	Send();

	va_end(va);
}

