#include <Ethernet.h>
#include <TwitPic.h>
#include <CameraC328R.h>
#include <NewSoftSerial.h>
 
#define SNAPSHOT     4
#define ERROR_LED    5
#define PROGRESS_LED 6
 
#define CAMERA_BAUD 57600
 
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 2, 120 };
byte gateway[] = {192, 168, 2, 1};
byte subnet[] = { 255, 255, 255, 0};
 
TwitPic twitpic("tweeting_hamste","logi23te");
 
CameraC328R camera;
 
uint16_t pictureSize = 0;
Client *targetClient;
 
/**
 * This callback is called EVERY time a JPEG data packet is received.
 */
void getJPEGPicture_callback( uint16_t pictureSize, uint16_t packageSize, uint16_t packageCount, byte* package )
{
  targetClient->write(package,packageSize);
}
 
uint32_t c328rImageTransfer(Client *client)
{
  if(client){
    targetClient = client;
    camera.getJPEGPictureData( &getJPEGPicture_callback );
  }
  return pictureSize;
}
 
void setup()
{
  Ethernet.begin(mac, ip, gateway, subnet); 
  Serial.begin( CAMERA_BAUD );
 
  pinMode( PROGRESS_LED, OUTPUT );
  digitalWrite( PROGRESS_LED, HIGH );
 
  pinMode( ERROR_LED, OUTPUT );
  digitalWrite( ERROR_LED, HIGH );
 
  pinMode( SNAPSHOT, INPUT );
  digitalWrite( SNAPSHOT, HIGH ); // pull-up
 
  delay(10000);
 
  digitalWrite( PROGRESS_LED, LOW );
  digitalWrite( ERROR_LED, LOW );
}
 
void loop()
{
  do {
    if( digitalRead(SNAPSHOT) == LOW ){
 
      digitalWrite( PROGRESS_LED, HIGH );
      digitalWrite( ERROR_LED, LOW );
 
      if( !camera.sync() ){
        goto camera_error;
      }
 
      if( !camera.initial( CameraC328R::CT_JPEG, CameraC328R::PR_160x120, CameraC328R::JR_640x480 ) ){
        goto camera_error;
      }
 
      if( !camera.setPackageSize( 64 ) ){
        goto camera_error;
      }
 
      if( !camera.setLightFrequency( CameraC328R::FT_50Hz ) ){
        goto camera_error;    
      }
 
      if( !camera.snapshot( CameraC328R::ST_COMPRESSED, 0 ) ){
        goto camera_error;    
      }
 
      pictureSize = 0;
      if( !camera.getJPEGPictureSize( CameraC328R::PT_SNAPSHOT, PROCESS_DELAY, pictureSize) ){
        goto camera_error;    
      }
 
      if(twitpic.upload(&c328rImageTransfer) < 0){
        goto camera_error;
      }
 
      camera.powerOff();
      break;
 
camera_error:
      digitalWrite( ERROR_LED, HIGH );
    }
 
    digitalWrite( PROGRESS_LED, LOW );
    delay(100);
  }
  while(0);
}