/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */
#include <iostypes.h>
#include <ios.h>
#include <iop.h>
#include <ioslibc.h>

#define USB_STD_LANG_EN_US 0x0409

#ifndef ENABLE_TEST
#define STACK_SIZE 2048
const u8        _initStack[STACK_SIZE];
const u32       _initStackSize = sizeof(_initStack);
const u32       _initPriority = 20;
#endif /* ENABLE_TEST */

#include "iosusbtypes.h"
#include "iosusb.h"

USBDeviceInfo deviceList[64];
u8 numDevices = 0;

static void
__ctrlTransferTests(IOSFd fd)
{
    u8 buf[IOS_USB_STR_MAX];
    struct USB_DevDescr d;
    IUSB_GetDevDescr(fd, &d); 

    printf("--- Ctrl transfer tests \n");

    if ( (d.iManufacturer != 0 )
            && (0 < IUSB_GetAsciiStr(fd, 0, d.iManufacturer, 
                    USB_LANG_EN_US, buf, sizeof(buf))))
        printf("Manufacturer: %s\n", buf);
    if ( (d.iProduct != 0)
            && (0 < IUSB_GetAsciiStr(fd, 0, d.iProduct, 
                    USB_LANG_EN_US, buf, sizeof(buf))) ) 
        printf("Product: %s\n", buf);

    if ( (d.iSerialNumber != 0)
            && (0 < IUSB_GetAsciiStr(fd, 0, d.iSerialNumber, 
                    USB_LANG_EN_US, buf, sizeof(buf))) ) 
        printf("Serial number: %s\n", buf);
}

static IOSError 
__getDeviceList(void)
{
    IOSError rv = IUSB_GetDeviceList("/dev/usb/ehc", deviceList, 
            sizeof(deviceList)/sizeof(USBDeviceInfo), 0, &numDevices);
    if (rv < 0) {
        printf("Get device list failed: %d\n", rv);
        goto done;
    }
    if (0 == numDevices) {
      printf("No devices connected\n");
      goto done;
  }
  { 
      u32 i;
      printf("Detected %d devices\n", numDevices);
      for (i = 0; i < numDevices; ++i) {
          printf("\tdevice %u vid = %x pid = %x\n", i, deviceList[i].vid,
                  deviceList[i].pid);
      }
  }
done:
  return rv;
}

#ifdef ENABLE_TEST
void
ehci_test(u32 arg)
#else
void
main(u32 arg)
#endif
{
    u32 i;
    IOSFd fd;
    char path[64];

    while (1) {
        usleep(100000); /* Wait for all devices to be enumerated */
        __getDeviceList();
        for (i = 0; i < numDevices; ++i) {
            memset(path, 0, sizeof(path));
            snprintf(path, sizeof(path),"/dev/usb/ehc/%x/%x",
                    deviceList[i].vid, deviceList[i].pid);
            printf("Attempting to open device: %s\n", path);
            fd = IOS_Open(path, 0);
            if (fd < 0) {
                printf("Failed to open %s: %d\n", path, fd);
                continue;
            
            }
            __ctrlTransferTests(fd);
            IOS_Close(fd);
        }
    }
    return;
}
