
// XBee wireless connection
#include "config.h"

#define BUF_SIZE 5
#define WRITE_PERIOD 1000

void AppLed_SetAll( int state );
void XBeeTask( void* p );
void BlinkTask( void* p );

void Run( ) // this task gets called as soon as we boot up.
{
  TaskCreate( XBeeTask, "XBee", BUF_SIZE + 500, 0, 2 );
  TaskCreate( BlinkTask, "Blink", 400, 0, 1 );
}

void XBeeTask( void *p)
{
  (void)p;
  uchar readBuf[BUF_SIZE]; // the buffer we'll be reading into
  int writeCounter = 0; // we'll only want to write every once in a while
  bool dataValue = false;
  int available;
  Serial_SetActive( 1 ); // initialize the Serial subsystem
  
  // then start your continuous loop
  while( 1 )
  {
    available = Serial_GetReadable( );
    if( available )
    {
      // make sure we only read as much as we have room for
      available =  (available > BUF_SIZE) ? BUF_SIZE : available;
      Serial_Read( readBuf, available, 0 );
      if( readBuf[0] == '1' )
        AppLed_SetAll( 1 );
      else
        AppLed_SetAll( 0 );
    }
    
    if( writeCounter++ > WRITE_PERIOD )
    {
      uchar x = dataValue ? '1' : '0';
      dataValue = !dataValue;
      Serial_Write( &x, 1, 0 );
      writeCounter = 0; // reset the counter
    }
    Sleep( 1 );
  }
}

void AppLed_SetAll( int state )
{
  AppLed_SetState( 0, state );
  AppLed_SetState( 1, state );
  AppLed_SetState( 2, state );
  AppLed_SetState( 3, state );
}

void BlinkTask( void* p )
{
  (void)p;
  Led_SetState( 1 );
  Sleep( 1000 );

  while ( true )
  {
    Led_SetState( 0 );
    Sleep( 900 );
    Led_SetState( 1 );
    Sleep( 10 );
  }
}






