

/*
 *              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 "stdafx.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#ifdef WIN32
#include <winsock2.h>

#else /* !WIN32 */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <sys/time.h>
#endif /* !WIN32 */

#include "utils.h"

static unsigned char usbRdBuf[USB_BUF_SIZE + 16];
static unsigned char usbWrBuf[USB_BUF_SIZE + 16];


/* * * * * * * * * * * * * * * * * * * * * * * * *
    Function: hostSend 
   
    Description:
        Host(PC) send data to NCproxy
 * * * * * * * * * * * * * * * * * * * * * * * * */

int
hostSend(int fd, void *p, int len)
{
    int wr=0, nwrite, n;
    
    n = len + 4;
    usbWrBuf[0] = 0x41;
    usbWrBuf[1] = 0x67;
    usbWrBuf[2] = (len >> 8) & 0xff;
    usbWrBuf[3] = len & 0xff;
    memcpy(usbWrBuf+4, p, len);

    while(wr < n) {
        nwrite = send(fd,(char*)(usbWrBuf+wr), n-wr, 0);
        if (nwrite < 0)  {
            printf("ERROR: socket send failed errno=%d\n", errno);
            return -1;
        }
        wr += nwrite;
    } 
    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * *
    Function: hostRecv
   
    Description:
        Host(PC) receive data from NCproxy
 * * * * * * * * * * * * * * * * * * * * * * * * */
int 
hostRecv(int fd, void *p, int len)
{
    int rd=0, nread, n;
    
    n =  len + 4;
    while(rd < n) {
        nread = recv(fd, (char*)(usbRdBuf+rd), n-rd, 0);
        if (nread < 0) {
            if (errno == EINTR) nread = 0;
            else {
                printf("ERROR: socket recv failed errno=%d\n", errno);
                return -1;
            }
        }
        rd += nread;
        if (rd >= 4) n = ((usbRdBuf[2] << 8) | usbRdBuf[3]) + 4;
    }
    
    memcpy(p, usbRdBuf+4, n-4);

    return n-4;
}
