#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include "usb2200.h"

int main(int argc, char **argv)
{
  int handle;
  WORD pid = USB2255_32;
  BYTE bid = 0x0;

  if (argc != 3) {
    printf("Usage: %s <channel> <value>\n", argv[0]);
    printf("  channel: decimal or hex (e.g. 5 / 0x5)\n");
    printf("  value  : 0 or 1\n");
    return 0;
  }

  if (argv[1][0] == '-' || argv[2][0] == '-') {
    printf("Error: negative value not allowed.\n");
    return 0;
  }

  BYTE channel = (BYTE)strtoul(argv[1], NULL, 0);

  BYTE value = (BYTE)strtoul(argv[2], NULL, 0);
  if (value != 0 && value != 1) {
    printf("Error: value must be 0 or 1\n");
    return 0;
  }

  // ---------- Open device ----------
  handle = USB2200_OpenDevice(pid, bid);
  if (handle < 0) {
    printf("open failed, error code %d\n", handle);
    return 0;
  }

  // ---------- Write specific channel ----------
  WORD ret = USB2200_DO_WriteChannel(handle, channel, value);
  if (ret != NO_ERR) {
    printf("Write failed, error code: %u\n", ret);
  }

  USB2200_CloseDevice(handle);
  return 0;
}

