#include <stdio.h>
#include "xc.h"
#include "math.h"
#include "BK_LoadDumpControl.h"
#include "UART.h"
#include "config.h"

#define PACKET_LENGTH 26
char LoadCmdPckt[PACKET_LENGTH];

void CalcChecksum(char *packet)
{
    int i;
    packet[PACKET_LENGTH-1] = 0x00;
    for(i=0;i<PACKET_LENGTH-1;i++)
        packet[PACKET_LENGTH-1] += packet[i];
    //packet[PACKET_LENGTH-1] %= 256;
    return;
}


int GetResponse()
{
  int i;
  for(i=0;i<PACKET_LENGTH-1;i++)
    {
    LoadCmdPckt[i] = getU1();
    }
  if(LoadCmdPckt[3] == 0x80)
      return 1;  //Command Succesful
  else
      return 0;
}

void EnableRemote(int on)
{
    int i;
  LoadCmdPckt[0] = 0xaa;
  LoadCmdPckt[1] = 0x00;
  LoadCmdPckt[2] = 0x20;
  if(on)
    LoadCmdPckt[3] = 0x01;
  else
    LoadCmdPckt[3] = 0x00;
  for(i=4;i<PACKET_LENGTH-1;i++)
      LoadCmdPckt[i] = 0x00;
  CalcChecksum(LoadCmdPckt);

  for(i=0;i<PACKET_LENGTH;i++)
     putU1(LoadCmdPckt[i]);

  return;
}

void LoadOn(int on)
{
    int i;
  LoadCmdPckt[0] = 0xaa;
  LoadCmdPckt[1] = 0x00;
  LoadCmdPckt[2] = 0x21;
  if(on)
    LoadCmdPckt[3] = 0x01;
  else
    LoadCmdPckt[3] = 0x00;
  for(i=4;i<PACKET_LENGTH-1;i++)
      LoadCmdPckt[i] = 0x00;
  CalcChecksum(LoadCmdPckt);

  for(i=0;i<PACKET_LENGTH;i++)
     putU1(LoadCmdPckt[i]);

  return;
}

void SetCCMode()
{
    int i;
  LoadCmdPckt[0] = 0xaa;
  LoadCmdPckt[1] = 0x00;
  LoadCmdPckt[2] = 0x28;
  LoadCmdPckt[3] = 0x00;
  for(i=4;i<PACKET_LENGTH-1;i++)
      LoadCmdPckt[i] = 0x00;
  CalcChecksum(LoadCmdPckt);

  for(i=0;i<PACKET_LENGTH;i++)
     putU1(LoadCmdPckt[i]);

  return;
}

//Sets current request value.  Argument is amps.
void SetCurrent(float current)
{
    int i;
    char *char_ptr;
    unsigned long fp_current;

  fp_current = (unsigned long) 10000*current;  //Convert from Amps to .1mA units

  char_ptr = (char *) &fp_current;

  LoadCmdPckt[0] = 0xaa;
  LoadCmdPckt[1] = 0x00;
  LoadCmdPckt[2] = 0x2a;

  LoadCmdPckt[3] = char_ptr[0];
  LoadCmdPckt[4] = char_ptr[1];
  LoadCmdPckt[5] = char_ptr[2];
  LoadCmdPckt[6] = char_ptr[3];

  for(i=7;i<PACKET_LENGTH-1;i++)
      LoadCmdPckt[i] = 0x00;
  CalcChecksum(LoadCmdPckt);

  for(i=0;i<PACKET_LENGTH;i++)
      putU1(LoadCmdPckt[i]);

  return;
}

//Sets maximumb allowable current request.  Argument is amps.

void SetMaxCurrent(float current)
{
   int i;
   char *char_ptr;
   unsigned long fp_current;

  fp_current = (unsigned long) 10000*current;  //Convert from Amps to .1mA units

  char_ptr = (char *) &fp_current;

  LoadCmdPckt[0] = 0xaa;
  LoadCmdPckt[1] = 0x00;
  LoadCmdPckt[2] = 0x24;

  LoadCmdPckt[3] = char_ptr[0];
  LoadCmdPckt[4] = char_ptr[1];
  LoadCmdPckt[5] = char_ptr[2];
  LoadCmdPckt[6] = char_ptr[3];

  for(i=7;i<PACKET_LENGTH-1;i++)
      LoadCmdPckt[i] = 0x00;
  CalcChecksum(LoadCmdPckt);

  for(i=0;i<PACKET_LENGTH;i++)
     putU1(LoadCmdPckt[i]);

  return;
}
