/*
 *               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>

#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"

static USBDeviceInfo deviceList[8];
static IOSError
__getDevListTest(u8 class)
{
  u8 numDev;
  u8 i = 0;
  IOSError rv;
  rv = IUSB_GetDeviceList("/dev/usb/ehc", deviceList, 8, class, &numDev);
  if (rv < 0) {
      printf("Get device list failed: %d\n", rv);
      goto done;
  }
  for (i = 0; i < numDev; ++i) {
      printf("\tDevice %u vid = %x pid = %x\n", i, deviceList[i].vid,
              deviceList[i].pid);
  }
  rv = numDev;
done:
  return rv;
}
#define SLEEP_TIME 3 /* s */

#ifdef ENABLE_TEST
void
ehci_test(u32 arg)
#else
void
main(u32 arg)
#endif
{
    IOSFd fd0;
    IOSError rv;
    char path[64];
        
    if ((rv = __getDevListTest(0 /* any class */)) < 0) {
        printf("Failed to get list of connected devices\n", rv);
        printf("Exiting\n");
        goto done;
    }
    if (rv == 0) {
        printf("No devices connected. Exiting.\n");
        goto done;
    }
    printf("Found %u devices. Will resume and suspend device 0: \
            vid = %x pid = %x\n", rv, deviceList[0].vid, deviceList[0].pid);
    memset(path, 0, sizeof(path));
    snprintf(path, sizeof(path),"/dev/usb/ehc/%x/%x",
            deviceList[0].vid, deviceList[0].pid);
    fd0 = IOS_Open(path, 0);
    if (fd0 < 0) {
        printf("Opening device failed: %d\n", fd0);
        printf("Exiting..\n");
        goto done;
    }

    while (1) {
            printf("Suspending device for %us\n", SLEEP_TIME);
            rv = IUSB_SuspendDevice(fd0);
            if (rv < 0) {
                printf("Suspend failed: %d. exiting...\n", rv);
                goto done;
            }
            usleep(1000000*SLEEP_TIME);
            printf("Resuming device\n");
            rv = IUSB_ResumeDevice(fd0);
            if (rv < 0) {
                printf("Resume failed: %d. exiting...\n", rv);
                goto done;
            }
            usleep(1000000*SLEEP_TIME);
    }
done:
    IOS_DestroyThread(0, NULL);
    return;
}
