/*
 * main.c
 *
 *  Created on: 12.01.2010
 *      Author: dthiele
 */

#include <avr/io.h>
#include <util/delay.h>
#include <ioutil.h>
#include <transceiver.h>

#include "../inc/wibocmd.h"


/* this is parsed and set from outside */
#ifndef NODEID
#warning "NODEID not defined, setting to 0x00"
#define NODEID (0x00)
#endif


#ifndef BLINKPERIOD
#define BLINKPERIOD (0xFFFFUL)
#endif

/* incoming frames are collected here */
static uint8_t rxbuf[MAX_FRAME_SIZE];

/* configuration data of node
 * hard coded and compiled into binary
 */
static const struct{
	uint16_t panid;		/* PAN ID */
	uint16_t nodeid;	/* Node ID (short addressing mode) */
}nodeconfig = { .panid = 0x01, .nodeid = NODEID };

const void (*bootl)(void) = (void*)0x1800;

int main()
{
	uint8_t i;
	volatile uint32_t cnt=0;

	LED_INIT();
	trx_io_init(DEFAULT_SPI_RATE);
	trx_init();

	DI_TRX_IRQ();

	trx_reg_write(RG_TRX_STATE, CMD_TRX_OFF);
    trx_reg_write(RG_TRX_CTRL_1, 0x20);			/* set TX_AUTO_CRC bit */

	/* setup network addresses for auto modes */
	trx_reg_write(RG_PAN_ID_0, (uint8_t)(nodeconfig.panid & 0x00FF));
	trx_reg_write(RG_PAN_ID_1, (uint8_t)(nodeconfig.panid >> 8));
	trx_reg_write(RG_SHORT_ADDR_0, (uint8_t)(nodeconfig.nodeid & 0x00FF));
	trx_reg_write(RG_SHORT_ADDR_1, (uint8_t)(nodeconfig.nodeid >> 8));

    trx_reg_write(RG_IRQ_MASK, TRX_IRQ_TRX_END);
	trx_reg_write(RG_TRX_STATE, CMD_RX_AACK_ON);

	for(;;){

		if(cnt++ >= BLINKPERIOD){
			cnt=0;
			LED_TOGGLE(0);
		}

		if((trx_reg_read(0x0F) & TRX_IRQ_TRX_END)){
			trx_frame_read(rxbuf, 128, &i);		/* dont use LQI, write into tmp variable */

			switch( ((wibocmd_hdr_t*)rxbuf)->command){

			case WIBOCMDCODE_XMPLJBOOTL:
				bootl();				/* jump to */
				break;

			case WIBOCMDCODE_XMPLLED:
				if(((wibocmd_xmplled_t*)rxbuf)->state){
					LED_SET(((wibocmd_xmplled_t*)rxbuf)->led);
				}else{
					LED_CLR(((wibocmd_xmplled_t*)rxbuf)->led);
				}
				break;

			default :
				/* unknown or unhandled command */
				break;
			};
		}
	}
}

/* EOF */
