void TDirIterator::start()
{
    Q_ASSERT(m_Status == stNotStarted);

    #ifdef Q_OS_WIN
        QString Path = PathToLongWinPath(m_StartPath);
        if (!Path.endsWith(QDir::separator()))
            Path += QDir::separator();
        Path += '*';

        m_hFind = FindFirstFileExW((LPCWSTR)Path.utf16(),
                                   FindExInfoStandard,
                                   &m_FindData,
                                   FindExSearchNameMatch,
                                   NULL,
                                   0);
        if (m_hFind != INVALID_HANDLE_VALUE) {
            m_FileInfoEx.m_Data->init(m_StartPath, &m_FindData);
            m_Status = stStarted;
        }
        else {
            DWORD ErrCode = GetLastError();
            if (ErrCode != ERROR_FILE_NOT_FOUND) {
                qWarning("TDirIterator::start. FindFirstFileEx error on \"%s\": %s",
                         qPrintable(m_StartPath),
                         qPrintable(GetSystemErrorString(ErrCode)));
            }
            m_Status = stFinished;
        }
    #else
        m_pDir = ::opendir(m_StartPath.toLocal8Bit().data());
        if (m_pDir != NULL) {
            m_Status = stStarted;
            getNext();
        }
        else {
            qWarning("TDirIterator::start. opendir error on \"%s\": %s",
                     qPrintable(m_StartPath),
                     qPrintable(GetSystemErrorString()));
            m_Status = stFinished;
        }
    #endif

    if (m_FileInfoEx.exists()) {
        if (!m_FileInfoEx.isDir()) {
            qWarning("TDirIterator::start. Not folder: \"%s\".",
                     qPrintable(m_StartPath));
            finish();
        }
    }
    else {
        qWarning("TDirIterator::start. Object not exists or insufficient privileges: \"%s\".",
                 qPrintable(m_StartPath));
    }
}
bool SHCreateItemFromParsingName_Wrapper(const QString& Path, IShellItem** ppShellItem)
{
    typedef HRESULT (WINAPI *TpSHCreateItemFromParsingName)(PCWSTR pszPath,
                                                            IBindCtx *pbc,
                                                            REFIID riid,
                                                            void **ppv);

    static TpSHCreateItemFromParsingName pSHCreateItemFromParsingName =
               reinterpret_cast<TpSHCreateItemFromParsingName>(
                   QLibrary::resolve("Shell32", "SHCreateItemFromParsingName")
            );

    if (pSHCreateItemFromParsingName != NULL)
    {
        HRESULT HResult = pSHCreateItemFromParsingName(
                              (PCWSTR)QDir::toNativeSeparators(Path).utf16(),
                              NULL,
                              IID_IShellItem,
                              reinterpret_cast<void**>(ppShellItem));
        if (FAILED(HResult))
        {
            qWarning("SHCreateItemFromParsingName error on \"%s\": %s.",
                     qPrintable(Path),
                     qPrintable(GetSystemErrorString(HResult)));

        }
        return SUCCEEDED(HResult);
    }
    else {
        qWarning("Poiner to Shell32.SHCreateItemFromParsingName is NULL.");
    }

    return false;
}
DWORD WINAPI FlexMsgReadThreadProc_Stub(LPVOID pVoid)
{
    VALIDATE_POINTER_RETURN_VAL(sg_pIlog, (DWORD)-1);

	CPARAM_THREADPROC* pThreadParam = (CPARAM_THREADPROC *) pVoid;

    pThreadParam->m_unActionCode = CREATE_TIME_MAP;
    // Validate certain required pointers
   
    bool bLoopON = true;

	while (bLoopON)
	{
        static HANDLE ahClientReadHandle[MAX_CLIENT_ALLOWED] = {0};
        for (UINT i = 0; i < sg_unClientCnt; i++)
        {
            ahClientReadHandle[i] = sg_asClientToBufMap[i].hClientHandle;
        }
        DWORD dwIndex = WaitForMultipleObjects(sg_unClientCnt, ahClientReadHandle, FALSE, INFINITE);

        if (dwIndex == WAIT_FAILED)
        {
            GetSystemErrorString();
        }
        else
        {
            UINT Index = dwIndex - WAIT_OBJECT_0;
            switch (pThreadParam->m_unActionCode)
		    {
			    case INVOKE_FUNCTION:
			    {
				    // Retrieve message from the pipe
                    ProcessCanMsg(sg_asClientToBufMap[Index].hPipeFileHandle, Index);
			    }
			    break;
                case CREATE_TIME_MAP:
                {
                    PerformAnOperation(GET_TIME_MAP);
                    ProcessCanMsg(sg_asClientToBufMap[Index].hPipeFileHandle, Index);
                    pThreadParam->m_unActionCode = INVOKE_FUNCTION;
                }
			    break;
			    case EXIT_THREAD:
			    {
				    bLoopON = false;
			    }
			    break;
			    default:
			    case INACTION:
			    {
				    // nothing right at this moment
			    }
			    break;
		    }
        }
	}
    SetEvent(pThreadParam->hGetExitNotifyEvent());

    return 0;
}
bool Cx_TextUtil::ReadTextFile(BYTE head[5], std::wstring& content, 
							   const std::wstring& filename, 
							   ULONG nLenLimitMB, UINT codepage)
{
	ZeroMemory(head, sizeof(BYTE) * 5);
	content.resize(0);
	
	bool bRet = false;
	HANDLE hFile = ::CreateFileW(filename.c_str(), 
		GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

	if (INVALID_HANDLE_VALUE == hFile)
	{
		LOG_ERROR2(LOGHEAD L"IDS_OPEN_FAIL", 
			filename << L", " << GetSystemErrorString(GetLastError()));
	}
	else
	{
		DWORD dwLength = ::GetFileSize(hFile, NULL);
		HGLOBAL hBuffer = NULL;

		if (dwLength != INVALID_FILE_SIZE)
		{
			if (dwLength > nLenLimitMB * 1024L * 1024L)
			{
				LOG_WARNING2(LOGHEAD L"IDS_HUGE_FILE", 
					(dwLength / (1024.0*1024.0)) << L"MB, " << filename);
				dwLength = nLenLimitMB * 1024L * 1024L;
			}
			hBuffer = GlobalAlloc(GHND, dwLength + 8);
		}
		
		if (hBuffer != NULL)
		{
			LPBYTE pBuffer = (LPBYTE)GlobalLock(hBuffer);
			if (pBuffer != NULL)
			{
				DWORD dwBytesRead = 0;
				::ReadFile(hFile, pBuffer, dwLength, &dwBytesRead, NULL);
				if (dwBytesRead > 0)
				{
					CopyMemory(head, pBuffer, sizeof(BYTE) * min(5, dwBytesRead));
					bRet = GetFileContent(content, pBuffer, dwBytesRead, codepage);
					if (!bRet)
					{
						LOG_WARNING2(LOGHEAD L"IDS_NOT_ANSIFILE", filename);
					}
				}
				GlobalUnlock(hBuffer);
			}
			GlobalFree(hBuffer);
		}
		
		::CloseHandle(hFile);
	}

	return bRet;
}
void TDirIterator::getNext()
{
    if (m_Status != stStarted)
        return;

    #ifdef Q_OS_WIN
        Q_ASSERT(m_hFind != INVALID_HANDLE_VALUE);

        if (FindNextFileW(m_hFind, &m_FindData) != 0) {
            m_FileInfoEx.m_Data->init(m_StartPath, &m_FindData);
        }
        else {
            DWORD ErrCode = GetLastError();
            if (ErrCode != ERROR_NO_MORE_FILES) {
                qWarning("TDirIterator::getNext. FindNextFile error on \"%s\": %s",
                         qPrintable(m_StartPath),
                         qPrintable(GetSystemErrorString(ErrCode)));
            }
            finish();
        }
    #else
        Q_ASSERT(m_pDir != NULL);

        errno = 0;
        struct dirent64* pDirEnt = ::readdir64(m_pDir);
        if (pDirEnt != NULL) {
            m_FileInfoEx.setName(AddWithSeparator(m_StartPath,
                                                  QString::fromLocal8Bit(pDirEnt->d_name)));
        }
        else {
            if (errno != 0) {
                qWarning("TDirIterator::getNext. readdir64 error on \"%s\": %s",
                         qPrintable(m_StartPath),
                         qPrintable(GetSystemErrorString()));
            }
            finish();
        }
    #endif
}
 IFileOpenDialog_Wrapper()
 {
     HRESULT HResult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
     if (SUCCEEDED(HResult))
     {
         HResult = CoCreateInstance(CLSID_FileOpenDialog,
                                    NULL,
                                    CLSCTX_INPROC_SERVER,
                                    IID_IFileOpenDialog,
                                    reinterpret_cast<void**>(&m_pInterface));
         if (FAILED(HResult))
         {
             qWarning("CoCreateInstance error: %s",
                      qPrintable(GetSystemErrorString(HResult)));
             CoUninitialize();
         }
     }
     else {
         qWarning("CoInitializeEx error: %s",
                  qPrintable(GetSystemErrorString(HResult)));
     }
 }
void TDirIterator::finish()
{
    #ifdef Q_OS_WIN
        if (m_hFind != INVALID_HANDLE_VALUE) {
            if (!FindClose(m_hFind)) {
                qWarning("TDirIterator::finish. FindClose error: %s",
                         qPrintable(GetSystemErrorString()));
            }
            m_hFind = INVALID_HANDLE_VALUE;
        }
    #else
        if (m_pDir != NULL) {
            if (::closedir(m_pDir) != 0) {
                qWarning("TDirIterator::finish. closedir error: %s",
                         qPrintable(GetSystemErrorString()));
            }
            m_pDir = NULL;
        }
    #endif

    m_FileInfoEx.clear();
    m_Status = stFinished;
}
Exemple #8
0
//==============================================================================
// SystemUtils::TraceSystemCall
//
//==============================================================================
void SystemUtils::TraceSystemCall(short nSection, short nLevel, const String& message, int rc)
{
	static String sRC = QC_T(" rc=");
	static String sErrno = QC_T(", errno=");
	static String sComma = QC_T(", ");
	int err=errno;

	String traceMsg = message + sRC + NumUtils::ToString(rc);
	if(rc!=0)
	{
		traceMsg += sErrno  + NumUtils::ToString(err)
	             + sComma + GetSystemErrorString(err);
	}

	Tracer::Trace(nSection, nLevel, traceMsg);
}
void setFileDialogParams(IFileDialog* pDialog,
                         const QString& caption,
                         const QString& dir,
                         bool AllowMultiselect)
{
    Q_ASSERT(pDialog != NULL);

    HRESULT HResult = S_OK;

    // Заголовок окна.
    if (!caption.isEmpty())
    {
        HResult = pDialog->SetTitle((LPCWSTR)caption.utf16());
        if (FAILED(HResult))
        {
            qWarning("IFileDialog::SetTitle error: %s.",
                     qPrintable(GetSystemErrorString(HResult)));
        }
    }

    // Начальный каталог.
    if (!dir.isEmpty())
    {
        IShellItem* pItem;
        if (SHCreateItemFromParsingName_Wrapper(dir, &pItem))
        {
            pDialog->SetFolder(pItem);
            pItem->Release();
        }
    }

    // Опции.
    FILEOPENDIALOGOPTIONS Options;
    Options = FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM |
              FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST;
    if (AllowMultiselect)
        Options |= FOS_ALLOWMULTISELECT;
    HResult = pDialog->SetOptions(Options);
    if (FAILED(HResult))
    {
        qWarning("IFileDialog::SetOptions error: %lu.", HResult);
    }
}
Exemple #10
0
DWORD Cx_TextUtil::GetHeadBytes(const std::wstring& filename, BYTE head[5])
{
	DWORD dwBytesRead = 0;
	HANDLE hFile = ::CreateFileW(filename.c_str(), 
		GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

	if (hFile != INVALID_HANDLE_VALUE)
	{
		::ReadFile(hFile, head, 5, &dwBytesRead, NULL);
		::CloseHandle(hFile);
	}
	else
	{
		LOG_ERROR2(LOGHEAD L"IDS_OPEN_FAIL", 
			filename << L", " << GetSystemErrorString(GetLastError()));
	}

	return dwBytesRead;
}
Exemple #11
0
bool Cx_TextUtil::SaveTextFile(const std::string& content, 
							   const std::wstring& filename, 
							   bool utf16, UINT codepage)
{
	bool bRet = false;

	::SetFileAttributes(filename.c_str(), FILE_ATTRIBUTE_NORMAL);
	HANDLE hFile = ::CreateFileW(filename.c_str(), 
		GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);

	if (INVALID_HANDLE_VALUE == hFile)
	{
		LOG_ERROR2(LOGHEAD L"IDS_WRITE_FAIL", 
			filename << L", " << GetSystemErrorString(GetLastError()));
	}
	else
	{
		DWORD dwLen, dwBytes;

		if (utf16)
		{
			std::wstring wstrUnicode (std::a2w(content, codepage));

			BYTE head[] = { 0xFF, 0xFE };
			::WriteFile(hFile, head, 2, &dwBytes, NULL);

			dwLen = (DWORD)(wstrUnicode.size() * sizeof(WCHAR));
			::WriteFile(hFile, wstrUnicode.c_str(), dwLen, &dwBytes, NULL);
			bRet = (dwBytes == dwLen);
		}
		else
		{
			dwLen = GetSize(content);
			::WriteFile(hFile, content.c_str(), dwLen, &dwBytes, NULL);
			bRet = (dwBytes == dwLen);
		}

		::CloseHandle(hFile);
	}

	return bRet;
}
Exemple #12
0
static void ProcessCanMsg(HANDLE hClientHandle, UINT unIndex)
{
    static SPIPE_CANMSG sPipeCanMsg;
    static STCANDATA sCanData;
    static DWORD dwBytes = 0;

    /* To be noted - there is no validation for any pointer. This is because 
    this function assumes them to have been duly validated beforehand and it
    is so by implementation. Efficiency is the motivation behind. */
    BYTE abyData[SIZE_DAT_P] = {'\0'};

    //if (ReadFile(hClientHandle, &sPipeCanMsg, SIZE_PIPE_CANMSG, &dwBytes, NULL))
    if (ReadFile(hClientHandle, abyData, SIZE_DAT_P, &dwBytes, NULL))
    {
        memcpy(&(sPipeCanMsg.m_byTxRxFlag), abyData, 1);
        memcpy(&(sPipeCanMsg.m_unTimeStamp), abyData + 1, SIZE_TIMESTAMP);
        memcpy(&(sPipeCanMsg.m_sCanMsg), abyData + 1 + SIZE_TIMESTAMP, sizeof(STCAN_MSG));
        if (dwBytes == SIZE_PIPE_CANMSG)
        {   
            sCanData.m_lTickCount.QuadPart = sPipeCanMsg.m_unTimeStamp;
            sCanData.m_uDataInfo.m_sCANMsg = sPipeCanMsg.m_sCanMsg;

            if (sPipeCanMsg.m_byTxRxFlag == FLAG_TX)
            {
                sCanData.m_ucDataType = TX_FLAG;
            }
            else
            {                
                sCanData.m_ucDataType = RX_FLAG;            
            }
            for (UINT i = 0; i < sg_asClientToBufMap[unIndex].unBufCount; i++)
            {
                sg_asClientToBufMap[unIndex].pClientBuf[i]->WriteIntoBuffer(&sCanData);
            }
        }
    }
    else
    {
        GetSystemErrorString();
    }
}
void CHttpDownloadDlg::HandleThreadErrorWithLastError(CString strIDError, DWORD dwLastError)
{
	if (dwLastError == 0)
		dwLastError = GetLastError();
	CString strLastError;
	if (dwLastError >= INTERNET_ERROR_BASE && dwLastError <= INTERNET_ERROR_LAST)
		GetModuleErrorString(dwLastError, strLastError, _T("wininet"));
	else
		GetSystemErrorString(dwLastError, strLastError);
	m_sError.Format(strIDError, _T(" ") + strLastError);

	//Delete the file being downloaded to if it is present
	try {
		m_FileToWrite.Close();
	}
	catch (CFileException *ex) {
		ex->Delete();
	}
	::DeleteFile(m_sFileToDownloadInto);

	PostMessage(WM_HTTPDOWNLOAD_THREAD_FINISHED, 1);
}
VOID CALLBACK TimerCallBack( 
    HWND hwnd,        // handle to window for timer messages 
    UINT message,     // WM_TIMER message 
    UINT idTimer,     // timer identifier 
    DWORD dwTime)     // current system time 
{
	unsigned int i = 0;
	int bResult, dwError;
	unsigned int ulWritten, ulRead;
	unsigned int x_pos, y_pos;
	int x_velocity, y_velocity;

	
	TxBuffer[0] = 'D';
	TxBuffer[1] = 'R';
	TxBuffer[2] = 'E';
	TxBuffer[3] = 'Q';

	
	bResult = WriteUSBPacket(hUSB, (unsigned char *)TxBuffer, DREQ_NUM, (unsigned long *)&ulWritten);
	if(!bResult)
	{
		//
		// We failed to write the data for some reason.
		//
		dwError = GetLastError();
		printf("Error %d (%S) writing to bulk OUT pipe.\n", dwError,
		GetSystemErrorString(dwError));
	}
	else
	{
                    //
                    // We wrote data successfully so now read it back.
                    //
		printf("Wrote %d bytes to the device: 0x%x, 0x%x, 0x%x, 0x%x.\n", ulWritten, TxBuffer[0], TxBuffer[1], TxBuffer[2], TxBuffer[3]);

                    //
                    // We expect the same number of bytes as we just sent.
                    //
			dwError = ReadUSBPacket(hUSB, (unsigned char *)RxBuffer, FRM_SIZE, (unsigned long *)&ulRead, INFINITE, NULL);

                    if(dwError != ERROR_SUCCESS)
                    {
                        //
                        // We failed to read from the device.
                        //
                        printf("Error %d (%S) reading from bulk IN pipe.\n", dwError,
                               GetSystemErrorString(dwError));
                    }
                    else
                    {
					
							x_pos = RxBuffer[0]|(RxBuffer[1]<<8)|(RxBuffer[2]<<16)|(RxBuffer[3]<<24);
							y_pos = RxBuffer[4]|(RxBuffer[5]<<8)|(RxBuffer[6]<<16)|(RxBuffer[7]<<24);
							x_velocity = RxBuffer[8]|(RxBuffer[9]<<8)|(RxBuffer[10]<<16)|(RxBuffer[11]<<24);
							y_velocity = RxBuffer[12]|(RxBuffer[13]<<8)|(RxBuffer[14]<<16)|(RxBuffer[15]<<24);
						
						printf("x_pos=%d, y_pos=%d, x_velocity=%d, y_velocity=%d.\n",x_pos, y_pos, x_velocity, y_velocity);
                    }
	}
}
QStringList showDirDialog(IFileOpenDialog* pDialog, QWidget* parent)
{
    Q_ASSERT(pDialog != NULL);

    QStringList Result;

    if (parent == NULL)
        parent = QApplication::activeWindow();
    HWND hwndParent = parent ? parent->window()->winId() : NULL;

    HRESULT HResult = pDialog->Show(hwndParent);
    if (SUCCEEDED(HResult))
    {
        // Что-то было выбрано.
        IShellItemArray* pShellItemArray;
        HResult = pDialog->GetResults(&pShellItemArray);
        if (SUCCEEDED(HResult))
        {
            DWORD ItemsCount;
            HResult = pShellItemArray->GetCount(&ItemsCount);
            if (SUCCEEDED(HResult))
            {
                IShellItem* pItem;
                for (DWORD i = 0; i < ItemsCount; ++i)
                {
                    HResult = pShellItemArray->GetItemAt(i, &pItem);
                    if (SUCCEEDED(HResult))
                    {
                        wchar_t* lpwName;
                        HResult = pItem->GetDisplayName(SIGDN_FILESYSPATH, &lpwName);
                        if (SUCCEEDED(HResult))
                        {
                            Result.append(QString::fromWCharArray(lpwName));
                            CoTaskMemFree(lpwName);
                        }
                        else {
                            qWarning("IShellItem::GetDisplayName error: %s.",
                                     qPrintable(GetSystemErrorString(HResult)));
                        }
                        pItem->Release();
                    }
                    else {
                        qWarning("IShellItemArray::GetItemAt(%lu, ...) error: %s.",
                                 i, qPrintable(GetSystemErrorString(HResult)));
                    }
                }
                pShellItemArray->Release();
            }
            else {
                qWarning("IShellItemArray::GetCount error: %s",
                         qPrintable(GetSystemErrorString(HResult)));
            }
        }
        else {
            qWarning("IFileOpenDialog::GetResults error: %s",
                     qPrintable(GetSystemErrorString(HResult)));
        }
    }
    else {
        if (HResult == HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
            // Пользователь ничего не выбрал.
        }
        else {
            qWarning("IFileOpenDialog::Show error: %s",
                     qPrintable(GetSystemErrorString(HResult)));
        }
    }

    return Result;
}
//****************************************************************************
//
// The main application entry function.
//
// \param None.
//
// This function forms the main entry point of the example application. It
// initializes the USB bulk device, prompts the user for an ASCII string,
// sends this string to the device, reads the response from the device (which
// will be the same string with the character order reversed if using the
// sample device provided by Luminary Micro) and displays the returned
// string.
//
// \return Set the exit code to 0 of no errors cause the application to end
// or a non-zero value otherwise.
//
//****************************************************************************
int main(int argc, char *argv[])
{
    BOOL bResult;
    BOOL bDriverInstalled;
    BOOL bEcho;
    char szBuffer[MAX_ENTRY_LEN];
    ULONG ulWritten;
    ULONG ulRead;
    ULONG ulLength;
    DWORD dwError;
    LMUSB_HANDLE hUSB;

    //
    // Are we operating in echo mode or not? The "-e" parameter tells the
    // app to echo everything it receives back to the device unchanged.
    //
    bEcho = ((argc > 1) && (argv[1][1] == 'e')) ? TRUE : FALSE;

    //
    // Print a cheerful welcome.
    //
    printf("\nLuminary Micro Bulk USB Device Example\n");
    printf("--------------------------------------\n\n");
    printf("Version %s\n\n", BLDVER);
    if(!bEcho)
    {
        printf("This is a partner application to the usb_dev_bulk example\n");
        printf("shipped with StellarisWare software releases for USB-enabled\n");
        printf("boards. Strings entered here are sent to the board which\n");
        printf("inverts the case of the characters in the string and returns\n");
        printf("them to the host.\n\n");
    }
    else
    {
        printf("If run with the \"-e\" command line switch, this application\n");
        printf("echoes all data received on the bulk IN endpoint to the bulk\n");
        printf("OUT endpoint.  This feature may be helpful during development\n");
        printf("and debug of your own USB devices.  Note that this will not\n");
        printf("do anything exciting if run with the usb_dev_bulk example\n");
        printf("device attached since it expects the host to initiate transfers.\n\n");
    }

    //
    // Find our USB device and prepare it for communication.
    //
    hUSB = InitializeDevice(BULK_VID, BULK_PID,
                            (LPGUID)&(GUID_DEVINTERFACE_LUMINARY_BULK),
                            &bDriverInstalled);

    if(hUSB)
    {
        //
        // Are we operating in echo mode or not? The "-e" parameter tells the
        // app to echo everything it receives back to the device unchanged.
        //
        if(bEcho)
        {
            //
            // Yes - we are in echo mode.
            //
            printf("Running in echo mode. Press Ctrl+C to exit.\n\n"
                "Throughput:      0Kbps Packets:           0");

            while(1)
            {
                //
                // Read a packet of data from the device.
                //
                dwError = ReadUSBPacket(hUSB, szBuffer, ECHO_PACKET_SIZE, &ulRead,
                                        INFINITE, NULL);

                if(dwError != ERROR_SUCCESS)
                {
                    //
                    // We failed to read from the device.
                    //
                    printf("\n\nError %d (%S) reading from bulk IN pipe.\n", dwError,
                           GetSystemErrorString(dwError));
                    break;
                }
                else
                {
                    //
                    // Update our byte and packet counters.
                    //
                    g_ulByteCount += ulRead;
                    g_ulPacketCount++;

                    //
                    // Write the data back out to the device.
                    //
                    bResult = WriteUSBPacket(hUSB, szBuffer, ulRead, &ulWritten);
                    if(!bResult)
                    {
                        //
                        // We failed to write the data for some reason.
                        //
                        dwError = GetLastError();
                        printf("\n\nError %d (%S) writing to bulk OUT pipe.\n", dwError,
                               GetSystemErrorString(dwError));
                        break;
                    }

                    //
                    // Display the throughput.
                    //
                    UpdateThroughput();
                }
            }
        }
        else
        {
            //
            // We are running in normal mode.  Keep sending and receiving
            // strings until the user indicates that it is time to exit.
            //
            while(1)
            {

                //
                // The device was found and successfully configured. Now get a string from
                // the user...
                //
                do
                {
                    printf("\nEnter a string (EXIT to exit): ");
                    fgets(szBuffer, MAX_ENTRY_LEN, stdin);
                    printf("\n");

                    //
                    // How many characters were entered (including the trailing '\n')?
                    //
                    ulLength = (ULONG)strlen(szBuffer);

                    if(ulLength <= 1)
                    {
                        //
                        // The string is either nothing at all or a single '\n' so reprompt the user.
                        //
                        printf("\nPlease enter some text.\n");
                        ulLength = 0;
                    }
                    else
                    {
                        //
                        // Get rid of the trailing '\n' if there is one there.
                        //
                        if(szBuffer[ulLength - 1] == '\n')
                        {
                            szBuffer[ulLength - 1] = '\0';
                            ulLength--;
                        }
                    }
                }
                while(ulLength == 0);

                //
                // Are we being asked to exit the application?
                //
                if(!(strcmp("EXIT", szBuffer)))
                {
                    //
                    // Yes - drop out and exit.
                    //
                    printf("Exiting on user request.\n");
                    break;
                }

                //
                // Write the user's string to the device.
                //
                bResult = WriteUSBPacket(hUSB, szBuffer, ulLength, &ulWritten);
                if(!bResult)
                {
                    //
                    // We failed to write the data for some reason.
                    //
                    dwError = GetLastError();
                    printf("Error %d (%S) writing to bulk OUT pipe.\n", dwError,
                           GetSystemErrorString(dwError));
                }
                else
                {
                    //
                    // We wrote data successfully so now read it back.
                    //
                    printf("Wrote %d bytes to the device. Expected %d\n",
                           ulWritten, ulLength);

                    //
                    // We expect the same number of bytes as we just sent.
                    //
                    dwError = ReadUSBPacket(hUSB, szBuffer, ulWritten, &ulRead,
                                            INFINITE, NULL);

                    if(dwError != ERROR_SUCCESS)
                    {
                        //
                        // We failed to read from the device.
                        //
                        printf("Error %d (%S) reading from bulk IN pipe.\n", dwError,
                               GetSystemErrorString(dwError));
                    }
                    else
                    {
                        //
                        // Add a string terminator to the returned data (this
                        // should already be there but, just in case...)
                        //
                        szBuffer[ulRead] = '\0';

                        printf("Read %d bytes from device. Expected %d\n",
                               ulRead, ulWritten);
                        printf("\nReturned string: \"%s\"\n", szBuffer);
                    }
                }
            }
        }
    }
    else
    {
        //
        // An error was reported while trying to connect to the device.
        //
        dwError = GetLastError();

        printf("\nUnable to initialize the Luminary Bulk USB Device.\n");
        printf("Error code is %d (%S)\n\n", dwError, GetSystemErrorString(dwError));
        printf("Please make sure you have a Luminary Stellaris USB-enabled\n");
        printf("evaluation or development kit running the usb_dev_bulk example\n");
        printf("application connected to this system via the \"USB OTG\" or\n");
        printf("\"USB DEVICE\" connectors. Once the device is connected, run\n");
        printf("this application again.\n\n");

        printf("\nPress \"Enter\" to exit: ");
        fgets(szBuffer, MAX_STRING_LEN, stdin);
        printf("\n");
        return(2);
    }

    TerminateDevice(hUSB);

    return(0);
}
Exemple #17
0
HRESULT Worker_RegisterClient(ISimENG* pISimENG, Base_WrapperErrorLogger* pIlog)
{ 
    USHORT ushClientID = 0;     // Client ID issued from the simulation engine
    BSTR PipeName;              // Name of the conduit
    BSTR EventName;             // Name of the message notifying event
    HRESULT hResult = S_OK;

    // Register to the simulation engine
    hResult = pISimENG->RegisterClient(CAN, sizeof (STCAN_MSG), &ushClientID, &PipeName, &EventName);
    if (hResult != S_OK)
    {
        pIlog->vLogAMessage(__FILE__, __LINE__, 
                    ("unable to register to the simulation engine"));
        return S_FALSE;
    }

    sg_ushTempClientID = ushClientID;

    // Extract the pipe and event name in normal string
    char acPipeName[64] = {'\0'};
    char acEventName[32] = {'\0'};
    if (BSTR_2_PCHAR(PipeName, acPipeName, 64) == false)
    {
        hResult = S_FALSE;
    }

    if (BSTR_2_PCHAR(EventName, acEventName, 32) == false)
    {
        hResult = S_FALSE;
    }

    if (S_FALSE == hResult)
    {
        // Unregister from the simulation engine
        pISimENG->UnregisterClient(ushClientID);
        pIlog->vLogAMessage(__FILE__, __LINE__,
                    ("Can't convert from BSTR to ASCII string"));
        return S_FALSE;
    }

    // Get the pipe handle
    sg_hTmpPipeHandle = CreateFile(
        acPipeName,     // pipe name 
        GENERIC_READ,   // read access 
        0,              // no sharing 
        NULL,           // no security attributes
        OPEN_EXISTING,  // opens existing pipe 
        0,              // default attributes 
        NULL);          // no template file 

    if (sg_hTmpPipeHandle == INVALID_HANDLE_VALUE) 
    {
        // Unregister from the simulation engine
        pISimENG->UnregisterClient(ushClientID);
        GetSystemErrorString();
        LOG_ERR_MSG();
        return S_FALSE;
    }

    sg_hTmpClientHandle = OpenEvent(EVENT_ALL_ACCESS, FALSE, acEventName);
    if (sg_hTmpClientHandle == NULL)
    {
        CloseHandle(sg_hTmpPipeHandle);
        sg_hTmpPipeHandle = NULL;
        // Unregister from the simulation engine
        pISimENG->UnregisterClient(ushClientID);
        GetSystemErrorString();
        LOG_ERR_MSG();
        return S_FALSE;
    }
    return hResult;
}
int main(int argc, char *argv[])
{
	BOOL bDriverInstalled;
	DWORD dwError;


    //
    // Find our USB device and prepare it for communication.
    //
   hUSB = InitializeDevice(BULK_VID, BULK_PID,
                            (LPGUID)&(GUID_DEVINTERFACE_STELLARIS_BULK),
                            &bDriverInstalled);
						
//							hUSB = 0xaadd;
	if(hUSB)
    {
				//set timer
//	UINT uResult;
	MSG msg;

	UINT BallInfoNum;
	UINT ulWritten, bResult;
	FILE * fp;
	char ch;


			bResult = fopen_s(&fp, "initial.txt", "rw");
			if(bResult){
				printf("file open error!\n");
				return -1;
			}

	//		ch = getchar();

			// read initial value and send to launchpad
//			fprintf(fp, "######!");
//			fclose(fp);
			bResult = fread(TxBuffer, 4, 3, fp);
			if(bResult != 3){
				printf("initial value read error!\n");
				return -2;
			}
			DisplayHandler.test_mode = TxBuffer[0];
			DisplayHandler.ball_num = TxBuffer[1];
			DisplayHandler.time_interval = TxBuffer[2];

			BallInfoNum = DisplayHandler.ball_num * sizeof(tBallData);

			bResult = fread(TxBuffer+3, 4, BallInfoNum, fp);
			if(bResult != BallInfoNum){
				printf("initial ball information read error!\n");
				return -3;
			}
			
			bResult = WriteUSBPacket(hUSB, (unsigned char *)TxBuffer, (BallInfoNum+3), (unsigned long *)&ulWritten);
//			if(!bResult)
			{

			}

			timer_id = SetTimer(NULL, NULL, 40, (TIMERPROC)TimerCallBack);
			if(timer_id == 0)
			{
				printf("error timer handle!\n");
			}
			printf("time handle ready %d!\n", timer_id);

			
			while (GetMessage(&msg, NULL, 0, 0) != -1) 
				DispatchMessage(&msg);

			while(1);

	}
	else{
        //
        // An error was reported while trying to connect to the device.
        //
        dwError = GetLastError();

        printf("\nUnable to initialize the Stellaris Bulk USB Device.\n");
        printf("Error code is %d (%S)\n\n", dwError, GetSystemErrorString(dwError));
        printf("Please make sure you have a Stellaris USB-enabled evaluation\n");
        printf("or development kit running the usb_dev_bulk example\n");
        printf("application connected to this system via the \"USB OTG\" or\n");
        printf("\"USB DEVICE\" connectors. Once the device is connected, run\n");
        printf("this application again.\n\n");

        printf("\nPress \"Enter\" to exit: ");
 //       fgets(rx_buf, MAX_STRING_LEN, stdin);
        printf("\n");
        return(2);
	}
    TerminateDevice(hUSB);

    return(0);
}