#include "Arduino.h"
#include "mrf24j40.h"
#include "protocol.h"
#include "extra-protocol.h"

#include <SPI/SPI.h>
#include "assert.h"

#define VERSION "v0.3"

#define PANID 0x0001
#define SADDR 0x0002
#define DADDR 0x0001
const unsigned char MAC_ADDR[8]= {1, 2, 3, 4, 5, 6, 7, 8};
#define DEFAULT_CHANNEL 26

#define PIN_SS 10
#define PIN_LED 13

void frame_cb(unsigned char *frame, unsigned int size)
{
  /* The frames have to be 125 bytes at most since we still
     have to include the CRC. */
  if(size > 125)
    cli_error();
  mrf24j40_tx_frame(frame, size);
  send_control(PROT_CTYPE_OK, NULL, 0);
  delay(100);
  send_control(PROT_CTYPE_ACK, NULL, 0);
}

void control_cb(enum prot_ctype type, unsigned char *data, unsigned int size)
{
  unsigned short channel;
  switch(type) {
  case(PROT_CTYPE_CONFIG_CHANNEL):
    if(size != 2)
      cli_error();
    channel = *((unsigned short *)data);

    /* reconfigure the transceiver */
    mrf24j40_init(NULL, PANID, SADDR, MAC_ADDR, channel, 0);

    break;
  default:
    cli_error();
  }
}

void send(const unsigned char *data, unsigned int size)
{
  Serial.write(data, size);
}

void setup(void)
{
  /* setup UART */
  Serial.begin(115200);

  /* setup SPI */
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.setBitOrder(MSBFIRST);
  pinMode(PIN_SS, OUTPUT);
  SPI.begin();

  /* setup MRF24J40 */
  mrf24j40_init(NULL, PANID, SADDR, MAC_ADDR, DEFAULT_CHANNEL, 0);

  protocol_init(frame_cb,
                control_cb,
                send);

  send_info("Injector Firmware " VERSION "\n");
}

void serialEvent()
{
  input_step((unsigned char)Serial.read());
}

void loop()
{
  /* doing nothing */
}
