Example #1
0
HANDLE
mkEvent()
{
  return CreateEvent(NULL, FALSE, FALSE, NULL);
}
Example #2
0
 PlatformParker  () {
   _ParkEvent = CreateEvent (NULL, true, false, NULL) ;
   guarantee (_ParkEvent != NULL, "invariant") ;
 }
Example #3
0
/*
** CreateAsc( ) --- Create an association.
**
** Inputs:
**	asipc	ASSOC_IPC for association
**	name	name of server creating association.
** Output:
**	returns TRUE if succeeds.
**
** GClisten( ) calls CreateAsc( ) when a server wishes to create
** a new association. CrateAsc( ) allocates the resources required by 
** the association, and exposes shared information available to other processes.
** The only requirements are that it create four handles in the ASSOC_IPC:
** standard send, standard receive, expedited send, and expeditied receive.
** These handles are the only members created here used by gcacl. In 
** this implementation handles to anonymous pipes are used.
**
** If there are no existing connections to the server spicified in the 
** name parameter, CreateAsc( ) creates the server specific resources and
** adds the server to the internally maintained list of servers. A memory mapped
** mapped file is created for passing information between the client and 
** server. This file contains a temporary area for passing process id and
** handles which the client needs to copy to its own ASSOC_IPC. It also 
** contains and array of assoc_info structures. These structures contain
** information that must be shared per connection for the duration of each 
** association. A mutex is created to protect access to the temporary area.
** The temporary area is only used when a connectionis first established
** to copy handles to the pipes and other information to the requester's
** ASSOC_IPC.
**
** Two events are also created to arbitrate the connection process. When
** a server is ready for a connection, it signals a "listening event". 
** and waits for a client to set a requesting event. Before connecting 
** a client waits on the listening event before trying to connect. When
** the client tries to connect it sets a requesting event to tell the server
** that a client has connected.
**
** The names for the memory mapped file, the mutex, and the events are
** based on the server name.
**
** History:
**      10-Dec-98 (lunbr01) Bug 94183
**          Eliminate use of *Ct fields (using PeekNamedPipe instead).
*/
BOOL 	 
CreateAsc(ASSOC_IPC * asipc, char *name )
{
	HANDLE 		hMapping; /* for memory mapped file */
	static HANDLE	hMutex;	  /* for memory mapped file */
	ASSOC_IPC	*asipc_temp;
	ASSOC_INFO	*assoc_info;
	struct _Asc_ipc_area	*svr_ipc_area;
	SERVER_ENTRY	*server;
	short		i;
															
	SECURITY_ATTRIBUTES	sa;
	
	/* Set up security attributes */		
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;
	
	/* If there are no existing connections to this server. Open the
	** memory mapped file, events, and mutex for this server. 
	*/
	if( NULL == ( server = LookUpServer( name ) ) )	
	{
		char ReqEventName[MAXPNAME + 4 ];
		char LstEventName[MAXPNAME + 4 ];
		
		if ((hMapping = CreateFileMapping(INVALID_HANDLE_VALUE,
				&sa,
				PAGE_READWRITE,
				0,
				sizeof( struct _Asc_ipc_area ),  
				name )) == NULL)
		{
			DWORD err = GetLastError( );
			return FALSE ;
		}
		
		if (NULL == (svr_ipc_area=
			(struct _Asc_ipc_area *)MapViewOfFile(hMapping,
						FILE_MAP_ALL_ACCESS,
						0,
						0,
						0 ) ) )
		{
			return FALSE;
		}
		
		/* Create an event that will be signaled when an 
		** association is requested.
		*/
		wsprintf( ReqEventName, "%s-%s", name, "req" );
		wsprintf( LstEventName, "%s-%s", name, "lst" );
		
		/* Create SERVER_ENTRY */
		server = AddServer( name,  svr_ipc_area, hMapping, 
					CreateEvent( &sa, FALSE, FALSE, 
					ReqEventName ), 
					CreateEvent( &sa, FALSE, FALSE, 
					LstEventName ) );
		
		/* Create a mutex to coordinate access to asipc_temp */
		hMutex = CreateMutex( &sa, FALSE, name );
		
		/* Create a proces handle so other processes can 
		   use DuplicateHandle */
		svr_ipc_area->nProcId =  GetCurrentProcessId( );
	}
	
	/* Get a pointer to the Memory mapped file for this server. */
	svr_ipc_area = server->lpMapping;
	
	if ( server->nConnections == MAX_ASSOCS ) /* no more assocs allowed */
		return FALSE ;
		
	asipc_temp = &( svr_ipc_area->asipc );
	assoc_info = (ASSOC_INFO *)&( svr_ipc_area->assoc_info );

	/* Make sure that it is safe to change temporary connection info.  
	** Copy the connection information the local ASSOC_IPC. 
	*/
	WaitForSingleObject( hMutex, INFINITE );	
	
	/* Find a valid id and set up the assoc_info. */
	for( i = 0; i < MAX_ASSOCS; i++ )
	{
		if ( assoc_info[i].refs == 0 )
			break;
	}
	asipc->IpcInternal.hMapping 	= hMapping; /* for save and restore */
	asipc->IpcInternal.AssocInfo	= &assoc_info[i];
	asipc_temp->IpcInternal.AscID	= asipc->IpcInternal.AscID = i;
	assoc_info[i].bPipesClosed = FALSE;
	assoc_info[i].refs++;

	/* Set the AssocInfo */

	assoc_info[i].out_buffer_size = Pipe_buffer_size;
	assoc_info[i].in_buffer_size = Pipe_buffer_size;

	if(!CreatePipe( &asipc->RcvStdChan, &asipc_temp->SndStdChan, &sa, 
				Pipe_buffer_size ) ||
	   !CreatePipe( &asipc_temp->RcvStdChan, &asipc->SndStdChan, &sa, 
				Pipe_buffer_size ) ||
	   !CreatePipe( &asipc->RcvExpChan, &asipc_temp->SndExpChan, &sa, 
				Pipe_buffer_size ) ||
	   !CreatePipe( &asipc_temp->RcvExpChan, &asipc->SndExpChan, &sa, 
				Pipe_buffer_size ) ) 
	{
		CloseAsc( asipc );
		CloseAsc( asipc_temp );
		return FALSE ;
	}

        /* We need to duplicate the client side of standard read handle
           asipc_temp->RcvStdChan for PeekNamedPipe() because it gets closed
           by the DUPLICATE_CLOSE_SOURCE option of DuplicateHandle() after a
           front end client connects to the server and duplicates it into
           their address space. */
        if (!DuplicateHandle(
                       GetCurrentProcess(),
                       asipc_temp->RcvStdChan,
                       GetCurrentProcess(),
                       &asipc->ClientReadHandle,
                       GENERIC_READ,
                       TRUE,
                       DUPLICATE_SAME_ACCESS
                       ) )
        {
                        CloseAsc( asipc );
                        CloseAsc( asipc_temp );
                        return FALSE ;
        }

        /* We need to duplicate the server side of standard read handle
           asipc->RcvStdChan for PeekNamedPipe() in the client because it
           gets closed by the DUPLICATE_CLOSE_SOURCE option of
           DuplicateHandle() after a front end client connects to the server
           and duplicates it into their address space. */
        if (!DuplicateHandle(
                       GetCurrentProcess(),
                       asipc->RcvStdChan,
                       GetCurrentProcess(),
                       &asipc_temp->ClientReadHandle,
                       GENERIC_READ,
                       TRUE,
                       DUPLICATE_SAME_ACCESS
                       ) )
        {
                        CloseAsc( asipc );
                        CloseAsc( asipc_temp );
                        return FALSE ;
        }

	ReleaseMutex( hMutex );

	/* 
	** Set up pointer to server and increment the number of connections.	
	*/
	asipc->IpcInternal.server = server;
	asipc->IpcInternal.server->nConnections++;
		
	return TRUE;
}
//==============================================================================
WaitableEvent::WaitableEvent (const bool manualReset) noexcept
    : handle (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0)) {}
clNamedPipe *clNamedPipeConnectionsServer::waitForNewConnection( int timeout )
{
	PIPE_HANDLE hConn = this->initNewInstance();

#ifdef __WXMSW__
	OVERLAPPED ov = {0};
	HANDLE ev = CreateEvent(NULL, TRUE, TRUE, NULL);
	ov.hEvent = ev;
	
	HandleLockerServer locker(ov.hEvent);
	
	bool fConnected = ConnectNamedPipe(hConn, &ov);
	if (fConnected != 0) {
		if(hConn != INVALID_PIPE_HANDLE) {
			CloseHandle(hConn);
		}
		this->setLastError(NP_SERVER_UNKNOWN_ERROR);
		return NULL;
	}

	switch (GetLastError()) {

		// The overlapped connection in progress.
	case ERROR_IO_PENDING: {
		DWORD res = WaitForSingleObject(ov.hEvent, timeout) ;
		switch (res) {
		case WAIT_OBJECT_0 : {
			clNamedPipeServer *conn = new clNamedPipeServer(_pipePath);
			conn->setHandle(hConn);
			return conn;
		}
		case WAIT_TIMEOUT : {
			if ( hConn != INVALID_PIPE_HANDLE ) {
				CloseHandle( hConn );
			}
			this->setLastError(NP_SERVER_TIMEOUT);
			return NULL;
		}
		default: {
			if ( hConn != INVALID_PIPE_HANDLE ) {
				CloseHandle( hConn );
			}

			this->setLastError(NP_SERVER_UNKNOWN_ERROR);
			return NULL;
		}

		}
	}

	case ERROR_PIPE_CONNECTED: {
		clNamedPipeServer *conn = new clNamedPipeServer(_pipePath);
		conn->setHandle(hConn);
		return conn;
	}
	// If an error occurs during the connect operation...
	default: {
		if(hConn != INVALID_PIPE_HANDLE) {
			CloseHandle(hConn);
		}

		this->setLastError(NP_SERVER_UNKNOWN_ERROR);
		return NULL;
	}
	}
#else
	// accept new connection
	if (hConn != INVALID_PIPE_HANDLE) {

		if ( timeout > 0 ) {
			fd_set fds;
			struct timeval tv;
			memset( (void*)&fds, 0, sizeof( fds ) );
			FD_SET( hConn, &fds );
			tv.tv_sec = 0;
			tv.tv_usec = timeout * 1000; // convert mili to micro

			int rc = select(hConn + 1, &fds, 0, 0, &tv);
			if ( rc == 0 || rc < 0 ) {
				// timeout or error
				setLastError(NP_SERVER_TIMEOUT);
				return NULL;
			}
		}

		PIPE_HANDLE fd = ::accept(hConn, 0, 0);
		if (fd > 0) {
			clNamedPipeServer *conn = new clNamedPipeServer(_pipePath);
			conn->setHandle(fd);
			return conn;
		} else {
			perror("ERROR: accept");
			return NULL;
		}

	}
	return NULL;
#endif
}
// The server and client have to rely on
// certain interprocess communication schemes
// to exchange the WSAPROTOCOL_INFO needed for
// duplicating the socket.  In this sample,
// we use momory mapped files.
BOOL DispatchChild(SOCKET ClientSock, char *pszChildProcName)
{
    char szChildComandLineBuf[MAX_PATH];
    char szFileMappingObj[MAX_PATH];
    BOOL bResult = TRUE;
    STARTUPINFO siParent;
    PROCESS_INFORMATION piChild;
    char szParentEventName[MAX_PATH];
    char szChildEventName[MAX_PATH];

    ZeroMemory(&siParent, sizeof(siParent));
    siParent.cb = sizeof(siParent);
    siParent.dwFlags = STARTF_USECOUNTCHARS;
    siParent.dwXCountChars = 10 * MAX_PATH;
    siParent.dwYCountChars = MAX_PATH;

    // Compose a name for the memory mappled file.
    sprintf_s(szFileMappingObj,
              MAX_PATH,
              "%s%i",
              FILE_MAPPING_BASE_NAME,
              nChildProcCount++);

    sprintf_s(szParentEventName, MAX_PATH,"%s%s", szFileMappingObj, PARENT);
    sprintf_s(szChildEventName, MAX_PATH,"%s%s", szFileMappingObj, CHILD);

    // Create an event to signal the child
    // that the protocol info is set
    if ((ghParentFileMappingEvent = CreateEvent(NULL, TRUE, FALSE, szParentEventName)) == NULL)
    {
        fprintf(stderr, "\nCreateEvent() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Create an event to for the child to signal the
    // parent that the protocol info can be released
    if ((ghChildFileMappingEvent = CreateEvent(NULL, TRUE, FALSE, szChildEventName)) == NULL)
    {
        fprintf(stderr, "\nCreateEvent() failed: %d\n", GetLastError());
        CloseHandle(ghParentFileMappingEvent);
        ghParentFileMappingEvent = NULL;
        return FALSE;
    }

    // Set up the child process command line options.
    // The memory mapped file name is passed in as
    // one of the options.
    sprintf_s(szChildComandLineBuf,
              MAX_PATH,
              "%s /c %s",
              pszChildProcName,
              szFileMappingObj);

    if (CreateProcess(NULL,
                szChildComandLineBuf,
                NULL,
                NULL,
                FALSE,
                CREATE_NEW_CONSOLE,
                NULL,
                NULL,
                &siParent,
                &piChild)) 
    {
        WSAPROTOCOL_INFO ProtocolInfo;
        int nError;
        LPVOID lpView;
        int nStructLen = sizeof(WSAPROTOCOL_INFO);

        // Get the protocol information
        // to be used to duplicate the socket
        if (WSADuplicateSocket(ClientSock,
                    piChild.dwProcessId,
                    &ProtocolInfo) == SOCKET_ERROR)
        {
            fprintf(stderr, "WSADuplicateSocket(): failed. Error = %d\n", WSAGetLastError());	
            DoCleanup();
            exit(1);
        }

        // Set the protocol information in a
        // memory mapped file for the child to use
        ghMMFileMap = CreateFileMapping(INVALID_HANDLE_VALUE,
                NULL,
                PAGE_READWRITE,
                0,
                nStructLen,
                szFileMappingObj);

        if (ghMMFileMap != NULL)
        {
            if ((nError = GetLastError()) == ERROR_ALREADY_EXISTS)
                fprintf(stderr, "CreateFileMapping(): mappping file already exists\n");
            else
            {
                lpView = MapViewOfFile(ghMMFileMap,
                        FILE_MAP_READ | FILE_MAP_WRITE,
                        0, 0, 0);

                if (lpView != NULL)
                {
                    memcpy(lpView, &ProtocolInfo, nStructLen);
                    UnmapViewOfFile(lpView);

                    // Signal the child the protocol infomation is set
                    SetEvent(ghParentFileMappingEvent);
                    // Wait the child to signal that the protocol
                    // infomation can be released now
                    if (WaitForSingleObject(ghChildFileMappingEvent, 2000) == WAIT_OBJECT_0)
                    {
                        fprintf(stderr, "WaitForSingleObject() failed: %d\n", GetLastError());
                        DoCleanup();
                        exit(1);
                    }
                }
                else
                {
                    fprintf(stderr, "MapViewOfFile() failed: %d\n", GetLastError());
                    bResult = FALSE;
                }
            }

            CloseHandle(ghMMFileMap);
            ghMMFileMap = NULL;
        }
        else
        {
            fprintf(stderr, "CreateFileMapping() failed: %d\n", GetLastError());
            bResult = FALSE;
        }

        CloseHandle(piChild.hThread);
        CloseHandle(piChild.hProcess);
    }
    else
    {
        printf("\nCreate child process failed!!!\n");
        bResult = FALSE;
    }

    if (ghParentFileMappingEvent != NULL) 
    {
        CloseHandle(ghParentFileMappingEvent);
        ghParentFileMappingEvent = NULL;
    }

    if (ghChildFileMappingEvent != NULL) 
    {
        CloseHandle(ghChildFileMappingEvent);
        ghChildFileMappingEvent = NULL;
    }

    return bResult;
}
Example #7
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
	int nItemCount;
	int nSelected;
	int *nIndexes;
	BOOL bFlag;
	WCHAR *pszFile;
	WCHAR *handle;
	WCHAR *token;
	Image *imgCurrent;
	Image out;

	switch (iMessage)
	{
		case WM_CREATE:
			HANDLE hToken;

			viewer.changeCaption(L"Preview");

			//Create Controls
			hListLayer = CreateWindow(L"ListBox", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL | LBS_EXTENDEDSEL | LBS_HASSTRINGS | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT, 0, 80, 240, 420, hWnd, (HMENU)ID_LAYER_LIST, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonStart = CreateWindow(L"Button", L"Start", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 0, 0, 80, 40, hWnd, (HMENU)ID_START_BUTTON, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonSave = CreateWindow(L"Button", L"Save Selected in merged file", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 80, 0, 80, 40, hWnd, (HMENU)ID_SAVE_BUTTON, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonSaveAll = CreateWindow(L"Button", L"Save All in individual file", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 160, 0, 80, 40, hWnd, (HMENU)ID_SAVE_ALL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonResetAll = CreateWindow(L"Button", L"Erase All", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 0, 40, 80, 40, hWnd, (HMENU)ID_RESET_ALL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonResetSelected = CreateWindow(L"Button", L"Erase Selected", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 80, 40, 80, 40, hWnd, (HMENU)ID_RESET_SEL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonResetUnselected = CreateWindow(L"Button", L"Erase Unelected", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 160, 40, 80, 40, hWnd, (HMENU)ID_RESET_UNSEL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);

			hFont = CreateFont(16, 0, 0, 0, 400, 0, 0, 0, DEFAULT_CHARSET, 3, 2, 1, FF_ROMAN, L"Segoe UI");

			SendMessage(hListLayer, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonStart, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonSave, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonSaveAll, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonResetAll, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonResetSelected, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonResetUnselected, WM_SETFONT, (WPARAM)hFont, TRUE);

			//Create Events
			hAttachSucceeded = CreateEvent(NULL, TRUE, FALSE, NULL);
			hDebugEnd = CreateEvent(NULL, TRUE, FALSE, NULL);
			hDebugInit = CreateEvent(NULL, TRUE, FALSE, NULL);

			//Adjust Privileges
			if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
			{
				if (SetPrivilege(hToken, SE_DEBUG_NAME, TRUE))
					return 0;
				else
					MessageBox(hWnd, L"Fail to get debug privilege!!", L"Error", MB_OK | MB_ICONERROR);
			}
			else
				MessageBox(hWnd, L"Fail to get process token!!", L"Error", MB_OK | MB_ICONERROR);

			SendMessage(hWnd, WM_DESTROY, 0, 0);

			return 0;
		case WM_ACTIVATE:
			if (wParam == WA_CLICKACTIVE)
			{
				viewer.foreground();
				SetForegroundWindow(hWnd);
				SetFocus(hListLayer);
			}
			return 0;
		case WM_COMMAND:
			switch (LOWORD(wParam))
			{
				case ID_START_BUTTON:
					if (!bStarted)
					{
						hAokanaWnd = FindAokana(&dwThreadID, &dwProcessID);

						if (dwThreadID != 0)
						{
							hDebugThread = CreateThread(NULL, 0, DebugThread, NULL, 0, NULL);

							WaitForSingleObject(hDebugInit, INFINITE);
							if (WaitForSingleObject(hAttachSucceeded, 0) != WAIT_OBJECT_0)
							{
								SetEvent(hDebugEnd);
								MessageBox(hWnd, L"Fail to attach process!!", L"Error", MB_OK | MB_ICONERROR);

								break;
							}

							SendMessage(hButtonStart, WM_SETTEXT, 0, (LPARAM)L"Stop");
							bStarted = TRUE;
						}
					}
					else
					{
						SetEvent(hDebugEnd);
						WaitForSingleObject(hDebugThread, INFINITE);

						ResetEvent(hDebugEnd);
						ResetEvent(hDebugInit);
						ResetEvent(hAttachSucceeded);
						CloseHandle(hDebugThread);

						SendMessage(hButtonStart, WM_SETTEXT, 0, (LPARAM)L"Start");
						bStarted = FALSE;
					}
					break;
				case ID_SAVE_BUTTON:
					nItemCount = SendMessage(hListLayer, LB_GETCOUNT, 0, 0);
					nSelected = SendMessage(hListLayer, LB_GETSELCOUNT, 0, 0);

					if (nSelected > 0)
					{
						nIndexes = (int *)calloc(nSelected, sizeof(int));

						SendMessage(hListLayer, LB_GETSELITEMS, nSelected, (LPARAM)nIndexes);

						memset(&out, 0, sizeof(Image));

						for (int i = nSelected - 1; i >= 0; i--)
						{
							imgCurrent = (Image *)SendMessage(hListLayer, LB_GETITEMDATA, nIndexes[i], 0);

							if (imgCurrent == NULL)
								continue;

							if (i == nSelected - 1)
							{
								out.data = (PIXEL *)calloc(imgCurrent->width * imgCurrent->height, sizeof(PIXEL));
								out.width = imgCurrent->width;
								out.height = imgCurrent->height;
							}

							if (imgCurrent->width == out.width && imgCurrent->height == out.height)
								pixeloverlay(out.width, out.height, out.data, imgCurrent->data, out.data);
						}

						saveDialog(hWnd, out);

						free(nIndexes);
						free(out.data);
					}
					break;
				case ID_SAVE_ALL:
					nItemCount = SendMessage(hListLayer, LB_GETCOUNT, 0, 0);

					if (nItemCount > 0)
					{
						if (selectFolder(hWnd, pszFolder))
						{
							pszFile = (WCHAR *)calloc(256, sizeof(WCHAR));

							for (int i = nItemCount - 1; i >= 0; i--)
							{
								imgCurrent = (Image *)SendMessage(hListLayer, LB_GETITEMDATA, i, 0);
								SendMessage(hListLayer, LB_GETTEXT, i, (LPARAM)pszFile);

								token = wcstok_s(pszFile, L" ", &handle);
								token = wcstok_s(NULL, L" ", &handle);

								if (pszFolder[wcslen(pszFolder) - 1] != '\\')
									wcscat_s(pszFolder, L"\\");

								nSelected = wcslen(pszFolder);	//Position of '\' + 1

								wcscat_s(pszFolder, token);
								wcscat_s(pszFolder, L".png");
								saveImage(*imgCurrent, pszFolder);

								pszFolder[nSelected] = 0;
							}

							free(pszFile);
						}
					}
					break;
				case ID_LAYER_LIST:
					if (HIWORD(wParam) == LBN_SELCHANGE)
					{
						nItemCount = SendMessage(hListLayer, LB_GETCOUNT, 0, 0);
						nSelected = SendMessage(hListLayer, LB_GETSELCOUNT, 0, 0);

						if (nSelected > 0)
						{
							nIndexes = (int *)calloc(nSelected, sizeof(int));

							SendMessage(hListLayer, LB_GETSELITEMS, nSelected, (LPARAM)nIndexes);

							for (int i = nSelected - 1; i >= 0; i--)
							{
								imgCurrent = (Image *)SendMessage(hListLayer, LB_GETITEMDATA, nIndexes[i], 0);

								if (imgCurrent == NULL)
									continue;

								if (i == nSelected - 1)
									viewer.create(imgCurrent->width, imgCurrent->height);

								if (imgCurrent->width == viewer.getwidth() && imgCurrent->height == viewer.getheight())
									viewer.overlay(imgCurrent->data);
							}

							viewer.show();

							free(nIndexes);
						}
						else
							viewer.hide();
					}
					break;
				case ID_RESET_ALL:
					nItemCount = SendMessage(hListLayer, LB_GETCOUNT, 0, 0);
					for (int i = 0; i < nItemCount; i++)
					{
						imgCurrent = (Image *)SendMessage(hListLayer, LB_GETITEMDATA, i, 0);
						free(imgCurrent->data);
						free(imgCurrent);
					}
					SendMessage(hListLayer, LB_RESETCONTENT, 0, 0);
					viewer.hide();
					break;
				case ID_RESET_SEL:
					nItemCount = SendMessage(hListLayer, LB_GETCOUNT, 0, 0);
					nSelected = SendMessage(hListLayer, LB_GETSELCOUNT, 0, 0);

					if (nSelected > 0)
					{
						nIndexes = (int *)calloc(nSelected, sizeof(int));

						SendMessage(hListLayer, LB_GETSELITEMS, nSelected, (LPARAM)nIndexes);

						for (int i = nSelected - 1; i >= 0; i--)
						{
							imgCurrent = (Image *)SendMessage(hListLayer, LB_GETITEMDATA, nIndexes[i], 0);
							free(imgCurrent->data);
							free(imgCurrent);
							SendMessage(hListLayer, LB_DELETESTRING, nIndexes[i], 0);
						}

						free(nIndexes);
						viewer.hide();
					}
					break;
				case ID_RESET_UNSEL:
					nItemCount = SendMessage(hListLayer, LB_GETCOUNT, 0, 0);
					nSelected = SendMessage(hListLayer, LB_GETSELCOUNT, 0, 0);

					if (nSelected > 0)
					{
						nIndexes = (int *)calloc(nSelected, sizeof(int));

						SendMessage(hListLayer, LB_GETSELITEMS, nSelected, (LPARAM)nIndexes);

						for (int i = nItemCount - 1; i >= 0; i--)
						{
							bFlag = FALSE;

							for (int j = nSelected - 1; j >= 0; j--)
								if (i == nIndexes[j])
									bFlag = TRUE;

							if (!bFlag)
							{
								imgCurrent = (Image *)SendMessage(hListLayer, LB_GETITEMDATA, i, 0);
								free(imgCurrent->data);
								free(imgCurrent);
								SendMessage(hListLayer, LB_DELETESTRING, i, 0);
							}
						}

						free(nIndexes);
					}
					break;
			}
			return 0;
		case WM_DESTROY:
			if (bStarted)
				SendMessage(hWnd, WM_COMMAND, ID_START_BUTTON, 0);

			SendMessage(hWnd, WM_COMMAND, ID_RESET_ALL, 0);

			CloseHandle(hAttachSucceeded);
			CloseHandle(hDebugEnd);

			DeleteObject(hFont);

			PostQuitMessage(0);
			return 0;
	}

	return DefWindowProc(hWnd, iMessage, wParam, lParam);
}
Example #8
0
int APIENTRY _tWinMain(HINSTANCE hinst,	HINSTANCE foo1, LPTSTR foo2, int foo3) {
	MSG msg;
	WNDCLASSEX wcex = {sizeof(wcex)};
	HANDLE htray;
	HMENU hmenu;
	MENUITEMINFO mi = {sizeof(mi)};
	INITCOMMONCONTROLSEX icex;
	RECT rect;
	int style;
	HWND hwnd;

	wcex.lpfnWndProc = WndProc;
	wcex.lpszClassName = WINDOW_CLASS;
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	RegisterClassEx(&wcex);

	icex.dwSize = sizeof(icex);
	icex.dwICC = ICC_DATE_CLASSES;
	InitCommonControlsEx(&icex);

	hwnd = CreateWindowEx(WS_EX_NOACTIVATE | WS_EX_TOPMOST, WINDOW_CLASS, WINDOW_TITLE, 0,
		0, 0, 0, 0, NULL, NULL, hinst, NULL);
	if (!hwnd) return 1;
	style = GetWindowLong(hwnd, GWL_STYLE);
	if (style & WS_CAPTION)  { 
		style ^= WS_CAPTION;
		SetWindowLong(hwnd, GWL_STYLE, style);
		SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
	}

	hcal = CreateWindowEx(0, MONTHCAL_CLASS, _T(""),
		WS_CHILD | WS_VISIBLE | MCS_NOTODAY | MCS_NOTRAILINGDATES | MCS_SHORTDAYSOFWEEK | MCS_NOSELCHANGEONNAV,
		0, 0, 0, 0, hwnd, NULL, hinst, NULL);
	MonthCal_GetMinReqRect(hcal, &rect);
	SetWindowPos(hcal, NULL, 0, 0, rect.right, rect.bottom, SWP_NOZORDER | SWP_NOMOVE);
	SetWindowPos(hwnd, NULL, 0, 0, rect.right, rect.bottom, SWP_NOZORDER | SWP_NOMOVE);

	tti.hwnd = hwnd;
	tti.hcal = hcal;
	tti.hnotify = CreateEvent(NULL, TRUE, FALSE, NULL);
	tti.exit = FALSE;
	htray = CreateThread(NULL, 0, &TrayThreadProc, &tti, 0, NULL);
	if (!htray) return 1;

	hsubmenu = CreateMenu();
	mi.fMask = MIIM_STRING | MIIM_ID;
	mi.wID = 1;
	mi.dwTypeData = EXIT_STRING;
	InsertMenuItem(hsubmenu, 0, TRUE, &mi);
	hmenu = CreateMenu();
	mi.fMask = MIIM_SUBMENU;
	mi.hSubMenu = hsubmenu;
	InsertMenuItem(hmenu, 0, TRUE, &mi);

	WM_TASKBARCREATED = RegisterWindowMessageA(_T("TaskbarCreated"));
	
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	DestroyMenu(hmenu);
	DestroyMenu(hsubmenu);

	WaitForSingleObject(htray, 1000);
	CloseHandle(htray);

	return (int)msg.wParam;
}
void EIO_WatchPort(uv_work_t* req) {
  WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
  data->bytesRead = 0;
  data->disconnected = false;

  // Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout
  // Event MUST be used if program has several simultaneous asynchronous operations
  // on the same handle (i.e. ReadFile and WriteFile)
  HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

  while(true) {
    OVERLAPPED ov = {0};
    ov.hEvent = hEvent;

    // Start read operation - synchrounous or asynchronous
    DWORD bytesReadSync = 0;
    if(!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {
      data->errorCode = GetLastError();
      if(data->errorCode != ERROR_IO_PENDING) {
        // Read operation error
        if(data->errorCode == ERROR_OPERATION_ABORTED) {
          data->disconnected = true;
        }
        else {
          ErrorCodeToString("Reading from COM port (ReadFile)", data->errorCode, data->errorString);
        }
        break;
      }

      // Read operation is asynchronous and is pending
      // We MUST wait for operation completion before deallocation of OVERLAPPED struct
      // or read data buffer

      // Wait for async read operation completion or timeout
      DWORD bytesReadAsync = 0;
      if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {
        // Read operation error
        data->errorCode = GetLastError();
        if(data->errorCode == ERROR_OPERATION_ABORTED) {
          data->disconnected = true;
        }
        else {
          ErrorCodeToString("Reading from COM port (GetOverlappedResult)", data->errorCode, data->errorString);
        }
        break;
      }
      else {
        // Read operation completed asynchronously
        data->bytesRead = bytesReadAsync;
      }
    }
    else {
      // Read operation completed synchronously
      data->bytesRead = bytesReadSync;
    }

    // Return data received if any
    if(data->bytesRead > 0) {
      break;
    }
  }

  CloseHandle(hEvent);
}
Example #10
0
static int
winmm_stream_init(cubeb * context, cubeb_stream ** stream, char const * stream_name,
                  cubeb_devid input_device,
                  cubeb_stream_params * input_stream_params,
                  cubeb_devid output_device,
                  cubeb_stream_params * output_stream_params,
                  unsigned int latency,
                  cubeb_data_callback data_callback,
                  cubeb_state_callback state_callback,
                  void * user_ptr)
{
  MMRESULT r;
  WAVEFORMATEXTENSIBLE wfx;
  cubeb_stream * stm;
  int i;
  size_t bufsz;

  XASSERT(context);
  XASSERT(stream);

  if (input_stream_params) {
    /* Capture support not yet implemented. */
    return CUBEB_ERROR_NOT_SUPPORTED;
  }

  if (input_device || output_device) {
    /* Device selection not yet implemented. */
    return CUBEB_ERROR_DEVICE_UNAVAILABLE;
  }

  *stream = NULL;

  memset(&wfx, 0, sizeof(wfx));
  if (output_stream_params->channels > 2) {
    wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
    wfx.Format.cbSize = sizeof(wfx) - sizeof(wfx.Format);
  } else {
    wfx.Format.wFormatTag = WAVE_FORMAT_PCM;
    if (output_stream_params->format == CUBEB_SAMPLE_FLOAT32LE) {
      wfx.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
    }
    wfx.Format.cbSize = 0;
  }
  wfx.Format.nChannels = output_stream_params->channels;
  wfx.Format.nSamplesPerSec = output_stream_params->rate;

  /* XXX fix channel mappings */
  wfx.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;

  switch (output_stream_params->format) {
  case CUBEB_SAMPLE_S16LE:
    wfx.Format.wBitsPerSample = 16;
    wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
    break;
  case CUBEB_SAMPLE_FLOAT32LE:
    wfx.Format.wBitsPerSample = 32;
    wfx.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
    break;
  default:
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  wfx.Format.nBlockAlign = (wfx.Format.wBitsPerSample * wfx.Format.nChannels) / 8;
  wfx.Format.nAvgBytesPerSec = wfx.Format.nSamplesPerSec * wfx.Format.nBlockAlign;
  wfx.Samples.wValidBitsPerSample = wfx.Format.wBitsPerSample;

  EnterCriticalSection(&context->lock);
  /* CUBEB_STREAM_MAX is a horrible hack to avoid a situation where, when
     many streams are active at once, a subset of them will not consume (via
     playback) or release (via waveOutReset) their buffers. */
  if (context->active_streams >= CUBEB_STREAM_MAX) {
    LeaveCriticalSection(&context->lock);
    return CUBEB_ERROR;
  }
  context->active_streams += 1;
  LeaveCriticalSection(&context->lock);

  stm = calloc(1, sizeof(*stm));
  XASSERT(stm);

  stm->context = context;

  stm->params = *output_stream_params;

  stm->data_callback = data_callback;
  stm->state_callback = state_callback;
  stm->user_ptr = user_ptr;
  stm->written = 0;

  if (latency < context->minimum_latency) {
    latency = context->minimum_latency;
  }

  bufsz = (size_t) (stm->params.rate / 1000.0 * latency * bytes_per_frame(stm->params) / NBUFS);
  if (bufsz % bytes_per_frame(stm->params) != 0) {
    bufsz += bytes_per_frame(stm->params) - (bufsz % bytes_per_frame(stm->params));
  }
  XASSERT(bufsz % bytes_per_frame(stm->params) == 0);

  stm->buffer_size = bufsz;

  InitializeCriticalSection(&stm->lock);

  stm->event = CreateEvent(NULL, FALSE, FALSE, NULL);
  if (!stm->event) {
    winmm_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  stm->soft_volume = -1.0;

  /* winmm_buffer_callback will be called during waveOutOpen, so all
     other initialization must be complete before calling it. */
  r = waveOutOpen(&stm->waveout, WAVE_MAPPER, &wfx.Format,
                  (DWORD_PTR) winmm_buffer_callback, (DWORD_PTR) stm,
                  CALLBACK_FUNCTION);
  if (r != MMSYSERR_NOERROR) {
    winmm_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  r = waveOutPause(stm->waveout);
  if (r != MMSYSERR_NOERROR) {
    winmm_stream_destroy(stm);
    return CUBEB_ERROR;
  }


  for (i = 0; i < NBUFS; ++i) {
    WAVEHDR * hdr = &stm->buffers[i];

    hdr->lpData = calloc(1, bufsz);
    XASSERT(hdr->lpData);
    hdr->dwBufferLength = bufsz;
    hdr->dwFlags = 0;

    r = waveOutPrepareHeader(stm->waveout, hdr, sizeof(*hdr));
    if (r != MMSYSERR_NOERROR) {
      winmm_stream_destroy(stm);
      return CUBEB_ERROR;
    }

    winmm_refill_stream(stm);
  }

  *stream = stm;

  return CUBEB_OK;
}
Example #11
0
static void test_capture_buffer(LPDIRECTSOUNDCAPTURE dsco,
				LPDIRECTSOUNDCAPTUREBUFFER dscbo, int record)
{
    HRESULT rc;
    DSCBCAPS dscbcaps;
    WAVEFORMATEX wfx;
    DWORD size,status;
    capture_state_t state;
    int i, ref;

    /* Private dsound.dll: Error: Invalid caps pointer */
    rc=IDirectSoundCaptureBuffer_GetCaps(dscbo,0);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetCaps() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    /* Private dsound.dll: Error: Invalid caps pointer */
    dscbcaps.dwSize=0;
    rc=IDirectSoundCaptureBuffer_GetCaps(dscbo,&dscbcaps);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetCaps() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    dscbcaps.dwSize=sizeof(dscbcaps);
    rc=IDirectSoundCaptureBuffer_GetCaps(dscbo,&dscbcaps);
    ok(rc==DS_OK,"IDirectSoundCaptureBuffer_GetCaps() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc==DS_OK && winetest_debug > 1) {
	trace("    Caps: size = %d flags=0x%08x buffer size=%d\n",
	    dscbcaps.dwSize,dscbcaps.dwFlags,dscbcaps.dwBufferBytes);
    }

    /* Query the format size. Note that it may not match sizeof(wfx) */
    /* Private dsound.dll: Error: Either pwfxFormat or pdwSizeWritten must
     * be non-NULL */
    rc=IDirectSoundCaptureBuffer_GetFormat(dscbo,NULL,0,NULL);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetFormat() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    size=0;
    rc=IDirectSoundCaptureBuffer_GetFormat(dscbo,NULL,0,&size);
    ok(rc==DS_OK && size!=0,"IDirectSoundCaptureBuffer_GetFormat() should "
       "have returned the needed size: rc=%s, size=%d\n",
       DXGetErrorString8(rc),size);

    rc=IDirectSoundCaptureBuffer_GetFormat(dscbo,&wfx,sizeof(wfx),NULL);
    ok(rc==DS_OK,"IDirectSoundCaptureBuffer_GetFormat() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc==DS_OK && winetest_debug > 1) {
	trace("    Format: tag=0x%04x %dx%dx%d avg.B/s=%d align=%d\n",
	      wfx.wFormatTag,wfx.nSamplesPerSec,wfx.wBitsPerSample,
	      wfx.nChannels,wfx.nAvgBytesPerSec,wfx.nBlockAlign);
    }

    /* Private dsound.dll: Error: Invalid status pointer */
    rc=IDirectSoundCaptureBuffer_GetStatus(dscbo,0);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetStatus() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    rc=IDirectSoundCaptureBuffer_GetStatus(dscbo,&status);
    ok(rc==DS_OK,"IDirectSoundCaptureBuffer_GetStatus() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc==DS_OK && winetest_debug > 1) {
	trace("    Status=0x%04x\n",status);
    }

    ZeroMemory(&state, sizeof(state));
    state.dscbo=dscbo;
    state.wfx=&wfx;
    state.buffer_size = dscbcaps.dwBufferBytes;
    for (i = 0; i < NOTIFICATIONS; i++)
	state.event[i] = CreateEvent( NULL, FALSE, FALSE, NULL );
    state.size = dscbcaps.dwBufferBytes / NOTIFICATIONS;

    rc=IDirectSoundCaptureBuffer_QueryInterface(dscbo,&IID_IDirectSoundNotify,
                                                (void **)&(state.notify));
    ok((rc==DS_OK)&&(state.notify!=NULL),
       "IDirectSoundCaptureBuffer_QueryInterface() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc!=DS_OK)
	return;

    for (i = 0; i < NOTIFICATIONS; i++) {
	state.posnotify[i].dwOffset = (i * state.size) + state.size - 1;
	state.posnotify[i].hEventNotify = state.event[i];
    }

    rc=IDirectSoundNotify_SetNotificationPositions(state.notify,NOTIFICATIONS,
                                                   state.posnotify);
    ok(rc==DS_OK,"IDirectSoundNotify_SetNotificationPositions() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc!=DS_OK)
	return;

    ref=IDirectSoundNotify_Release(state.notify);
    ok(ref==0,"IDirectSoundNotify_Release(): has %d references, should have "
       "0\n",ref);
    if (ref!=0)
	return;

    if (record) {
	rc=IDirectSoundCaptureBuffer_Start(dscbo,DSCBSTART_LOOPING);
	ok(rc==DS_OK,"IDirectSoundCaptureBuffer_Start() failed: %s\n",
           DXGetErrorString8(rc));
	if (rc!=DS_OK)
	    return;

	rc=IDirectSoundCaptureBuffer_GetStatus(dscbo,&status);
	ok(rc==DS_OK,"IDirectSoundCaptureBuffer_GetStatus() failed: %s\n",
           DXGetErrorString8(rc));
	ok(status==(DSCBSTATUS_CAPTURING|DSCBSTATUS_LOOPING),
           "GetStatus: bad status: %x\n",status);
	if (rc!=DS_OK)
	    return;

	/* wait for the notifications */
	for (i = 0; i < (NOTIFICATIONS * 2); i++) {
	    rc=WaitForMultipleObjects(NOTIFICATIONS,state.event,FALSE,3000);
	    ok(rc==(WAIT_OBJECT_0+(i%NOTIFICATIONS)),
               "WaitForMultipleObjects failed: 0x%x\n",rc);
	    if (rc!=(WAIT_OBJECT_0+(i%NOTIFICATIONS))) {
		ok((rc==WAIT_TIMEOUT)||(rc==WAIT_FAILED),
                   "Wrong notification: should be %d, got %d\n",
		    i%NOTIFICATIONS,rc-WAIT_OBJECT_0);
	    }
	    if (!capture_buffer_service(&state))
		break;
	}

	rc=IDirectSoundCaptureBuffer_Stop(dscbo);
	ok(rc==DS_OK,"IDirectSoundCaptureBuffer_Stop() failed: %s\n",
           DXGetErrorString8(rc));
	if (rc!=DS_OK)
	    return;
    }
}
Example #12
0
DWORD mmp_thread( DWORD dw ) { // open device

	int i;
	int nextbuf;
	
	short* sampledata;
	WAVEFORMATEX waveformat;
	WAVEHDR waveheader[NUMBUFS];

	if (UseDevice==(unsigned int)-1) return 0;

	SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST);

	weHaveTerminated=0;
	waveformat.wFormatTag=WAVE_FORMAT_PCM;
	waveformat.nChannels=2;
	waveformat.wBitsPerSample=16;
	waveformat.nSamplesPerSec=44100;
	waveformat.nBlockAlign=(waveformat.nChannels*waveformat.wBitsPerSample)/8;
    waveformat.nAvgBytesPerSec=waveformat.nSamplesPerSec*waveformat.nBlockAlign;
	waveformat.cbSize=0;

	waveOutOpen(&audiodev,UseDevice,&waveformat,(unsigned int)bufferdone,0,CALLBACK_FUNCTION);
#ifdef MMPDEBUG
	printf("audiodev: %X\n",audiodev);
#endif

	musicevent=CreateEvent(NULL,FALSE,FALSE,"WinUsmPlayer");
	sampledata=(short*)GlobalAlloc(MEM_COMMIT,BUFLENGTH*NUMBUFS);

#ifdef MMPDEBUG
	printf("%X, %X\n",sampledata,sampledata+BUFLENGTH*NUMBUFS);
#endif

	for (i=0;i<NUMBUFS;i++)
	{
		//printf("preparing %ld bytes at %X\n", BUFLENGTH, sampledata+BUFLENGTH*i);
		waveheader[i].lpData=(char*)sampledata+i*BUFLENGTH;
		waveheader[i].dwFlags=0;
		waveheader[i].dwBufferLength = BUFLENGTH;
		waveOutPrepareHeader(audiodev,&waveheader[i],sizeof(WAVEHDR));
		mmp_generate( sampledata+(i*BUFLENGTH/2), BUFLENGTH>>1 );
		waveOutWrite(audiodev,&waveheader[i],sizeof(WAVEHDR));
	}

	nextbuf=0;
	while(playing)
    {
        IXA_PlayerActive=0;
		if (WaitForSingleObject(musicevent,1000)==WAIT_TIMEOUT)
		{
//			WinUsmPlayPause();
//			WinUsmPlayRestart();
		}

        IXA_PlayerActive=1;
		for (i=0;i<NUMBUFS;i++)
        {
			if ((waveheader[i].dwFlags & WHDR_DONE) && nextbuf==i)
			{
				waveOutUnprepareHeader(audiodev,&waveheader[i],sizeof(WAVEHDR));
				mmp_generate( sampledata+(i*BUFLENGTH/2), BUFLENGTH>>1 );
				waveOutPrepareHeader(audiodev,&waveheader[i],sizeof(WAVEHDR));
				waveOutWrite(audiodev,&waveheader[i],sizeof(WAVEHDR));
				nextbuf++;
				if (nextbuf==NUMBUFS) nextbuf=0;
			}
		}
	}
Example #13
0
// Função relativa à thread do servidor TCP. é o intermédio entre o client OPC e o client TCP,
// trocando assim mensagens constantemente entre ambos os clientes.
DWORD WINAPI TCPServer(LPVOID id) {

    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;

	char recvbuf[DEFAULT_BUFLEN];
    
	int recvbuflen = DEFAULT_BUFLEN;
	int seqdados = 0;

	char ack_string[13];
	char ack_data[14];

    char msgreq[TAMMSGREQ+1];

    char msgsp[TAMMSGSP+1];

	Monitor<vector<int>> mSocket(VERB_ON);

	char dados2[55];
	char dados1[100];

	LPTSTR MailSlotDados = TEXT("\\\\.\\mailslot\\mailslotDados");	//Inicializa mailslot Dados (caminho da troca de dados de processo)
	LPTSTR MailSlotSP = TEXT("\\\\.\\mailslot\\mailslotSP");		//Inicializa mailslot SP (caminho da troca de setpoints)

	HANDLE hSlotDados = CreateMailslot(MailSlotDados,		//Criação do mailslot de dados
															//Código adaptado do MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365785%28v=vs.85%29.aspx
        0,                             // no maximum message size 
        MAILSLOT_WAIT_FOREVER,         // no time-out for operations 
        (LPSECURITY_ATTRIBUTES) NULL); // default security
 
    if (hSlotDados == INVALID_HANDLE_VALUE) 
    { 
        printf("CreateMailslot failed with %d\n", GetLastError());
        return FALSE; 
    } 
    else printf("MailslotDados created successfully.\n"); 

	HANDLE hFileSP = CreateFile(MailSlotSP,			// Abertura de arquivo para leitura do mailslot de setpoints
													// Código adaptado do MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365802%28v=vs.85%29.aspx
		 GENERIC_WRITE, 
		 FILE_SHARE_READ,
		 (LPSECURITY_ATTRIBUTES) NULL, 
		 OPEN_EXISTING, 
		 FILE_ATTRIBUTE_NORMAL, 
		 (HANDLE) NULL); 

	if (hFileSP == INVALID_HANDLE_VALUE)  
		printf("CreateFile failed with %d.\n", GetLastError());
	else
		printf("MailSlotSP File criado.\n");

		// Criação de um evento para sincronizar a leitura do mailslot de setpoints.
		// Este evento será setado após os setpoints serem escritos no arquivo,
		// desta forma, o client OPC apenas vai ler deste quando tal ocorrer.
	   HANDLE hMSWrite = CreateEvent(NULL, FALSE, FALSE, TEXT("hMSWrite"));

	 if (hMSWrite == INVALID_HANDLE_VALUE)  
		printf("Handle hMSWrite failed with %d.\n", GetLastError());
	else
		printf("hMSWrite, handle criado.\n");


	// Daqui em diante, grande parte do código de inicialização de um servidor TCP foi retirado do MSDN
	// https://msdn.microsoft.com/pt-br/library/windows/desktop/ms737593%28v=vs.85%29.aspx
	// A partir do código acima, alterações foram feitas para que a comunicação também com o Cliente OPC ocorresse
	// e também para que reconexões possam ser feitas. O servidor continua a tratar apenas um cliente simultâneo,
	// visto que não era previsto múltiplos acessos pela especificação do trabalho prático (apenas um computador do processo)

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
	 printf("TCP Server inicializado.\n");//Linha adicionada

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }
	 printf("Endereco resolvido.\n");//Linha adicionada

	 

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }
	 printf("Socket TCP criado.\n");//Linha adicionada

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
	 printf("Socket TCP de escuta inicializado.\n");//Linha adicionada

    freeaddrinfo(result);

   while(1){ // Este While permite que após uma conexão ser finalizada, o servidor volte a
			 // escutar por uma nova conexão.

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
	 printf("Socket TCP ouvindo.\n");//Linha adicionada

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
	 printf("Cliente conectado.\n"); //Linha adicionada
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }


	// Daqui para baixo grande parte do código foi alterado,
	// visando a comunicação bilateral com TCP Cliente e OPC Cliente
    do {

		// Receber pedido de dados
        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0); 

			// Testa se uma mensagem chegou
	        if (iResult > 0) {

				// Analise da mensagem. Requisicao de pacotes?
				if (iResult == TAMMSGREQ){
					strncpy_s(msgreq, sizeof(msgreq), recvbuf, iResult);
					// Confirmacao de requisicao. Testa tag inicial
					if (strncmp(msgreq, "100000", 6) == 0){
						printf("Requisicao de pacotes recebida!\nMsg recebida: %s\nBytes recebidos: %d\n", msgreq, iResult);

						// Caso a mensagem recebida for uma requisicao de pacotes, aguarda que estes sejam enviados pelo cliente OPC
						// e os repassa ao cliente TCP
						ReadSlot(hSlotDados,recvbuf);

						// Monta a mensagem com os dados mais uma tag identificadora e uma contagem sequencial
						sprintf_s(dados1,"200000|%.6d|%s",seqdados,recvbuf);

						// Envia dados em resposta ao pedido
						memcpy_s(&dados2, 55, dados1, 55);
						iSendResult = send( ClientSocket, dados2, 55, 0 );

						// Incrementa sequenciador
						seqdados++;

						// Teste do envio
						if (iSendResult == SOCKET_ERROR) {
							printf("send failed with error: %d\n", WSAGetLastError());
							iResult = 0;
						}

					} // Tag inicial desconhecida
					else {
						printf("Mensagem nao identificada recebida.\nMsg recebida: %s\nBytes recebidos: %d\n", msgreq, iResult);
						iResult = 0;
							}
				} //IF result = request


				// Analise da mensagem. Envio de set points?
				else if (iResult == TAMMSGSP){
					strncpy_s(msgsp, sizeof(msgsp), recvbuf, iResult);

					// Confirmacao da chegada de set points. Testa tag inicial
					if (strncmp(msgsp, "300000", 6) == 0){
						printf("Set-points recebidos!\nMsg recebida: %s\nBytes recebidos: %d\n", msgsp, iResult);

						// Caso a mensagem recebida for um envio de setpoints, repassa-os ao cliente OPC e sinaliza o envio
						WriteSlot(hFileSP,msgsp);
						SetEvent(hMSWrite);

						// Monta uma nova mensagem e envia um ACK de confirmação ao cliente TCP
						sprintf_s(ack_data,"%s|%c%c%c%c%c%c",ACKDATA,recvbuf[7],recvbuf[8],recvbuf[9],recvbuf[10],recvbuf[11],recvbuf[12]);
						memcpy_s(&ack_string, 13, ack_data, 13);
						iSendResult = send(ClientSocket,ack_string,TAMMSGACK,0);

						// Teste do envio
						if (iSendResult == SOCKET_ERROR) {
							printf("send failed with error: %d\n", WSAGetLastError());
							iResult = 0;
						}

					} // Tag inicial desconhecida
					else {
						printf("Mensagem nao identificada recebida.\nMsg recebida: %s\nBytes recebidos: %d\n", msgreq, iResult);
						iResult = 0;
							}
				} //IF result = sp

			} //IF result > 0

        else if (iResult == 0)
            printf("Connection closing...\n");
        else  {
            printf("recv failed with error: %d\n", WSAGetLastError());
			iResult = 0;
		}


    } while (iResult > 0);
	
	cout << "Aguardando reconexao..." << endl;

}


    // No longer need server socket
    closesocket(ListenSocket); //Inicialização sockets

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
	CloseHandle(hMSWrite);
	CloseHandle(hSlotDados);
	CloseHandle(hFileSP);
    closesocket(ClientSocket);
    WSACleanup();


	return(0);
}
Example #14
0
// Função para leitura de um mailslot. Recebe como parâmetros o handle do mailslot em questão
// e um buffer para receber a mensagem lida.
// Adapatada da função ReadSlot do MSDN:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365785%28v=vs.85%29.aspx
BOOL ReadSlot(HANDLE hSlot, char* outStr)	// Foi adicionado o parâmetro do HANDLE, para poder diferenciar
											// entre os mailslots criados. Foi também adicionado um vetor
											// de saída, para transportar a mensagem.
{ 
    DWORD cbMessage, cMessage, cbRead; 
    BOOL fResult; 
    LPTSTR lpszBuffer; 
    TCHAR achID[80]; 
    DWORD cAllMessages; 
    HANDLE hEvent;
    OVERLAPPED ov;
 
    cbMessage = cMessage = cbRead = 0; 

    hEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("hMailSlot"));
    if( NULL == hEvent )
        return FALSE;
    ov.Offset = 0;
    ov.OffsetHigh = 0;
    ov.hEvent = hEvent;
 
    fResult = GetMailslotInfo( hSlot, // mailslot handle 
        (LPDWORD) NULL,               // no maximum message size 
        &cbMessage,                   // size of next message 
        &cMessage,                    // number of messages 
        (LPDWORD) NULL);              // no read time-out 
 
    if (!fResult) 
    { 
        printf("GetMailslotInfo failed with %d.\n", GetLastError()); 
        return FALSE; 
    } 
 
    if (cbMessage == MAILSLOT_NO_MESSAGE) 
    { 
        printf("Waiting for a message...\n"); 
        return TRUE; 
    } 
 
    cAllMessages = cMessage; 
 
    while (cMessage != 0)  // retrieve all messages
    { 
        // Create a message-number string. 
 
        StringCchPrintf((LPTSTR) achID, 
            80,
            TEXT("\nMessage #%d of %d\n"), 
            cAllMessages - cMessage + 1, 
            cAllMessages); 

        // Allocate memory for the message. 
 
        lpszBuffer = (LPTSTR) GlobalAlloc(GPTR, 
            lstrlen((LPTSTR) achID)*sizeof(TCHAR) + cbMessage); 
        if( NULL == lpszBuffer )
            return FALSE;
        lpszBuffer[0] = '\0'; 
 
        fResult = ReadFile(hSlot, 
            lpszBuffer, 
            cbMessage, 
            &cbRead, 
            &ov); 
 
        if (!fResult) 
        { 
            printf("ReadFile failed with %d.\n", GetLastError()); 
            GlobalFree((HGLOBAL) lpszBuffer); 
            return FALSE; 
        } 
 
        // Concatenate the message and the message-number string. 
 
        StringCbCat(lpszBuffer, 
                    lstrlen((LPTSTR) achID)*sizeof(TCHAR)+cbMessage, 
                    (LPTSTR) achID); 
 
        // Display the message. 
 
        //_tprintf(TEXT("Contents of the mailslot: %s\n"), lpszBuffer); 
 
		strcpy_s(outStr, 100, lpszBuffer);
 
        fResult = GetMailslotInfo(hSlot,  // mailslot handle 
            (LPDWORD) NULL,               // no maximum message size 
            &cbMessage,                   // size of next message 
            &cMessage,                    // number of messages 
            (LPDWORD) NULL);              // no read time-out 
 
        if (!fResult) 
        { 
            printf("GetMailslotInfo failed (%d)\n", GetLastError());
            return FALSE; 
        } 
    } 
    CloseHandle(hEvent);
    return TRUE; 
}
Example #15
0
// Internal API functions
static int wince_init(struct libusb_context *ctx)
{
    int i, r = LIBUSB_ERROR_OTHER;
    HANDLE semaphore;
    TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)

    _stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
    semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
    if (semaphore == NULL) {
        usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
        return LIBUSB_ERROR_NO_MEM;
    }

    // A successful wait brings our semaphore count to 0 (unsignaled)
    // => any concurent wait stalls until the semaphore's release
    if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
        usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
        CloseHandle(semaphore);
        return LIBUSB_ERROR_NO_MEM;
    }

    // NB: concurrent usage supposes that init calls are equally balanced with
    // exit calls. If init is called more than exit, we will not exit properly
    if ( ++concurrent_usage == 0 ) {	// First init?
        // Initialize pollable file descriptors
        init_polling();

        // Load DLL imports
        if (init_dllimports() != LIBUSB_SUCCESS) {
            usbi_err(ctx, "could not resolve DLL functions");
            r = LIBUSB_ERROR_NOT_SUPPORTED;
            goto init_exit;
        }

        // try to open a handle to the driver
        driver_handle = UkwOpenDriver();
        if (driver_handle == INVALID_HANDLE_VALUE) {
            usbi_err(ctx, "could not connect to driver");
            r = LIBUSB_ERROR_NOT_SUPPORTED;
            goto init_exit;
        }

        // Windows CE doesn't have a way of specifying thread affinity, so this code
        // just has  to hope QueryPerformanceCounter doesn't report different values when
        // running on different cores.
        r = LIBUSB_ERROR_NO_MEM;
        for (i = 0; i < 2; i++) {
            timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
            if (timer_request[i] == NULL) {
                usbi_err(ctx, "could not create timer request event %d - aborting", i);
                goto init_exit;
            }
        }
        timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
        if (timer_response == NULL) {
            usbi_err(ctx, "could not create timer response semaphore - aborting");
            goto init_exit;
        }
        timer_mutex = CreateMutex(NULL, FALSE, NULL);
        if (timer_mutex == NULL) {
            usbi_err(ctx, "could not create timer mutex - aborting");
            goto init_exit;
        }
        timer_thread = CreateThread(NULL, 0, wince_clock_gettime_threaded, NULL, 0, NULL);
        if (timer_thread == NULL) {
            usbi_err(ctx, "Unable to create timer thread - aborting");
            goto init_exit;
        }

        // Wait for timer thread to init before continuing.
        if (WaitForSingleObject(timer_response, INFINITE) != WAIT_OBJECT_0) {
            usbi_err(ctx, "Failed to wait for timer thread to become ready - aborting");
            goto init_exit;
        }
    }
    // At this stage, either we went through full init successfully, or didn't need to
    r = LIBUSB_SUCCESS;

init_exit: // Holds semaphore here.
    if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
        if (driver_handle != INVALID_HANDLE_VALUE) {
            UkwCloseDriver(driver_handle);
            driver_handle = INVALID_HANDLE_VALUE;
        }
        if (timer_thread) {
            SetEvent(timer_request[1]); // actually the signal to quit the thread.
            if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
                usbi_warn(ctx, "could not wait for timer thread to quit");
                TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
                // all objects it might have held anyway.
            }
            CloseHandle(timer_thread);
            timer_thread = NULL;
        }
        for (i = 0; i < 2; i++) {
            if (timer_request[i]) {
                CloseHandle(timer_request[i]);
                timer_request[i] = NULL;
            }
        }
        if (timer_response) {
            CloseHandle(timer_response);
            timer_response = NULL;
        }
        if (timer_mutex) {
            CloseHandle(timer_mutex);
            timer_mutex = NULL;
        }
    }

    if (r != LIBUSB_SUCCESS)
        --concurrent_usage; // Not expected to call libusb_exit if we failed.

    ReleaseSemaphore(semaphore, 1, NULL);	// increase count back to 1
    CloseHandle(semaphore);
    return r;
}
Example #16
0
HRESULT CKsIrpTarget::SyncIoctl(
        IN  HANDLE  handle,
        IN  ULONG   ulIoctl,
        IN  PVOID   pvInBuffer,
        IN  ULONG   cbInBuffer,
        OUT PVOID   pvOutBuffer,
        OUT ULONG   cbOutBuffer,
        OUT PULONG  pulBytesReturned)
{
    TRACE_ENTER();
    HRESULT hr = S_OK;
    OVERLAPPED overlapped;
        BOOL fRes = TRUE;
        ULONG ulBytesReturned;

    if (!IsValidHandle(handle))
    {
        hr = E_FAIL;
        DebugPrintf(TRACE_ERROR,TEXT("CKsIrpTarget::SyncIoctl Invalid Handle"));
    }
    
    if (!pulBytesReturned)
    {
        pulBytesReturned = &ulBytesReturned;
    }

    if (SUCCEEDED(hr))
    {
        ZeroMemory(&overlapped,sizeof(overlapped));
        overlapped.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
        if (!overlapped.hEvent)
        {
            hr = E_OUTOFMEMORY;
            DebugPrintf(TRACE_ERROR,TEXT("CKsIrpTarget::SyncIoctl CreateEvent failed"));
        }
        else
        {
            // Flag the event by setting the low-order bit so we
            // don't get completion port notifications.
            // Really! - see the description of the lpOverlapped parameter in
            // the docs for GetQueuedCompletionStatus
            overlapped.hEvent = (HANDLE)((DWORD_PTR)overlapped.hEvent | 0x1);
        }
    }

    if (SUCCEEDED(hr))
    {
        fRes = DeviceIoControl(handle, ulIoctl, pvInBuffer, cbInBuffer, pvOutBuffer, cbOutBuffer, pulBytesReturned, &overlapped);
        if (!fRes)
        {

            DWORD dwError;
            dwError = GetLastError();
            if (ERROR_IO_PENDING == dwError)
            {
                DWORD dwWait;
                // Wait for completion
                dwWait = ::WaitForSingleObject(overlapped.hEvent,INFINITE);
                ASSERT(WAIT_OBJECT_0 == dwWait);
                if (dwWait != WAIT_OBJECT_0)
                {
                    hr = E_FAIL;
                    DebugPrintf(TRACE_ERROR,TEXT("CKsIrpTarget::SyncIoctl WaitForSingleObject failed dwWait:0x%08x"),dwWait);
                }
            }
            else if (((ERROR_INSUFFICIENT_BUFFER == dwError) || (ERROR_MORE_DATA == dwError)) &&
                (IOCTL_KS_PROPERTY == ulIoctl) &&
                (cbOutBuffer == 0))
            {
                hr = S_OK;
                fRes = TRUE;
            }
            else
            {
                hr = E_FAIL;
            }
        }
        if (!fRes) *pulBytesReturned = 0;
        SafeCloseHandle(overlapped.hEvent);
    }
    
    TRACE_LEAVE_HRESULT(hr);
    return hr;
}
Example #17
0
File: winmm.c Project: 9heart/DT3
static ALCenum WinMMOpenPlayback(ALCdevice *pDevice, const ALCchar *deviceName)
{
    WAVEFORMATEX wfexFormat;
    WinMMData *pData = NULL;
    UINT lDeviceID = 0;
    MMRESULT res;
    ALuint i = 0;

    // Find the Device ID matching the deviceName if valid
    if(!deviceName || strcmp(deviceName, woDefault) == 0)
        lDeviceID = WAVE_MAPPER;
    else
    {
        if(!PlaybackDeviceList)
            ProbePlaybackDevices();

        for(i = 0;i < NumPlaybackDevices;i++)
        {
            if(PlaybackDeviceList[i] &&
               strcmp(deviceName, PlaybackDeviceList[i]) == 0)
            {
                lDeviceID = i;
                break;
            }
        }
        if(i == NumPlaybackDevices)
            return ALC_INVALID_VALUE;
    }

    pData = calloc(1, sizeof(*pData));
    if(!pData)
        return ALC_OUT_OF_MEMORY;
    pDevice->ExtraData = pData;

    if(pDevice->FmtChans != DevFmtMono)
    {
        if((pDevice->Flags&DEVICE_CHANNELS_REQUEST) &&
           pDevice->FmtChans != DevFmtStereo)
        {
            ERR("Failed to set %s, got Stereo instead\n", DevFmtChannelsString(pDevice->FmtChans));
            pDevice->Flags &= ~DEVICE_CHANNELS_REQUEST;
        }
        pDevice->FmtChans = DevFmtStereo;
    }
    switch(pDevice->FmtType)
    {
        case DevFmtByte:
            pDevice->FmtType = DevFmtUByte;
            break;
        case DevFmtUShort:
            pDevice->FmtType = DevFmtShort;
            break;
        case DevFmtUByte:
        case DevFmtShort:
        case DevFmtFloat:
            break;
    }

retry_open:
    memset(&wfexFormat, 0, sizeof(WAVEFORMATEX));
    wfexFormat.wFormatTag = ((pDevice->FmtType == DevFmtFloat) ?
                             WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM);
    wfexFormat.nChannels = ChannelsFromDevFmt(pDevice->FmtChans);
    wfexFormat.wBitsPerSample = BytesFromDevFmt(pDevice->FmtType) * 8;
    wfexFormat.nBlockAlign = wfexFormat.wBitsPerSample *
                             wfexFormat.nChannels / 8;
    wfexFormat.nSamplesPerSec = pDevice->Frequency;
    wfexFormat.nAvgBytesPerSec = wfexFormat.nSamplesPerSec *
                                 wfexFormat.nBlockAlign;
    wfexFormat.cbSize = 0;

    if((res=waveOutOpen(&pData->hWaveHandle.Out, lDeviceID, &wfexFormat, (DWORD_PTR)&WaveOutProc, (DWORD_PTR)pDevice, CALLBACK_FUNCTION)) != MMSYSERR_NOERROR)
    {
        if(pDevice->FmtType == DevFmtFloat)
        {
            pDevice->FmtType = DevFmtShort;
            goto retry_open;
        }
        ERR("waveOutOpen failed: %u\n", res);
        goto failure;
    }

    pData->hWaveThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if(pData->hWaveThreadEvent == NULL)
    {
        ERR("CreateEvent failed: %lu\n", GetLastError());
        goto failure;
    }

    pData->Frequency = pDevice->Frequency;

    pDevice->szDeviceName = strdup((lDeviceID==WAVE_MAPPER) ? woDefault :
                                   PlaybackDeviceList[lDeviceID]);
    return ALC_NO_ERROR;

failure:
    if(pData->hWaveThreadEvent)
        CloseHandle(pData->hWaveThreadEvent);

    if(pData->hWaveHandle.Out)
        waveOutClose(pData->hWaveHandle.Out);

    free(pData);
    pDevice->ExtraData = NULL;
    return ALC_INVALID_VALUE;
}
Example #18
0
static int DX5_DInputInit(_THIS)
{
	int         i;
	LPDIRECTINPUTDEVICE device;
	HRESULT     result;
	DIPROPDWORD dipdw;
	HWND        topwnd;

	/* Create the DirectInput object */
	result = DInputCreate(SDL_Instance, DIRECTINPUT_VERSION,
							&dinput, NULL);
	if ( result != DI_OK ) {
		SetDIerror("DirectInputCreate", result);
		return(-1);
	}

	/* Create all of our registered input devices */
	SDL_DIndev = 0;
	for ( i=0; inputs[i].name; ++i ) {
		/* Create the DirectInput device */
		result = IDirectInput_CreateDevice(dinput, inputs[i].guid,
								&device, NULL);
		if ( result != DI_OK ) {
			SetDIerror("DirectInput::CreateDevice", result);
			return(-1);
		}
		result = IDirectInputDevice_QueryInterface(device,
			&IID_IDirectInputDevice2, (LPVOID *)&SDL_DIdev[i]);
		IDirectInputDevice_Release(device);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::QueryInterface", result);
			return(-1);
		}
		topwnd =  GetTopLevelParent(SDL_Window);
		result = IDirectInputDevice2_SetCooperativeLevel(SDL_DIdev[i],
					topwnd, inputs[i].win_level);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetCooperativeLevel",
									result);
			return(-1);
		}
		result = IDirectInputDevice2_SetDataFormat(SDL_DIdev[i],
							inputs[i].format);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetDataFormat", result);
			return(-1);
		}

		/* Set buffered input -- we aren't polling */
		SDL_memset(&dipdw, 0, sizeof(dipdw));
		dipdw.diph.dwSize = sizeof(dipdw);
		dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
		dipdw.diph.dwObj = 0;
		dipdw.diph.dwHow = DIPH_DEVICE;
		dipdw.dwData = INPUT_QSIZE;
		result = IDirectInputDevice2_SetProperty(SDL_DIdev[i],
						DIPROP_BUFFERSIZE, &dipdw.diph);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetProperty", result);
			return(-1);
		}

		/* Create an event to be signaled when input is ready */
		SDL_DIevt[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
		if ( SDL_DIevt[i] == NULL ) {
			SDL_SetError("Couldn't create DirectInput event");
			return(-1);
		}
		result = IDirectInputDevice2_SetEventNotification(SDL_DIdev[i],
								SDL_DIevt[i]);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetEventNotification",
									result);
			return(-1);
		}
		SDL_DIfun[i] = inputs[i].fun;

		/* Acquire the device for input */
		IDirectInputDevice2_Acquire(SDL_DIdev[i]);

		/* Increment the number of devices we have */
		++SDL_DIndev;
	}
	mouse_pressed = 0;
	mouse_buttons_swapped = GetSystemMetrics(SM_SWAPBUTTON);

	/* DirectInput is ready! */
	return(0);
}
Example #19
0
File: winmm.c Project: 9heart/DT3
static ALCenum WinMMOpenCapture(ALCdevice *pDevice, const ALCchar *deviceName)
{
    WAVEFORMATEX wfexCaptureFormat;
    ALbyte *BufferData = NULL;
    DWORD ulCapturedDataSize;
    WinMMData *pData = NULL;
    UINT lDeviceID = 0;
    ALint lBufferSize;
    MMRESULT res;
    ALuint i;

    if(!CaptureDeviceList)
        ProbeCaptureDevices();

    // Find the Device ID matching the deviceName if valid
    if(deviceName)
    {
        for(i = 0;i < NumCaptureDevices;i++)
        {
            if(CaptureDeviceList[i] &&
               strcmp(deviceName, CaptureDeviceList[i]) == 0)
            {
                lDeviceID = i;
                break;
            }
        }
    }
    else
    {
        for(i = 0;i < NumCaptureDevices;i++)
        {
            if(CaptureDeviceList[i])
            {
                lDeviceID = i;
                break;
            }
        }
    }
    if(i == NumCaptureDevices)
        return ALC_INVALID_VALUE;

    pData = calloc(1, sizeof(*pData));
    if(!pData)
        return ALC_OUT_OF_MEMORY;
    pDevice->ExtraData = pData;

    if((pDevice->FmtChans != DevFmtMono && pDevice->FmtChans != DevFmtStereo) ||
       (pDevice->FmtType != DevFmtUByte && pDevice->FmtType != DevFmtShort &&
        pDevice->FmtType != DevFmtFloat))
        goto failure;

    memset(&wfexCaptureFormat, 0, sizeof(WAVEFORMATEX));
    wfexCaptureFormat.wFormatTag = ((pDevice->FmtType == DevFmtFloat) ?
                                    WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM);
    wfexCaptureFormat.nChannels = ChannelsFromDevFmt(pDevice->FmtChans);
    wfexCaptureFormat.wBitsPerSample = BytesFromDevFmt(pDevice->FmtType) * 8;
    wfexCaptureFormat.nBlockAlign = wfexCaptureFormat.wBitsPerSample *
                                    wfexCaptureFormat.nChannels / 8;
    wfexCaptureFormat.nSamplesPerSec = pDevice->Frequency;
    wfexCaptureFormat.nAvgBytesPerSec = wfexCaptureFormat.nSamplesPerSec *
                                        wfexCaptureFormat.nBlockAlign;
    wfexCaptureFormat.cbSize = 0;

    if((res=waveInOpen(&pData->hWaveHandle.In, lDeviceID, &wfexCaptureFormat, (DWORD_PTR)&WaveInProc, (DWORD_PTR)pDevice, CALLBACK_FUNCTION)) != MMSYSERR_NOERROR)
    {
        ERR("waveInOpen failed: %u\n", res);
        goto failure;
    }

    pData->hWaveThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if(pData->hWaveThreadEvent == NULL)
    {
        ERR("CreateEvent failed: %lu\n", GetLastError());
        goto failure;
    }

    pData->Frequency = pDevice->Frequency;

    // Allocate circular memory buffer for the captured audio
    ulCapturedDataSize = pDevice->UpdateSize*pDevice->NumUpdates;

    // Make sure circular buffer is at least 100ms in size
    if(ulCapturedDataSize < (wfexCaptureFormat.nSamplesPerSec / 10))
        ulCapturedDataSize = wfexCaptureFormat.nSamplesPerSec / 10;

    pData->pRing = CreateRingBuffer(wfexCaptureFormat.nBlockAlign, ulCapturedDataSize);
    if(!pData->pRing)
        goto failure;

    pData->lWaveBuffersCommitted = 0;

    // Create 4 Buffers of 50ms each
    lBufferSize = wfexCaptureFormat.nAvgBytesPerSec / 20;
    lBufferSize -= (lBufferSize % wfexCaptureFormat.nBlockAlign);

    BufferData = calloc(4, lBufferSize);
    if(!BufferData)
        goto failure;

    for(i = 0;i < 4;i++)
    {
        memset(&pData->WaveBuffer[i], 0, sizeof(WAVEHDR));
        pData->WaveBuffer[i].dwBufferLength = lBufferSize;
        pData->WaveBuffer[i].lpData = ((i==0) ? (LPSTR)BufferData :
                                       (pData->WaveBuffer[i-1].lpData +
                                        pData->WaveBuffer[i-1].dwBufferLength));
        pData->WaveBuffer[i].dwFlags = 0;
        pData->WaveBuffer[i].dwLoops = 0;
        waveInPrepareHeader(pData->hWaveHandle.In, &pData->WaveBuffer[i], sizeof(WAVEHDR));
        waveInAddBuffer(pData->hWaveHandle.In, &pData->WaveBuffer[i], sizeof(WAVEHDR));
        InterlockedIncrement(&pData->lWaveBuffersCommitted);
    }

    pData->hWaveThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CaptureThreadProc, (LPVOID)pDevice, 0, &pData->ulWaveThreadID);
    if (pData->hWaveThread == NULL)
        goto failure;

    pDevice->szDeviceName = strdup(CaptureDeviceList[lDeviceID]);
    return ALC_NO_ERROR;

failure:
    if(pData->hWaveThread)
        CloseHandle(pData->hWaveThread);

    if(BufferData)
    {
        for(i = 0;i < 4;i++)
            waveInUnprepareHeader(pData->hWaveHandle.In, &pData->WaveBuffer[i], sizeof(WAVEHDR));
        free(BufferData);
    }

    if(pData->pRing)
        DestroyRingBuffer(pData->pRing);

    if(pData->hWaveThreadEvent)
        CloseHandle(pData->hWaveThreadEvent);

    if(pData->hWaveHandle.In)
        waveInClose(pData->hWaveHandle.In);

    free(pData);
    pDevice->ExtraData = NULL;
    return ALC_INVALID_VALUE;
}
Example #20
0
 inline TEvImpl(ResetMode rmode) {
     cond = CreateEvent(NULL, rmode == rManual ? true : false, false, NULL);
 }
//以一个线程不同监控串口行接收的数据
DWORD WINAPI SerialPort1ThreadProcess(HWND hWnd) //主窗口句柄
{
	char str[101];
	DWORD wCount; //读取的字节数
#if 1
	char lpInBuffer[512];
	DWORD dwBytesRead = 512;
	DWORD dwRealRead = 0;
	COMSTAT ComStat;
	DWORD dwErrorFlags;
	OVERLAPPED m_osRead;
	DWORD dwError;

	BOOL bReadStatus;

	memset(&m_osRead, 0, sizeof(OVERLAPPED));
	m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	
#endif
	
	while (1)
	{
#if 1
		
		ClearCommError(hCom, &dwErrorFlags, &ComStat);
		dwBytesRead = 256;
		
		PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
		bReadStatus = ReadFile(hCom, lpInBuffer, dwBytesRead, &dwRealRead, &m_osRead);
		if (!bReadStatus) //如果ReadFile函数返回FALSE
		{
			//GetLastError()函数返回ERROR_IO_PENDING,表明串口正在进行读操作
			if (dwError = GetLastError() == ERROR_IO_PENDING)
			{
				// WaitForSingleObject(m_osRead.hEvent, 2000);
				//使用WaitForSingleObject函数等待,直到读操作完成或延时已达到2秒钟
				//当串口读操作进行完毕后,m_osRead的hEvent事件会变为有信号
				//GetOverlappedResult(hCom,&m_osRead, &dwBytesRead, TRUE);
				GetOverlappedResult(hCom, &m_osRead, &dwRealRead, TRUE);
				if (dwRealRead > 0) //收到数据
				{
					lpInBuffer[dwRealRead] = '\0';
					::PostMessage(hWnd, COM_RECVDATA, (unsigned int)lpInBuffer, dwRealRead);
					//发送消息给对话框主窗口,以进行接收内容的显示
					
				}
					
				//PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
				//return dwBytesRead;

			}
		}
		else
		{
			//PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
			if (dwRealRead > 0) //收到数据
			{
				lpInBuffer[dwRealRead] = '\0';
				::PostMessage(hWnd, COM_RECVDATA, (unsigned int)lpInBuffer, dwRealRead);
				//发送消息给对话框主窗口,以进行接收内容的显示
			}
		}
		
	
#else
		ReadFile(hCom, str, 100, &wCount, NULL);
		if (wCount > 0) //收到数据
		{
			str[wCount] = '\0';
			::PostMessage(hWnd, COM_RECVDATA, (unsigned int)str, wCount);
			//发送消息给对话框主窗口,以进行接收内容的显示
		}
#endif
	}
	return TRUE;
}
Example #22
0
static int dshow_read_header(AVFormatContext *avctx)
{
    struct dshow_ctx *ctx = avctx->priv_data;
    IGraphBuilder *graph = NULL;
    ICreateDevEnum *devenum = NULL;
    IMediaControl *control = NULL;
    IMediaEvent *media_event = NULL;
    HANDLE media_event_handle;
    HANDLE proc;
    int ret = AVERROR(EIO);
    int r;

    CoInitialize(0);

    if (!ctx->list_devices && !parse_device_name(avctx)) {
        av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
        goto error;
    }

    ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id
                                                : AV_CODEC_ID_RAWVIDEO;
    if (ctx->pixel_format != AV_PIX_FMT_NONE) {
        if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
            av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when "
                              "video codec is not set or set to rawvideo\n");
            ret = AVERROR(EINVAL);
            goto error;
        }
    }
    if (ctx->framerate) {
        r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);
        if (r < 0) {
            av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
            goto error;
        }
    }

    r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
                         &IID_IGraphBuilder, (void **) &graph);
    if (r != S_OK) {
        av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
        goto error;
    }
    ctx->graph = graph;

    r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
                         &IID_ICreateDevEnum, (void **) &devenum);
    if (r != S_OK) {
        av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
        goto error;
    }

    if (ctx->list_devices) {
        av_log(avctx, AV_LOG_INFO, "DirectShow video devices (some may be both video and audio devices)\n");
        dshow_cycle_devices(avctx, devenum, VideoDevice, VideoSourceDevice, NULL);
        av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");
        dshow_cycle_devices(avctx, devenum, AudioDevice, AudioSourceDevice, NULL);
        ret = AVERROR_EXIT;
        goto error;
    }
    if (ctx->list_options) {
        if (ctx->device_name[VideoDevice])
            if ((r = dshow_list_device_options(avctx, devenum, VideoDevice, VideoSourceDevice))) {
                ret = r;
                goto error;
            }
        if (ctx->device_name[AudioDevice]) {
            if (dshow_list_device_options(avctx, devenum, AudioDevice, AudioSourceDevice)) {
                /* show audio options from combined video+audio sources as fallback */
                if ((r = dshow_list_device_options(avctx, devenum, AudioDevice, VideoSourceDevice))) {
                    ret = r;
                    goto error;
                }
            }
        }
    }
    if (ctx->device_name[VideoDevice]) {
        if ((r = dshow_open_device(avctx, devenum, VideoDevice, VideoSourceDevice)) < 0 ||
            (r = dshow_add_device(avctx, VideoDevice)) < 0) {
            ret = r;
            goto error;
        }
    }
    if (ctx->device_name[AudioDevice]) {
        if ((r = dshow_open_device(avctx, devenum, AudioDevice, AudioSourceDevice)) < 0 ||
            (r = dshow_add_device(avctx, AudioDevice)) < 0) {
            av_log(avctx, AV_LOG_INFO, "Searching for audio device within video devices %s\n", ctx->device_name[AudioDevice]);
            /* see if there's a video source with an audio pin with the given audio name */
            if ((r = dshow_open_device(avctx, devenum, AudioDevice, VideoSourceDevice)) < 0 ||
                (r = dshow_add_device(avctx, AudioDevice)) < 0) {
                ret = r;
                goto error;
            }
        }
    }
    if (ctx->list_options) {
        /* allow it to list crossbar options in dshow_open_device */
        ret = AVERROR_EXIT;
        goto error;
    }
    ctx->curbufsize[0] = 0;
    ctx->curbufsize[1] = 0;
    ctx->mutex = CreateMutex(NULL, 0, NULL);
    if (!ctx->mutex) {
        av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
        goto error;
    }
    ctx->event[1] = CreateEvent(NULL, 1, 0, NULL);
    if (!ctx->event[1]) {
        av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
        goto error;
    }

    r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
    if (r != S_OK) {
        av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
        goto error;
    }
    ctx->control = control;

    r = IGraphBuilder_QueryInterface(graph, &IID_IMediaEvent, (void **) &media_event);
    if (r != S_OK) {
        av_log(avctx, AV_LOG_ERROR, "Could not get media event.\n");
        goto error;
    }
    ctx->media_event = media_event;

    r = IMediaEvent_GetEventHandle(media_event, (void *) &media_event_handle);
    if (r != S_OK) {
        av_log(avctx, AV_LOG_ERROR, "Could not get media event handle.\n");
        goto error;
    }
    proc = GetCurrentProcess();
    r = DuplicateHandle(proc, media_event_handle, proc, &ctx->event[0],
                        0, 0, DUPLICATE_SAME_ACCESS);
    if (!r) {
        av_log(avctx, AV_LOG_ERROR, "Could not duplicate media event handle.\n");
        goto error;
    }

    r = IMediaControl_Run(control);
    if (r == S_FALSE) {
        OAFilterState pfs;
        r = IMediaControl_GetState(control, 0, &pfs);
    }
    if (r != S_OK) {
        av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
        goto error;
    }

    ret = 0;

error:

    if (devenum)
        ICreateDevEnum_Release(devenum);

    if (ret < 0)
        dshow_read_close(avctx);

    return ret;
}
Example #23
0
void Plat_SetSimpleLogName( const char * szLogName )
{
    Plat_GetExePath( g_LogName, 256 );
    //DeleteFileByTime( g_LogName ,1);
#ifdef WIN32
    strcat( g_LogName, "Log\\" );
#else
    strcat( g_LogName, "Log/" );
#endif

    struct tm *newtime;
    time_t aclock;
    time( &aclock );   // Get time in seconds
    newtime = localtime( &aclock );   // Convert time to struct tm form

    char strSubLogName[256] = { };

#ifdef WIN32

    FILETIME tmCreateTime ;
    FILETIME tmExitTime ;
    FILETIME tmKernalTime ;
    FILETIME tmUserTime ;
    SYSTEMTIME tmSystemTime;

    GetProcessTimes( GetCurrentProcess( ),&tmCreateTime , &tmExitTime , &tmKernalTime , &tmUserTime );
    FileTimeToSystemTime( &tmCreateTime ,&tmSystemTime );
    TIME_ZONE_INFORMATION    zinfo;

    GetTimeZoneInformation(&zinfo);//得到时区信息
    SystemTimeToTzSpecificLocalTime(&zinfo,&tmSystemTime,&tmSystemTime);//将格林威治时间转换为对应的当前时区的时间
    //SetLocalTime(&stime);//设置时间
    //tReturning = CTime(stime);

    //sprintf( strSubLogName ,"[LOG_%d_%d_%d_%d_%d_%d]\\" ,tmSystemTime.wYear ,tmSystemTime.wMonth, tmSystemTime.wDay,tmSystemTime.wHour ,tmSystemTime.wMinute , tmSystemTime.wSecond );
    sprintf( strSubLogName ,"[LOG_%d_%d_%d]\\" ,tmSystemTime.wYear ,tmSystemTime.wMonth, tmSystemTime.wDay );
#else
    //sprintf( strSubLogName ,"[LOG_%d_%d_%d]\\" , newtime->tm_hour,newtime->tm_min ,newtime->tm_sec );
    sprintf( strSubLogName ,"[LOG_%d_%d_%d]/" , newtime->tm_hour,newtime->tm_min ,newtime->tm_sec );
#endif
    strcat( g_LogName , strSubLogName );
    strcat( g_LogName, szLogName );
    strcpy(g_LogFileName,g_LogName);
    strcpy(g_FileName,szLogName);
    g_InitDay = tmSystemTime.wDay;

    if (!Plat_CreatePath( g_LogName )) {
        //return;
    }


    char fileTime[512] = {};
    sprintf( fileTime ,"[%d_%d_%d].log" , newtime->tm_hour,newtime->tm_min ,newtime->tm_sec );
    strcat( g_LogName , fileTime );

    //if( g_LogName[0] != 0 )
    //	g_hFile = fopen(g_LogName,"at+");
    //unlink( g_LogName );
#ifdef WIN32
    //by jinsheng 2009.1.7
    //_CrtSetReportHook( NewCrtMemReport );
#endif

#ifdef THREAD_LOG

    g_pLogUnitHead = new CHAINHEADER;
//	DWORD dwThreadID = 0;
    g_bLogRun = TRUE;// by sun 2009.2.7
    g_LogCount = 0 ;
#ifdef WIN32
    g_hLogEvent = CreateEvent( NULL, TRUE, FALSE, NULL );// by sun 2009.2.7 //  [4/10/2010 sun ]
    //	g_hLogThread = (HANDLE)CreateThread( NULL, 0, &LogThreadFunc, NULL, 0, &dwThreadID );
#else
    sem_init( &g_hLogEvent, 1, 0 );			// li9chuan	2010-12-1
#endif

    g_hLogThread = ThreadLib::Create( LogThreadFunc, NULL );

#endif
}
Example #24
0
/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
UINT printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints,
                      rdpPrinter* printer)
{
	char* port;
	UINT32 Flags;
	int DriverNameLen;
	WCHAR* DriverName = NULL;
	int PrintNameLen;
	WCHAR* PrintName = NULL;
	UINT32 CachedFieldsLen;
	BYTE* CachedPrinterConfigData;
	PRINTER_DEVICE* printer_dev;
	UINT error;
	port = malloc(10);

	if (!port)
	{
		WLog_ERR(TAG, "malloc failed!");
		return CHANNEL_RC_NO_MEMORY;
	}

	sprintf_s(port, 10, "PRN%d", printer->id);
	printer_dev = (PRINTER_DEVICE*) calloc(1, sizeof(PRINTER_DEVICE));

	if (!printer_dev)
	{
		WLog_ERR(TAG, "calloc failed!");
		free(port);
		return CHANNEL_RC_NO_MEMORY;
	}

	printer_dev->device.type = RDPDR_DTYP_PRINT;
	printer_dev->device.name = port;
	printer_dev->device.IRPRequest = printer_irp_request;
	printer_dev->device.Free = printer_free;
	printer_dev->rdpcontext = pEntryPoints->rdpcontext;
	printer_dev->printer = printer;
	CachedFieldsLen = 0;
	CachedPrinterConfigData = NULL;
	Flags = 0;

	if (printer->is_default)
		Flags |= RDPDR_PRINTER_ANNOUNCE_FLAG_DEFAULTPRINTER;

	DriverNameLen = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, &DriverName,
	                                 0) * 2;
	PrintNameLen = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &PrintName,
	                                0) * 2;
	printer_dev->device.data = Stream_New(NULL,
	                                      28 + DriverNameLen + PrintNameLen + CachedFieldsLen);

	if (!printer_dev->device.data)
	{
		WLog_ERR(TAG, "calloc failed!");
		error = CHANNEL_RC_NO_MEMORY;
		free(DriverName);
		free(PrintName);
		goto error_out;
	}

	Stream_Write_UINT32(printer_dev->device.data, Flags);
	Stream_Write_UINT32(printer_dev->device.data, 0); /* CodePage, reserved */
	Stream_Write_UINT32(printer_dev->device.data, 0); /* PnPNameLen */
	Stream_Write_UINT32(printer_dev->device.data, DriverNameLen + 2);
	Stream_Write_UINT32(printer_dev->device.data, PrintNameLen + 2);
	Stream_Write_UINT32(printer_dev->device.data, CachedFieldsLen);
	Stream_Write(printer_dev->device.data, DriverName, DriverNameLen);
	Stream_Write_UINT16(printer_dev->device.data, 0);
	Stream_Write(printer_dev->device.data, PrintName, PrintNameLen);
	Stream_Write_UINT16(printer_dev->device.data, 0);

	if (CachedFieldsLen > 0)
	{
		Stream_Write(printer_dev->device.data, CachedPrinterConfigData,
		             CachedFieldsLen);
	}

	free(DriverName);
	free(PrintName);
	printer_dev->pIrpList = (WINPR_PSLIST_HEADER) _aligned_malloc(sizeof(
	                            WINPR_SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT);

	if (!printer_dev->pIrpList)
	{
		WLog_ERR(TAG, "_aligned_malloc failed!");
		error = CHANNEL_RC_NO_MEMORY;
		goto error_out;
	}

	InitializeSListHead(printer_dev->pIrpList);

	if (!(printer_dev->event = CreateEvent(NULL, TRUE, FALSE, NULL)))
	{
		WLog_ERR(TAG, "CreateEvent failed!");
		error = ERROR_INTERNAL_ERROR;
		goto error_out;
	}

	if (!(printer_dev->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
	{
		WLog_ERR(TAG, "CreateEvent failed!");
		error = ERROR_INTERNAL_ERROR;
		goto error_out;
	}

	if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman,
	             (DEVICE*) printer_dev)))
	{
		WLog_ERR(TAG, "RegisterDevice failed with error %"PRIu32"!", error);
		goto error_out;
	}

	if (!(printer_dev->thread = CreateThread(NULL, 0,
	                            (LPTHREAD_START_ROUTINE) printer_thread_func, (void*) printer_dev, 0, NULL)))
	{
		WLog_ERR(TAG, "CreateThread failed!");
		error = ERROR_INTERNAL_ERROR;
		goto error_out;
	}

	return CHANNEL_RC_OK;
error_out:
	CloseHandle(printer_dev->stopEvent);
	CloseHandle(printer_dev->event);
	_aligned_free(printer_dev->pIrpList);
	Stream_Free(printer_dev->device.data, TRUE);
	free(printer_dev);
	free(port);
	return error;
}
Example #25
0
 PlatformEvent() {
   _Event   = 0 ;
   _ParkHandle = CreateEvent (NULL, false, false, NULL) ;
   guarantee (_ParkHandle != NULL, "invariant") ;
 }
Example #26
0
/*----------------------------------------------------------------------*
                            rtp_term_aux_getch
 *----------------------------------------------------------------------*/
int rtp_term_aux_getch ()
{

    unsigned long dwRead;
    unsigned char buffer;
    unsigned long ret;

    HANDLE hComm;
    OVERLAPPED osReader = {0};
    
    hComm = (HANDLE) auxComm;

    // Create the overlapped event. Must be closed before exiting
    // to avoid a handle leak.
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (osReader.hEvent == NULL)
    {
        rtp_term_puts("rtp_term_aux_getch: Error creating overlapped event; abort\n");
        return -1;
    }

    do
    {// Issue read operation.
        if (!ReadFile(hComm, &buffer, 1, &dwRead, &osReader)) 
        {
            if (GetLastError() != ERROR_IO_PENDING)     // read not delayed?
            {
                            rtp_term_puts("rtp_term_aux_getch: Error in communications; report it.\n");
                return (-1);
            }
            else
            {
                /* wait for 1ms */
                do
                {
                    ret = WaitForSingleObject(osReader.hEvent, 0);

                    poll_os_cycle();

                }while (ret == WAIT_TIMEOUT);
    
                switch(ret)
                {
                    // Read completed.
                    case WAIT_OBJECT_0:
                        if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE))
                        {
                            // Error in communications; report it.
                            rtp_term_puts("rtp_term_aux_getch: Error in communications; report it.\n");
                        }
                        else
                        {
                            // Read completed successfully.
                            //HandleASuccessfulRead(buffer, dwRead);
                        }
                        break;
    
                    case WAIT_TIMEOUT:
                        break;                       
    
                    default:
                        // Error in the WaitForSingleObject; abort.
                        // This indicates a problem with the OVERLAPPED structure's
                        // event handle.
                        break;
                }
            }
        }
        else
        {
        // read completed immediately
        //HandleASuccessfulRead(buffer, dwRead);
        }
        poll_os_cycle();
//tvotvo        TERMINAL_AUX_THREAD_SLEEP(100);
    }while (dwRead == 0);
    
    CloseHandle(osReader.hEvent);
    
    return (int) buffer;
    
}
Example #27
0
co_rc_t co_os_pipe_server_create_client(co_os_pipe_server_t *ps, HANDLE handle)
{
	char pipename[0x100];
	co_os_pipe_connection_t *connection;
	HANDLE event;
	int index;
	co_rc_t rc = CO_RC(OK);

	pipe_server_pathname(pipename, sizeof(pipename), ps->id);

	if (CO_OS_PIPE_SERVER_MAX_CLIENTS == ps->num_clients) {
		rc = CO_RC(ERROR); 
		goto out;
	}

	connection = co_os_malloc(sizeof(*connection));
	if (connection == NULL) {
		rc = CO_RC(ERROR); 
		goto out;
	}

	memset(connection, 0, sizeof(*connection));
	connection->in_buffer = (char *)co_os_malloc(CO_OS_PIPE_SERVER_BUFFER_SIZE);
	if (connection->in_buffer == NULL) {
		rc = CO_RC(ERROR);
		goto out_free_connection;
	}

	connection->buffer_size = CO_OS_PIPE_SERVER_BUFFER_SIZE;

	event = CreateEvent(NULL,  TRUE, FALSE, NULL);
	if (event == INVALID_HANDLE_VALUE) {
		rc = CO_RC(ERROR);
		goto out_free_buffer;
	}
	ResetEvent(event);

	if (handle) {
		connection->pipe = handle;
	}
	else {
		connection->pipe = CreateNamedPipe(
			pipename,
			PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
			PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
			PIPE_UNLIMITED_INSTANCES,
			0x100000,
			0x100000,
			10000,
			NULL);
	}

	if (connection->pipe == INVALID_HANDLE_VALUE) {
		rc = CO_RC(ERROR);
		goto out_close_event;
	}

	index = ps->num_clients;	
	connection->overlap.hEvent = event;
	connection->index = index;
	ps->num_clients++;
	ps->clients[index] = connection;
	ps->events[index] = event;

	if (ConnectNamedPipe(connection->pipe, &connection->overlap) != 0) {
		co_os_pipe_server_client_connected(ps, connection);
		rc = co_os_pipe_server_read_sync(ps, connection);
	} else {
		connection->state = CO_OS_PIPE_SERVER_STATE_NOT_CONNECTED;
	}

	return rc;
	
	/* error path */
out_close_event:
	CloseHandle(event);

out_free_buffer:
	co_os_free(connection->in_buffer);

out_free_connection:
	co_os_free(connection);

out:
	return rc;
}
Example #28
0
DWORD
HW_Init(
    PI2C_CONTEXT pI2C
    )
{
    DWORD dwErr = ERROR_SUCCESS;
	UINT32 Irq;
    
//    RETAILMSG(1,(TEXT("I2C Init\r\n")));
    if ( !pI2C ) {
        return ERROR_INVALID_PARAMETER;
    }
    
    DEBUGMSG(ZONE_TRACE,(TEXT("+I2C_Init: %u, 0x%x, 0x%x \r\n"), 
        pI2C->Mode, pI2C->SlaveAddress));

    InitializeCriticalSection(&pI2C->RegCS);
    
    pI2C->Status    = 0;
    pI2C->Data      = NULL;
    pI2C->DataCount = INVALID_DATA_COUNT;
    pI2C->Flags.DropRxAddr = FALSE;

    pI2C->hProc = (HANDLE)GetCurrentProcessId();

    InitRegs(pI2C);

    // create I/O Done Event
    if ( (pI2C->DoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) == NULL)
    {
        dwErr = GetLastError();
        DEBUGMSG(ZONE_ERR,(TEXT("I2C_Init ERROR: Unable to create Done event: %u \r\n"), dwErr));
        goto _init_error;
    }

    // setup Operating Mode
    if ( pI2C->Mode == INTERRUPT ) {
        // create IST event
        if ( (pI2C->ISTEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) == NULL)
        {
            dwErr = GetLastError();
            DEBUGMSG(ZONE_ERR,(TEXT("I2C_Init ERROR: Unable to create IST event: %u \r\n"), dwErr));
            goto _init_error;
        }

	// Obtain sysintr values from the OAL for the camera interrupt.
	//
	Irq = IRQ_I2C;
	if (!KernelIoControl(IOCTL_HAL_REQUEST_SYSINTR, &Irq, sizeof(UINT32), &gIntrIIC, sizeof(UINT32), NULL))
	{
		DEBUGMSG(ZONE_ERR, (TEXT("ERROR: Failed to request the IIC sysintr.\r\n")));
		gIntrIIC = SYSINTR_UNDEFINED;
		return(FALSE);
	}
//	RETAILMSG(1, (TEXT("IIC IRQ mapping: [IRQ:%d->sysIRQ:%d].\r\n"), Irq, gIntrIIC));

        // initialize the interrupt
        if( !InterruptInitialize(gIntrIIC, pI2C->ISTEvent, NULL, 0) ) 
        {
            dwErr = GetLastError();
            DEBUGMSG(ZONE_ERR,(TEXT("I2C_Init ERROR: Unable to initialize interrupt: %u\r\n"), dwErr));
            goto _init_error;
        }

        InterruptDone(gIntrIIC);

        // create the IST
        if ( (pI2C->IST = CreateThread(NULL, 0, I2C_IST, (LPVOID)pI2C, 0, NULL)) == NULL)
        {
            dwErr = GetLastError();
            DEBUGMSG(ZONE_ERR,(TEXT("I2C_Init ERROR: Unable to create IST: %u\r\n"), dwErr));
            goto _init_error;
        }

        // TODO: registry override
        if ( !CeSetThreadPriority(pI2C->IST, I2C_THREAD_PRIORITY)) {
            dwErr = GetLastError();
            DEBUGMSG(ZONE_ERR, (TEXT("I2C_Init ERROR: CeSetThreadPriority ERROR:%d\n"), dwErr));
            goto _init_error;
        }
    }

    DEBUGMSG(ZONE_TRACE,(TEXT("-I2C_Init \r\n")));

    return dwErr;

_init_error:
    HW_Deinit(pI2C);

    return dwErr;
}
Example #29
0
void EventDlg_OnCommand(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify)
{
	int rc;

	switch (id)
	{
	case IDC_AUTOMATIC:
		KillThreads();
		if (hEventObject) rc = CloseHandle(hEventObject);
		MTVERIFY( hEventObject = CreateEvent(NULL,	// Security
										FALSE,		// Automatic (FALSE = not manual)
										0,			// Clear on creation
										"EventTest")// Name of object
									);
		// CreateEvent ALWAYS sets the last error
		if (GetLastError() == ERROR_ALREADY_EXISTS)
			AddToList("WARNING: Event wasn't destroyed");
		StartThreads();
		AddToList("Event set to AUTOMATIC");
		break;

	case IDC_MANUAL:
		KillThreads();
		if (hEventObject) rc = CloseHandle(hEventObject);
		MTVERIFY( hEventObject = CreateEvent(NULL,	// Security
										TRUE,		// Manual
										0,			// Clear on creation
										"EventTest")// Name of object
									);
		if (GetLastError() == ERROR_ALREADY_EXISTS)
			AddToList("Reusing old event");
		StartThreads();
		AddToList("Event set to MANUAL");
		break;

	case IDC_SIGNAL:
		MTVERIFY( SetEvent(hEventObject) );
		break;

	case IDC_RESET:
		MTVERIFY( ResetEvent(hEventObject) );
		break;

	case IDC_PULSE:
		MTVERIFY( PulseEvent(hEventObject) );
		break;

	case IDC_CLEAR:
		ListBox_ResetContent(GetDlgItem(hDlg, IDC_RESULTS));
		break;

	case IDCANCEL:
	case IDM_EXIT:
		PostMessage(GetParent(hDlg),WM_DESTROY, (WPARAM)0, (LPARAM)0);
		DestroyWindow(hDlgMain);
		hDlgMain = NULL;
		break;
		
	default:
		break;
	}
}
Example #30
-1
//--------------------------------------------------------------
// constructor
mgWinEvent::mgWinEvent()
{
  m_event = CreateEvent(NULL, false, false, NULL);
}