/* 
 * There are 2 threads:
 *         - reader thread, running rd_func()
 *         - main thread, running wr_func()
 * wr_func() writes commands to bluetooth device 
 *    VendorId = 0x0a5c
 *    DeviceId = 0x2101
 *    [BroadCom bluetooth dongle that we received. ]
 * rd_func() reads and prints data from the dongle.
 * Message queues are used to synchronize the threads.
 */
/* Test based on BroadCom sample */
#include <iostypes.h>
#include <ios.h>
#include <ioslibc.h>
#include <iop.h>
#include "iosusbtypes.h"
#include "iosusb.h"

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

#define RESET_OFFSET  32
u8 *intr_data = (u8 *) 0x12000fe0;
u8 *scan_buf  = (u8 *) 0x12001020;
u8 *reset_buf = (u8 *) 0x12001060;
u8 *str_buf = (u8 *) 0x120010a0;

IOSFd fd0 = -1;

/* Stuff for synchronization */
#define MSGQ_SIZE 8

IOSMessage rd_msgQ[MSGQ_SIZE];
IOSMessage wr_msgQ[MSGQ_SIZE];
IOSMessageQueueId rd_qid = -1;
IOSMessageQueueId wr_qid = -1;

#define UINT8 u8
#define UINT16 u16

/********************************************************************************
** Macros to get and put bytes to and from a stream (Little Endian format).
*/
#define UINT32_TO_STREAM(p, i) {*(p)++ = (UINT8)(i); *(p)++ = (UINT8)((i) >> 8); *(p)++ = (UINT8)((i) >> 16); *(p)++ = (UINT8)((i) >> 24);}
#define UINT24_TO_STREAM(p, i) {*(p)++ = (UINT8)(i); *(p)++ = (UINT8)((i) >> 8); *(p)++ = (UINT8)((i) >> 16);}
#define UINT16_TO_STREAM(p, i) {*(p)++ = (UINT8)(i); *(p)++ = (UINT8)((i) >> 8);}
#define UINT8_TO_STREAM(p, i)   {*(p)++ = (UINT8)(i);}
#define INT8_TO_STREAM(p, i)    {*(p)++ = (INT8)(i);}
#define ARRAY16_TO_STREAM(p, a)  {register int ijk; for (ijk = 0; ijk < 16;           ijk++) *(p)++ = (UINT8) a[15 - ijk];}
#define ARRAY8_TO_STREAM(p, a)   {register int ijk; for (ijk = 0; ijk < 8;            ijk++) *(p)++ = (UINT8) a[7 - ijk];}
#define BDADDR_TO_STREAM(p, a)   {register int ijk; for (ijk = 0; ijk < BD_ADDR_LEN;  ijk++) *(p)++ = (UINT8) a[BD_ADDR_LEN - 1 - ijk];}
#define LAP_TO_STREAM(p, a)      {register int ijk; for (ijk = 0; ijk < LAP_LEN;      ijk++) *(p)++ = (UINT8) a[LAP_LEN - 1 - ijk];}
#define DEVCLASS_TO_STREAM(p, a) {register int ijk; for (ijk = 0; ijk < DEV_CLASS_LEN;ijk++) *(p)++ = (UINT8) a[DEV_CLASS_LEN - 1 - ijk];}
#define ARRAY_TO_STREAM(p, a, len) {register int ijk; for (ijk = 0; ijk < len;        ijk++) *(p)++ = (UINT8) a[ijk];}

#define STREAM_TO_UINT8(i, p)   {i = (UINT8)(*(p)); (p) += 1;}
#define STREAM_TO_UINT16(i, p) {i = ((UINT16)(*(p)) + (((UINT16)(*((p) + 1))) << 8)); (p) += 2;}
#define STREAM_TO_UINT32(i, p) {i = (((UINT32)(*(p))) + ((((UINT32)(*((p) + 1)))) << 8) + ((((UINT32)(*((p) + 2)))) << 16) + ((((UINT32)(*((p) + 3)))) << 24)); (p) += 4;}
#define STREAM_TO_BDADDR(a, p)   {register int ijk; register UINT8 *pbda = (UINT8 *)a + BD_ADDR_LEN - 1; for (ijk = 0; ijk < BD_ADDR_LEN; ijk++) *pbda-- = *p++;}
#define STREAM_TO_ARRAY16(a, p)  {register int ijk; register UINT8 *_pa = (UINT8 *)a + 15; for (ijk = 0; ijk < 16; ijk++) *_pa-- = *p++;}
#define STREAM_TO_ARRAY8(a, p)   {register int ijk; register UINT8 *_pa = (UINT8 *)a + 7; for (ijk = 0; ijk < 8; ijk++) *_pa-- = *p++;}
#define STREAM_TO_DEVCLASS(a, p) {register int ijk; register UINT8 *_pa = (UINT8 *)a + DEV_CLASS_LEN - 1; for (ijk = 0; ijk < DEV_CLASS_LEN; ijk++) *_pa-- = *p++;}
#define STREAM_TO_LAP(a, p)      {register int ijk; register UINT8 *plap = (UINT8 *)a + LAP_LEN - 1; for (ijk = 0; ijk < LAP_LEN; ijk++) *plap-- = *p++;}
#define STREAM_TO_ARRAY(p, a, len) {register int ijk; for (ijk = 0; ijk < len; ijk++) ((UINT8 *) a)[ijk] = *p++;}
#define REVERSE_STREAM_TO_ARRAY(a, p, len) {register int ijk; register UINT8 *_pa = (UINT8 *)a + len - 1; for (ijk = 0; ijk < len; ijk++) *_pa-- = *p++;}

#define INTR_READ_EP            0x81
#define HCI_CMD_COMPLETE_LEN	4
typedef struct
{
    u8 res;
    u8 len;
    u8 pkts;
    UINT16 code;
    u8 status;
    char data[200];
}tHciResPkt;

tHciResPkt  hci_res;

static void
read_intr(u32 id, u8 ep)
{
    char *pbuf, *pdata, buf[20] = "\0";
    int i;
    int siz = IUSB_ReadIntrMsg(id, ep, 20, buf);
    if(buf[0] != 0x0e) {
        printf("buf[0] ! = 0x0e. Read unsuccessful\n");
        return;
    }
    printf("read_intr: read successful: read %d bytes\n", siz);
    pbuf = buf;
    STREAM_TO_UINT8(hci_res.res, pbuf);
    STREAM_TO_UINT8(hci_res.len, pbuf);
    STREAM_TO_UINT8(hci_res.pkts, pbuf);
    STREAM_TO_UINT16(hci_res.code, pbuf);
    STREAM_TO_UINT8(hci_res.status, pbuf);

    pdata = hci_res.data;

    if(hci_res.len > HCI_CMD_COMPLETE_LEN)
        REVERSE_STREAM_TO_ARRAY(pdata, pbuf, hci_res.len - 4);

    printf("Hex Code: 0x%02x  ", hci_res.res);
    printf("Length  : 0x%02x\n", hci_res.len);
    printf(" HCI Cmd Packets: 0x%02x\n", hci_res.pkts);
    printf(" CMD Code       : %04x\n", hci_res.code);
    printf(" Status         : 0x%02x\n", hci_res.status);
    if ( hci_res.len > HCI_CMD_COMPLETE_LEN ) {
        printf("Data : ");
        for (i = 0; i < hci_res.len - 4; ++i) {
           printf("%02x ", hci_res.data[i]);
        }
    }
    printf("\n");
}

static void
wait_for_rdr()
{
  IOSMessage m;
  IOSError err;
  printf("wr_func: Tell rd thread to read\n");
  err = IOS_SendMessage(rd_qid, 0xbabecafe, IOS_MESSAGE_BLOCK);
  printf("wr_func: waiting for rd thread to finish ...\n");
  IOS_ReceiveMessage(wr_qid, &m, IOS_MESSAGE_BLOCK);
}

void
HCI_reset(IOSFd fd0)
{
    int ret = 0;
    /* HCI reset command */
    reset_buf[RESET_OFFSET + 0] = 0x0c;
    reset_buf[RESET_OFFSET + 1] = 0x03;
    reset_buf[RESET_OFFSET + 2] = 0;
    printf("HCI_reset: calling IUSB_WriteCtrlMsg(Reset command)\n");
    printf("HCI_reset: write buf = %p\n", reset_buf);
    if ( (ret = IUSB_WriteCtrlMsg(fd0, 0x20, 0, 0, 0, 3, reset_buf + RESET_OFFSET)) < 0)
        printf("wr_func: IUSB_WriteCtrlMsg failed:%d\n", ret);
    else
        printf("wr_func: IUSB_WriteCtrlMsg succeeded: wrote %d bytes\n", ret);
}
void 
HCI_read_bdaddr(IOSFd fd0)
{
    int ret = 0;
    u8 buf[4];
    buf[0] = 0x10;
    buf[1] = 0x09;
    printf("Read BDADDR command\n");
    if ( (ret = IUSB_ReadCtrlMsg(fd0, 0x20, 0, 0, 0, 2, buf)) <0 )
        printf("read_bdaddr: IUSB_ReadCtrlMsg failed: %d\n", ret);
    else 
        printf("read_bdaddr: IUSB_ReadCtrlMsg succeeded: wrote %d bytes\n", ret);
}
void 
HCI_read_localversion(IOSFd fd)
{
    int ret = 0;
    u8 buf[4];
    buf[0] = 0x10;
    buf[1] = 0x01;
    printf("Read version info command\n");
    if ( (ret = IUSB_ReadCtrlMsg(fd0, 0x20, 0, 0, 0, 2, buf)) <0 )
        printf("read_bdaddr: IUSB_ReadCtrlMsg failed: %d\n", ret);
    else 
        printf("read_bdaddr: IUSB_ReadCtrlMsg succeeded: wrote %d bytes\n", ret);
}
void
HCI_scan_enable(IOSFd fd0)
{
    int ret = 0;
    scan_buf[0] = 0x0c;
    scan_buf[1] = 0x1a;
    scan_buf[2] = 0x01;
    printf("HCI_scan_enable:calling IUSB_WriteCtrlMsg(Scan enable command)\n");
    printf("HCI_scan_enable: write buf = %p\n", scan_buf);
    if ((ret = IUSB_WriteCtrlMsg(fd0, 0x20, 0, 0, 0, 3, scan_buf)) < 0 )
        printf("wr_func: IUSB_WriteCtrlMsg failed: %d\n", ret);
    else
        printf("wr_func: IUSB_WriteCtrlMsg succeeded: wrote %d bytes\n", ret);
}
static void 
wr_func()
{

    HCI_reset(fd0);
    HCI_scan_enable(fd0);
    while (1) {
        HCI_read_bdaddr(fd0);
        wait_for_rdr();
        HCI_read_localversion(fd0);
        wait_for_rdr();
    }
    printf("write test exits\n");
}

static void
rd_func(u32 x)
{
    IOSMessage msg;
    IOSError err;
    while (1) {
        read_intr(fd0, INTR_READ_EP);
        printf("rd_func: Inform wr thread that message is read\n");
        err = IOS_SendMessage(wr_qid, 0xcafebabe, IOS_MESSAGE_BLOCK);
        printf("rd_func: wait for wr thread to finish processing...\n");
        IOS_ReceiveMessage(rd_qid, &msg, IOS_MESSAGE_BLOCK);
        printf("rd_func: got woken up by wr thread ...\n");
    }
}

u8 progStack[STACK_SIZE];
void 
create_rd()
{
    u32 id = IOS_CreateThread(rd_func, 0, progStack + STACK_SIZE, STACK_SIZE, IOS_GetThreadPriority(0), IOS_THREAD_CREATE_DETACHED);
    IOS_StartThread(id);
}

static void
__ctrlTransferTests(IOSFd fd)
{
    u8 buf[64];
    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);
}

#ifdef ENABLE_TEST
void
ohci_test(u32 arg)
#else
void
main(u32 arg)
#endif
{
    do {
#if OH0 
        fd0 = IOS_Open("/dev/usb/oh0/0a5c/2045", 0); 
#elif OH1
        fd0 = IOS_Open("/dev/usb/oh1/0a5c/2045", 0); 
        if (fd0 < 0)
            fd0 = IOS_Open("/dev/usb/oh1/057e/0305", 0); 
#endif
    }
    while (fd0 < 0);
    
    __ctrlTransferTests(fd0);
    
    /* Create message queues for synchronization */
    rd_qid = IOS_CreateMessageQueue(rd_msgQ, MSGQ_SIZE);
    printf("rd msg queue %d created...\n", rd_qid);
    wr_qid = IOS_CreateMessageQueue(wr_msgQ, MSGQ_SIZE);
    printf("wr msg queue %d created...\n", wr_qid);

    IUSB_SuspendDevice(fd0);
    usleep(5000000);
    IUSB_ResumeDevice(fd0);

    create_rd(); /* Create a new thread for reader */
    wr_func();
    /* Clean up */
    IOS_DestroyMessageQueue(rd_qid);
    IOS_DestroyMessageQueue(wr_qid);
    IOS_DestroyThread(0, NULL);
}
