#include <stdio.h>
#include <unistd.h>
#include <usb.h>
#include <ftdi.h>

/*
ftdi_open_results[0] = "all fine";
ftdi_open_results[1] = "usb_find_busses() failed";
ftdi_open_results[2] = "usb_find_devices() failed";
ftdi_open_results[3] = "usb device not found";
ftdi_open_results[4] = "unable to open device";
ftdi_open_results[5] = "unable to claim device";
ftdi_open_results[6] = "reset failed";
ftdi_open_results[7] = "set baudrate failed";
*/

int main(int argc, char **argv)
{
  struct ftdi_context ftdic;
  int f,i;

  ftdi_init(&ftdic);

  f = ftdi_usb_open(&ftdic, 0x0403, 0x6001); 

  if(f < 0 && f != -5) {
    fprintf(stderr, "unable to open ftdi device: %d\n",f);
    exit(-1);
  }

  printf("ftdi open succeeded: %d\n",f);

  printf("enabling bitbang mode\n");
  ftdi_enable_bitbang(&ftdic, 0xFF);

  char buf[1];

  sleep(3);

  buf[0] = 0x0;
  printf("turning everything on\n");
  f = ftdi_write_data(&ftdic, buf, 1);
  if(f < 0) {
    fprintf(stderr,"write failed for 0x%x, error %d\n",buf[0],f);
  }

  sleep(3);

  buf[0] = 0xFF;
  printf("turning everything off\n");
  f = ftdi_write_data(&ftdic, buf, 1);
  if(f < 0) {
    fprintf(stderr,"write failed for 0x%x, error %d\n",buf[0],f);
  }

  sleep(3);

  for(i = 0; i < 32; i++) {
    buf[0] =  0 | (0xFF ^ 1 << (i % 8));
    if( i > 0 && (i % 8) == 0) {
      printf("\n");
    }
    printf("%02hhx ",buf[0]);
    fflush(stdout);
    f = ftdi_write_data(&ftdic, buf, 1);
    if(f < 0) {
      fprintf(stderr,"write failed for 0x%x, error %d\n",buf[0],f);
    }
    sleep(1);
  }

  printf("\n");
  
  printf("disabling bitbang mode\n");
  ftdi_disable_bitbang(&ftdic);

  ftdi_usb_close(&ftdic);
  ftdi_deinit(&ftdic);
}
