/*
Copyright 2003/2004, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

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 Freie Universitaet Berlin (FUB) 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 FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB 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.

This implementation was developed by the CST group at the FUB.
Contributors: Bjoern Lichtblau

For documentation and questions please use the web site
http://www.scatterweb.net and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2003/2004/2005
*/

#include <io.h>
#include "ScatterWeb.Event.h"
#include "lib/ScatterWeb.JTAGFunc.h"
#include "lib/ScatterWeb.LowLevelFunc.h"
#include "lib/ScatterWeb.Routing.h"
#include "../../../../System/src/ScatterWeb.System.h"

void Process_interceptRadioHandler() {

}

void Process_radioHandler() {
  if ( !(rxPacket.to == BROADCAST || rxPacket.to == Configuration.id) ) {
    Process_interceptRadioHandler();
  }
  else {
    switch(rxPacket.type){
      case ACK_PACKET: break;
      case SYNCH_PACKET: break;
      case MESSAGING_REQ_PACKET: Messaging_requestHandler(); break;
      case MESSAGING_ANS_PACKET: Messaging_answerHandler(); break;
      case ROUTING_INFO:        if(Configuration.firmwareFlags & FF_ROUTING) Routing_infoHandler(); break;
      case ROUTING_REQUEST:     if(Configuration.firmwareFlags & FF_ROUTING) Routing_requestHandler(); break;
      case ROUTING_ACCEPT:      if(Configuration.firmwareFlags & FF_ROUTING) Routing_acceptHandler(); break;
      case ROUTING_DENY:        if(Configuration.firmwareFlags & FF_ROUTING) Routing_denyHandler(); break;
      case ROUTING_NOCHILD:     if(Configuration.firmwareFlags & FF_ROUTING) Routing_noChildHandler(); break;        
      case ROUTING_ROOTPACKET:  if(Configuration.firmwareFlags & FF_ROUTING) Routing_rootPacketHandler(); break;
      case ROUTING_TREEPACKET:  if(Configuration.firmwareFlags & FF_ROUTING) Routing_treePacketHandler(); break;
      case PING_PACKET: 
         if (rxPacket.to == Configuration.id) {
           packet_t packet;
           packet.to = rxPacket.from;    packet.type = PONG_PACKET;
           packet.header_length = 0;     packet.header = NULL;
           packet.data_length = 0;       packet.data = NULL;
           Net_send(&packet, NULL);
         }
         break;
      case PONG_PACKET: 
          if (rxPacket.to == Configuration.id) {
            Comm_print("PONG from %i\r\n", rxPacket.from);   
          }
          break;
      case SENSOR_PACKET: {
            UINT16 i, j;
            j = rxPacket.data_length / sizeof(sdata_t);
            for(i=0; i<j; i++) {
              sdata_t* sdata = ((sdata_t*) rxPacket.data) + i;
              if(sdata->timeStamp.secs == 0 && sdata->timeStamp.millis == 0) sdata->timeStamp = CURRENT_TIME;
              Comm_print("$ %e\r\n", sdata); 
            }
          }
          break;
      case PICTURE_ANS_PACKET: {
            UINT16 id = rxPacket.data[0] + (rxPacket.data[1]<<8);
            if(id==0xFFFF) { // ERROR
                Comm_print("ERROR: %s\r\n", &rxPacket.data[2]); 
            }
            else if(id==0xF0F1) {
              Comm_print("OK PIC %i\r\n", (*((UINT16*)&rxPacket.data[2]))  );         
            }
            else if(id==0xF0F0) {
              Comm_print("%b", '*');
              Comm_print("%b", id>>8);
              Comm_print("%b", id);
              Comm_print("%b", 0);
              Comm_print("%b", 0);
              Comm_print("OK PIC done\r\n");
            }
            else { // data
              UINT16 dlength = rxPacket.data_length - 2;
              Comm_print("%b", '*');
              Comm_print("%b", id>>8);
              Comm_print("%b", id);
              Comm_print("%b", dlength>>8);
              Comm_print("%b", dlength);
              UINT16 i;
              for(i=0; i<dlength; i++) Comm_print("%b", rxPacket.data[2+i]);
            }
          }
          break;
      default: break;
    }
  }
}


COMMAND(pic, 0){
  UINT8* c = (UINT8*) &str[4];
  packet_t packet;
  UINT16 to = String_parseInt(c, &c);
  c++;
  UINT8 type = String_parseInt(c, NULL);
  packet.to = to; packet.type = PICTURE_REQ_PACKET;
  packet.header = NULL; packet.header_length=0;
  packet.data = &type; packet.data_length=1;
  Net_send(&packet, NULL);
  String_write(term_reply, "OK PICTURE_REQ sent to %i type %i", to, type);
}

void Process_init(){
  System_registerCallback(C_SERIAL, Messaging_serialHandler);
  System_registerCallback(C_RADIO, Process_radioHandler);
  Event_init();
  if(Configuration.firmwareFlags & FF_ROUTING) Routing_init(AS_GATE);
  Comm_log(LOW, "| Application %s initialized\r\n\r\n", imageData.versionName);    
}

////////////////////////////////////////////////////////////////////////////////
/// \name USB/EWS430Stick specific commands
/// \ingroup Commands
//@{

/// Download a Hex file to EEPROM.
COMMAND(dfl, SERIALONLY){ extern void fterm_init(UINT16); fterm_init(String_parseInt(&str[4], NULL)); }

/// JTAG program.
COMMAND(jta, SERIALONLY){ FlashEEPROMImage(); }

/// Do a JTAG Reset.
COMMAND(jtr, SERIALONLY){ 
    UINT16 r;
    InitTarget();
    r = GetDevice();
    ReleaseDevice(V_RESET);               // Perform Reset, release CPU from JTAG control
    ReleaseTarget();                      // Release Target Board from power
    if(r) Comm_print("OK Target resetted! Device was %x\r\n", DEVICE);
    else  Comm_print("ERROR No target connected!\r\n");
}

// Continuos reception testing, togglest red led on target continously.

UINT16 xctTarget;
const UINT8 xctData[] = "swr";

void xctTest(UINT16 data){
  packet_t p;
  p.to = xctTarget;
  p.type = MESSAGING_REQ_PACKET;
  p.header = 0; p.header_length = 0;
  p.data = (UINT8*) xctData; p.data_length = 4;
  Net_send(&p, NULL);
  Timers_add(300, xctTest, 0xFFFF);

}

COMMAND(xct, 0){
  xctTarget = String_parseInt(&str[4], NULL);
  Comm_print("Starting test to %i\r\n", xctTarget);
  xctTest(0);
}

//@}

//@}

/// \name Software header. See programming.h for description.
//@{
/// Theses variables are defined by the linker script, they are needed in the software header
extern int __image_start;
extern int __image_end;
extern UINT16 prog_reprogram();
IMAGE_DATA const imageData_t imageData = {
    (UINT16)&__image_start, (UINT16)&__image_end,

  2,            // eGate
    (UINT16)prog_reprogram,
    "eGate: V2.10", // Must be 20 chars max (with \0 21 alltogether).
    __DATE__ " " __TIME__        // Only filled when programming.o is rebuilt!
};
//@}
