#include "parallel.h"

#include <string>
#include <math.h>

const char *Parallel::devstr = "/dev/parport0";
const unsigned int Parallel::numPins = 8;\

Parallel::Parallel(){
  int failure = 0;
  fd = open(devstr, O_WRONLY, 0);
  
  if (fd != -1){
    // claim the port
    failure = ioctl(fd, PPCLAIM);
    
    // close if failed
    if (failure){
      throw ParallelException("Failed to claim parallel port.");
    }
  }
  else{
    throw ParallelException("Failed to open parallel port device " + string(devstr));
  }
}

Parallel::~Parallel(){
  // release the port
  ioctl(fd, PPRELEASE);
  
  // close the port
  close(fd);
}

void Parallel::setState(int state){
  struct ppdev_frob_struct frob;
  unsigned char data;

  int failure = 0;

  // standard mask
  frob.mask = PARPORT_CONTROL_STROBE;

  // check what state to set
  if (state == 0){
    // turn it off
    frob.val = 0;
    data = 0;
  }
  else
  {
    // turn it on
    frob.val = PARPORT_CONTROL_STROBE;
    data = 0xFF;
  }

  // talk to the port
  failure = ioctl(fd, PPWDATA, &data);
  if (!failure){
    failure = ioctl(fd, PPFCONTROL, &frob);
  }

  if (failure){
    throw ParallelException("Failed to set pin state in ioctl.");
  }  
}
  
unsigned char Parallel::binaryStringToNum(unsigned char *str){
  if (strlen((const char *)str)!=numPins){
    throw ParallelException("Invalid signal string.");
  }

  unsigned char numVal = 0;
  for (unsigned int i=0; i<numPins; i++){
    char thisone;
    // get the ith bit, starting from the least sig.
    strncpy(&thisone, (const char *)(&str[numPins - i - 1]), 1);
    // multiply 
    numVal += static_cast<int>(atoi(&thisone)*pow(2, i));
  }
  return numVal;
}

void Parallel::setSignal(unsigned char *signal){
  struct ppdev_frob_struct frob;
  unsigned char data = binaryStringToNum(signal);

  int failure = 0;

  // standard mask
  frob.mask = PARPORT_CONTROL_STROBE;

  // turn it on
  frob.val = PARPORT_CONTROL_STROBE;

  // talk to the port
  failure = ioctl(fd, PPWDATA, &data);
  if (!failure){
    failure = ioctl(fd, PPFCONTROL, &frob);
  }

  if (failure){
    throw ParallelException("Failed to set pin state in ioctl.");
  }  
}
  
