/* Copyright (c) 2011 Axel Wachtler, Daniel Thiele
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the
 documentation and/or other materials provided with the distribution.
 * Neither the name of the authors nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE. */

/* $Id$ */
/**
 * @file
 * @brief ....
 * @_addtogroup grpApp...
 */

/* avr-libc inclusions */
#include <avr/io.h>
#include <util/atomic.h>

/* uracoli inclusions */
#include <board.h>
#include <radio.h>
#include <hif.h>

/* project inclusions */
#include "sensorproto.h"
#include "rose.h"

#ifndef BAUD			/* try to get baudrate from build configuration settings */
#define BAUD (38400UL)	/* otherwise use this one */
#endif

#if defined(radiofaro)
#define DBGPIN0 _BV(PE2)
#define DBGPIN1 _BV(PE3)
#define DBGPIN_INIT() do{ PORTE &= ~(DBGPIN0 | DBGPIN1); DDRE |= (DBGPIN0 | DBGPIN1); }while(0)
#define DBGPIN_HI(pin) do{ PORTE |= pin; }while(0)
#define DBGPIN_LO(pin) do{ PORTE &= ~pin; }while(0)
#else
#define DBGPIN0 0
#define DBGPIN1 0
#define DBGPIN_INIT() do{  }while(0)
#define DBGPIN_HI(pin) do{  }while(0)
#define DBGPIN_LO(pin) do{  }while(0)
#endif

#define MAX_FRAME_SIZE (127)
#define RXFRM_FIFOSIZE (4) /* must be power of 2 */
#define RXFRM_FIFOMASK (0x03)

typedef struct{
	uint8_t phr; /**< PHY header (frame length) */
	uint8_t psdu[MAX_FRAME_SIZE]; /**< PHY payload */
	int8_t ed; /**< ED level */
	uint8_t lqi; /**< LQI */
}rxfrm_t;

static volatile struct{
	volatile uint8_t rdidx;
	volatile uint8_t wridx;
	rxfrm_t frm[RXFRM_FIFOSIZE];
}rxfrm;

static inline void print_rose(rose_measresult_t *measres)
{
#if 0
		printf("AX=%+05d AY=%+05d AZ=%+05d CX=%+05d CY=%+05d CZ=%+05d UP=%+05d",
		measres->acc.x, measres->acc.y, measres->acc.z,
		measres->comp.x, measres->comp.y, measres->comp.z,
		measres->pressure);
#else
		printf("AX=%04X AY=%04X AZ=%04X CX=%04X CY=%04X CZ=%04X UP=%04X",
		measres->acc.x, measres->acc.y, measres->acc.z,
		measres->comp.x, measres->comp.y, measres->comp.z,
		measres->pressure);
#endif
}

uint8_t * usr_radio_receive_frame(uint8_t len, uint8_t *frm, uint8_t lqi, int8_t ed, uint8_t crc_fail)
{
	rxfrm.frm[rxfrm.wridx].phr = len;
	rxfrm.frm[rxfrm.wridx].ed = ed;
	rxfrm.frm[rxfrm.wridx].lqi = lqi;

	ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
		rxfrm.wridx++;
		rxfrm.wridx &= RXFRM_FIFOMASK;
		if( rxfrm.wridx == rxfrm.rdidx){
			printf("Rx overflow\n");
		}
	}

	return (uint8_t*)rxfrm.frm[rxfrm.wridx].psdu;
}

void usr_radio_tx_done(radio_tx_done_t status)
{
	switch(status){
	case TX_OK:
		break;
	case TX_NO_ACK:
		break;
	case TX_FAIL:
		break;
	default:
		break;
	}	/* switch(status) */
}


/*
 * \brief Make putc function avr-libc compatible to make use of avr-libc printf/scanf facility
 */
static inline int hif_putc_libcwrapper(char c, FILE *stream)
{
	hif_putc((uint8_t)c);
	return EOF;
}

/*
 * \brief Make getc function avr-libc compatible to make use of avr-libc printf/scanf facility
 */
static inline int hif_getc_libcwrapper(FILE *stream)
{
	uint16_t c = hif_getc();
	return (c&0xFF00)?EOF:(c&0x00FF);
}

/* setup stream for UART communication */
static FILE usart_stdio = FDEV_SETUP_STREAM(hif_putc_libcwrapper, hif_getc_libcwrapper, _FDEV_SETUP_RW);

int main()
{
	rose_cfgframe_t rosecfg = {.hdr.FCF = 0x8861, .hdr.boardtype=BOARD_RADIOFARO, .hdr.frametype=SENSORPROTO_FRAMETYPE_ROSE_CFG,
			.hdr.srcaddr=0x00, .hdr.destpanid=0x22};
	rose_slowframe_t *slowfrm;
	rose_fastframe_t *fastfrm;
	sensorproto_hdr_t *hdrfrm;
	int c;
	uint8_t answerpending=0;

	DBGPIN_INIT();

	rxfrm.rdidx = 0;
	rxfrm.wridx = 0;

	radio_init((uint8_t*)rxfrm.frm[rxfrm.wridx].psdu, MAX_FRAME_SIZE);
	radio_set_param(RP_CHANNEL(SENSORPROTO_WORKCHANNEL));
	radio_set_param(RP_IDLESTATE(STATE_RXAUTO));
	radio_set_param(RP_PANID(0x22));
	radio_set_param(RP_SHORTADDR(0x00));

	hif_init(BAUD);
	stdin = stdout = stderr = &usart_stdio;

	sei();

	printf("Rose Host <BUILD %s %s>\n", __DATE__, __TIME__);

	printf("Commands:\n");
	printf("  1 : fast sampling 10ms\n");
	printf("  2 : fast sampling 10ms, store to flash 200ms\n");
	printf("  9 : readout flash\n");

	radio_set_state(STATE_RXAUTO);

	for(;;){
		if(EOF != (c=getchar()) ){
    		if( (c >= '0') && (c <= '9') ){
    			if(answerpending){
    				printf_P(PSTR("Skipping, already queued\n"));
    			}else{
    				switch(c){
    				case '1':
    					rosecfg.appmode = ROSE_APPMODE_FAST;
    					answerpending=1;
    					break;
    				case '2':
    					rosecfg.appmode = ROSE_APPMODE_FAST_FLASH;
    					answerpending=1;
    					break;
    				case '9':
    					rosecfg.appmode = ROSE_APPMODE_READFLASH;
    					answerpending=1;
    					break;
    				default:
    					break;
    				}	/* switch(c) */
    				if(answerpending){	/* if set above */
    					printf_P(PSTR("Queuing answer\n"));
    				}
    			}	/* if(answerpending) */
    		}
		}	/* if(EOF != (c=getchar()) ) */

		if(rxfrm.wridx != rxfrm.rdidx){
			DBGPIN_HI(DBGPIN0);
			hdrfrm = (sensorproto_hdr_t*)rxfrm.frm[rxfrm.rdidx].psdu;

			if(BOARD_ROSE231 == hdrfrm->boardtype){

				if(answerpending){
					rosecfg.hdr.destaddr = hdrfrm->srcaddr;	/* to where it came from */
					radio_set_state(STATE_TXAUTO);
					radio_send_frame(sizeof(rose_cfgframe_t), (uint8_t*)&rosecfg, 0);
					printf_P(PSTR("Answering\n"));
					answerpending=0;
				}

				if(SENSORPROTO_FRAMETYPE_ROSE_SLOW == hdrfrm->frametype){
					slowfrm = (rose_slowframe_t*)rxfrm.frm[rxfrm.rdidx].psdu;
					printf("# T=%04X ADDR=%04X ED=%02X ", slowfrm->data.tstamp, slowfrm->hdr.srcaddr, rxfrm.frm[rxfrm.rdidx].ed);
					print_rose(&slowfrm->data);
					printf(" BMPCAL=");
					for(uint8_t i=0;i<sizeof(slowfrm->bmp085prom)/sizeof(slowfrm->bmp085prom[0]);i++){
						printf("%02X", slowfrm->bmp085prom[i]);
					}
					printf(" VBAT[mV]=%04d", slowfrm->vbat_mv);
					printf(" UT=%02X", slowfrm->data.temperature);
					printf(" VERSION=%u.%u", slowfrm->version_maj, slowfrm->version_min);
					putchar('\n');
				}else if(SENSORPROTO_FRAMETYPE_ROSE_FAST == hdrfrm->frametype){
					fastfrm = (rose_fastframe_t*)rxfrm.frm[rxfrm.rdidx].psdu;
					printf("T=%04X ADDR=%04X ED=%02X ", fastfrm->data.tstamp, fastfrm->hdr.srcaddr, rxfrm.frm[rxfrm.rdidx].ed);
					print_rose(&fastfrm->data);
					putchar('\n');
				}else{
					printf("Unknown frametype %02X\n", hdrfrm->frametype);
				}
			}else{
				printf("Unknown board type %02X\n", hdrfrm->boardtype);
			}

			DBGPIN_LO(DBGPIN0);

			ATOMIC_BLOCK(ATOMIC_RESTORESTATE){
				rxfrm.rdidx++;
				rxfrm.rdidx &= RXFRM_FIFOMASK;	/* frame is processed */
				sei();
			}

		}	/* if(rxpending) */
	}
}

/* EOF */
