⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usb_diag_lib.c

📁 VC下USB的驱动代码,及其相关操作检测。
💻 C
📖 第 1 页 / 共 2 页
字号:
////////////////////////////////////////////////////////////////
// File - USB_DIAG_LIB.C
//
// Utility functions for communication with USB devices 
// using WinDriver's API.
// 
// Copyright (c) 2003 - 2004 Jungo Ltd.  http://www.jungo.com
// 
////////////////////////////////////////////////////////////////

// use in wizard's device-specific generated code
#include "c:\windriver/include/wdu_lib.h"
#include "c:\windriver/include/status_strings.h"
#include "c:\windriver/include/utils.h"
#include "c:\windriver/samples/shared/usb_diag_lib.h"

#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <string.h>

#ifdef _USE_SPECIFIC_KERNEL_DRIVER_
    #undef WD_Open
    #define WD_Open WD_OpenKernelHandle
    #if defined(UNIX)
        #undef WD_FUNCTION
        #define WD_FUNCTION(wFuncNum,h,pParam,dwSize,fWait) ((ULONG) ioctl((int)(h), wFuncNum, pParam))
    #endif
#endif
#include "usb_diag_lib.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#if !defined(ERR)
#define ERR printf
#endif

#define TRANSFER_TIMEOUT 30000 // in msecs


static FILE * log_file = NULL;
static HANDLE _g_hDevice;

typedef struct  
{
    DWORD dwListenPipeNum;
    DWORD dwWritePipeNum;
    HANDLE hDevice;
    DWORD dwPacketSize;
    PVOID pContext;
    BOOL fStopped;
    HANDLE hThread;
    DWORD dwError;
} USB_LISTEN_PIPE;

static USB_LISTEN_PIPE ListenPipe;

// Function: CloseListening()
//   Stop listening to USB device pipe
void CloseListening(USB_LISTEN_PIPE *pListenPipe);

// Function: ListenToPipe()
//   Start listening to a USB device pipe
void ListenToPipe(USB_LISTEN_PIPE *pListenPipe);

// Function: pipeType2Str()
//   Returns a string identifying the pipe type
// Parameters:
//   pipeType [in] pipe type
// Return Value:
//   String containing the description of the pipe
char *pipeType2Str(ULONG pipeType)
{
    char *res = "unknown";
    switch (pipeType)
    {
        case PIPE_TYPE_CONTROL: 
            res = "Control";
            break;
        case PIPE_TYPE_ISOCHRONOUS:
            res = "Isochronous";
            break;          
        case PIPE_TYPE_BULK:
            res = "Bulk";
            break;
        case PIPE_TYPE_INTERRUPT:
            res = "Interrupt";
            break;
    }
    return res;
}

void PrintTime(unsigned char * str)
{
    char datetime_buf[10];
    struct _timeb tstruct;
    
    /* Display operating system-style date and time. */
    _strtime( datetime_buf);
    printf( "\n %s %s", str, datetime_buf );

    _ftime( &tstruct );
    printf(  ".%3.3u", tstruct.millitm );

    _strdate( datetime_buf);
    printf( " Date: %s \n", datetime_buf );

}

void LogTime(unsigned char * str)
{
    char datetime_buf[10];
    struct _timeb tstruct;
    
    /* Display operating system-style date and time. */
    _strtime( datetime_buf);
    fprintf(log_file, "\n %s %s", str, datetime_buf );

    _ftime( &tstruct );
    fprintf(log_file, ".%3.3u", tstruct.millitm );

    _strdate( datetime_buf);
    fprintf(log_file, " Date: %s \n", datetime_buf );
    
}


/* frame received
*/
unsigned long  recv_frame_buf[16];
#define recv_frame_len recv_frame_buf[15]

unsigned long  send_frame_buf[16];
#define send_frame_len send_frame_buf[15]


// input of command from user
static char line[256];

#define BYTES_IN_LINE 16
#define HEX_CHARS_PER_BYTE 3
#define HEX_STOP_POS BYTES_IN_LINE*HEX_CHARS_PER_BYTE

// Function: PrintHexBuffer()
//   Print a buffer in HEX format
// Parameters:
//   pBuffer [in] pointer to buffer
//   dwBytes [in] number of bytes to print
// Return Value:
//   None
void PrintHexBuffer(PVOID pBuffer, DWORD dwBytes)
{
    PBYTE pData = (PBYTE) pBuffer;
    CHAR pHex[HEX_STOP_POS+1];
    CHAR pAscii[BYTES_IN_LINE+1];
    DWORD offset;
    DWORD i;
    
    if (!dwBytes)
    {
        printf("\nNULL\n");
        return;
    }
    for (offset=0; offset<dwBytes; offset++)
    {
        DWORD line_offset = offset%BYTES_IN_LINE;
        if (offset && !line_offset)
        {
            pAscii[line_offset] = '\0';
            printf("%s | %s\n", pHex, pAscii);
        }
        sprintf(pHex+line_offset*HEX_CHARS_PER_BYTE, "%02X ", (UINT)pData[offset]);
        pAscii[line_offset] = (CHAR)((pData[offset]>=0x20) ? pData[offset] : '.');
    }

    // print the last line. fill with blanks if needed
    if (offset%BYTES_IN_LINE)
    {
        for (i=(offset%BYTES_IN_LINE)*HEX_CHARS_PER_BYTE; i<BYTES_IN_LINE*HEX_CHARS_PER_BYTE; i++)
            pHex[i] = ' ';
        pHex[i] = '\0';
    }
    pAscii[offset%BYTES_IN_LINE]='\0';
    printf("%s | %s\n", pHex, pAscii);
}

// Function: CloseListening()
//   Stop listening to USB device pipe
// Parameters:
//   pListenPipe [in] pointer to USB device pipe
// Return Value:
//   None
void CloseListening(USB_LISTEN_PIPE* pListenPipe)
{
    if (!pListenPipe->hThread)
        return;

    printf("Stop listening to pipe\n");
    pListenPipe->fStopped = TRUE;

    WDU_HaltTransfer(pListenPipe->hDevice, pListenPipe->dwListenPipeNum);

    ThreadWait(pListenPipe->hThread);
    pListenPipe->hThread = NULL;
}


void OpenLogFile(const char * fname)
{
    char datetime_buf[10];
    
    if(log_file == NULL)
    {
        log_file = fopen( fname, "a");

        if(log_file == NULL)
        {
            printf("Open log file fail\n");
        }
        else
        {
            _strdate( datetime_buf);
            fprintf(log_file,  "-------------- Date: %s ", datetime_buf );

            _strtime( datetime_buf);
            fprintf(log_file,  "Time: %s -------------\n", datetime_buf );
        }
    }
}

void CloseLogFile(void)
{
    if(log_file != NULL)
    {
        fclose(log_file);    
        log_file = NULL;
    }
}

// Function: PrintHexBuffer()
//   Print a buffer in HEX format
// Parameters:
//   pBuffer [in] pointer to buffer
//   dwBytes [in] number of bytes to print
// Return Value:
//   None
void LogHexBuffer(PVOID pBuffer, DWORD dwBytes)
{
    PBYTE pData = (PBYTE) pBuffer;
    CHAR pHex[HEX_STOP_POS+1];
    CHAR pAscii[BYTES_IN_LINE+1];
    DWORD offset;
    DWORD i;
    
    if (!dwBytes)
    {
        fprintf(log_file, "\nNULL\n");
        return;
    }
    for (offset=0; offset<dwBytes; offset++)
    {
        DWORD line_offset = offset%BYTES_IN_LINE;
        if (offset && !line_offset)
        {
            pAscii[line_offset] = '\0';
            fprintf(log_file, "%s | %s\n", pHex, pAscii);
        }
        sprintf(pHex+line_offset*HEX_CHARS_PER_BYTE, "%02X ", (UINT)pData[offset]);
        pAscii[line_offset] = (CHAR)((pData[offset]>=0x20) ? pData[offset] : '.');
    }

    // print the last line. fill with blanks if needed
    if (offset%BYTES_IN_LINE)
    {
        for (i=(offset%BYTES_IN_LINE)*HEX_CHARS_PER_BYTE; i<BYTES_IN_LINE*HEX_CHARS_PER_BYTE; i++)
            pHex[i] = ' ';
        pHex[i] = '\0';
    }
    pAscii[offset%BYTES_IN_LINE]='\0';
    fprintf(log_file, "%s | %s\n", pHex, pAscii);
    
}


void SetDeviceHandler(HANDLE hDevice)
{
    _g_hDevice = hDevice;
}

HANDLE GetDeviceHandler(void)
{
    return _g_hDevice;
}

int USB_Diag_LibInit(const char * flog, HANDLE hDevice)
{
    OpenLogFile(flog);

    SetDeviceHandler(hDevice);

    return 0;
}

int USB_Diag_LibUninit(void)
{
    CloseLogFile();
    return 0;
}

int PipeSend(void * pParam)
{
    DWORD dwError;
    DWORD dwBytesTransferred = 0;
    BYTE  SetupPacket[8];

    DWORD frame_finished = 1;
    DWORD totalTransferred = 0;

    char * send_ptr = ((unsigned char *)&send_frame_buf[0]);

    USB_LISTEN_PIPE *pListenPipe = (USB_LISTEN_PIPE*) pParam;

    while(send_frame_len)
    {

        dwError = WDU_Transfer(_g_hDevice, pListenPipe->dwWritePipeNum, 0, 0, 
            send_ptr, (send_frame_len>16) ? 16 : send_frame_len, &dwBytesTransferred, SetupPacket, TRANSFER_TIMEOUT);

        if(dwBytesTransferred <= 16)
        {
            send_frame_len -= dwBytesTransferred;
        }
        else
        {
            //impossible
            send_frame_len = 0;
        }

        if(frame_finished)
        {
            frame_finished = 0;

            /* Display operating system-style date and time. */
            LogTime("TX Time:");
        }
        
        if(dwError)
        {
            //
            if(log_file) 
            {
                fprintf(log_file, "PipeSend error code %X\n", dwError);
            }
            printf("PipeSend error code %X\n", dwError);

            break;
        }
        else
        {
            LogHexBuffer(send_ptr, dwBytesTransferred);
        }

        send_ptr += dwBytesTransferred;

        totalTransferred += dwBytesTransferred;

        if(dwBytesTransferred != 16)
        {
            frame_finished = 1;
        }
        
    }
    
    return totalTransferred;
    
}

extern int RF_USB_recv_frame(unsigned char * frame, unsigned int flen);


int RF_USB_send_frame(unsigned char * frame, unsigned int flen)
{
    int rc = 0;

    if(_g_hDevice == NULL)
    {
        return -1;
    }

    if(!frame)
    {
        return -1;
    }

    if(flen > (sizeof(send_frame_buf)-sizeof(long)))
    {
        return -1;
    }

    memcpy(((unsigned char *)&send_frame_buf[0]), frame, flen);
    send_frame_len = flen;
    
    if(ListenPipe.hDevice)
    {
        WDU_HaltTransfer(ListenPipe.hDevice, ListenPipe.dwListenPipeNum);
    }
    
    return rc;
    
}

typedef int (* RF_USB_RTS_FUNC)(void);

RF_USB_RTS_FUNC RF_USB_RTS;

// Function: PipeHandlerThread()
//   Callback function, which listens to a pipe continuously when there is data 
//   available in the pipe
// Parameters:
//   pParam [in] contains the relevant pipe information
// Return Value:
//   None
void DLLCALLCONV PipeHandlerThread(void * pParam)
{
    static DWORD dwErrorLast;
    DWORD dwError;
    USB_LISTEN_PIPE *pListenPipe = (USB_LISTEN_PIPE*) pParam;
    PVOID buf = malloc(pListenPipe->dwPacketSize);
        
    DWORD frame_finished = 1;
    DWORD dwBytesTransferred;

    int rc;

    for (;;)
    {

        if(send_frame_len)
        {
            PipeSend(pParam);

            recv_frame_len = 0;
        }
        
        dwError = WDU_Transfer(pListenPipe->hDevice, pListenPipe->dwListenPipeNum,
            TRUE, 0, buf, pListenPipe->dwPacketSize, 
            &dwBytesTransferred, NULL, TRANSFER_TIMEOUT);
        
        if (pListenPipe->fStopped)
        {
            if(log_file) 
            {
                fprintf(log_file, "Stoped\n");
            }
            printf("Stoped\n");
            break;
        }

        if (dwError)
        {
            if(dwError == WD_IRP_CANCELED)
            {
                continue;
            }
            if(dwError == WD_TIME_OUT_EXPIRED)
            {
            }
            else if(dwError == WD_DEVICE_NOT_FOUND)
            {
            }
            else if(dwErrorLast != dwError)
            {
                if(log_file) 
                {
                    fprintf(log_file, "PipeHandlerThread error code %X\n", dwError);
                }
                printf("PipeHandlerThread error code %X\n", dwError);
            }
            pListenPipe->dwError = dwError;
        }
        else

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -