/*
	blog.makezine.com RSS notifier

  Use the Make Controller as an RSS client and check for new material on the Make blog.
*/

#include "config.h"
#include "stdlib.h"
#include "string.h"
#include <stdio.h>

#include "webclient.h"

void BlinkTask( void* parameters );
void ReaderTask( void* p );
void onNewPost( void );

void Run( ) // this task gets called as soon as we boot up.
{
  TaskCreate( BlinkTask, "Blink", 400, 0, 1 );
  Network_SetActive( true ); // Starts the network up.
  TaskCreate( ReaderTask, "Read", 3500, 0, 1 );
}

#define RSS_FREQUENCY 10 // the number of minutes to wait between each RSS request

void ReaderTask( void* p )
{
  (void)p;
  int addr = IP_ADDRESS( 72, 34, 58, 9 ); // the address we got for blog.makezine.com
  int buffLength = 1000;
  char responseBuffer[buffLength];
  char* begin;
  char* end;
  char lastDate[50];
  while( 1 )
  {
		int getSize = WebClient_Get( addr, 80, "blog.makezine.com", "/index.xml", responseBuffer, buffLength );
    if( getSize > 0 )
    {
      begin = responseBuffer;
      while( getSize-- ) // cruise through all the characters we've received
      {
        if( *begin != '<' ) // look for the beginning of a tag
          begin++;
        else
        {
          end = ++begin;
          while( *end != '>' ) // now find the end of the tag
            end++;
          *end = '\0'; // null-terminate the string so we can compare it
          if( strcmp( begin, "lastBuildDate" ) == 0 ) // we found the tag with our date
          {
            begin = ++end;
            while( *end != '<' )
              end++;
            *end = '\0'; // terminate the date string
            if( strcmp( begin, lastDate ) != 0 )
            {
              snprintf( lastDate, 50, begin );
              onNewPost( ); // do our notification
              break;
            }
          }
          else
            begin = end++;
        }
      }
    }
    Sleep( RSS_FREQUENCY * 60 * 1000 );
  }
}

// replace this with whatever kind of notification you like...
void onNewPost( )
{
  int repeats = 10;
  while (repeats--)
  {
    AppLed_SetState( 0, 1 ); // turn everything on
    AppLed_SetState( 1, 1 );
    AppLed_SetState( 2, 1 );
    AppLed_SetState( 3, 1 );
    DigitalOut_SetValue( 0, 1 );
    Sleep( 500 ); // leave them on for a 1/2 second
    AppLed_SetState( 0, 0 ); // turn everything off
    AppLed_SetState( 1, 0 );
    AppLed_SetState( 2, 0 );
    AppLed_SetState( 3, 0 );
    DigitalOut_SetValue( 0, 0 );
    Sleep( 500 ); // leave them off for a 1/2 second
  }
}

void BlinkTask( void* p )
{
 (void)p;
  Led_SetState( 1 );
  Sleep( 1000 );

  while ( true )
  {
    Led_SetState( 0 );
    Sleep( 900 );
    Led_SetState( 1 );
    Sleep( 10 ); 
  }
}


