I'm working with one of the official Kinect SDK 1.5 examples, and I'm trying to figure out how to add a check to detect when the Kinect is being disconnected. Currently the app will just freeze, so there must be a way to prevent this from happening.
This is the main message loop from the SDK example:
// Main message loop
while (WM_QUIT != msg.message)
{
hEvents[0] = m_hNextDepthFrameEvent;
// Check to see if we have either a message (by passing in QS_ALLINPUT)
// Or a Kinect event (hEvents)
// Update() will check for Kinect events individually, in case more than one are signalled
DWORD dwEvent = MsgWaitForMultipleObjects(eventCount, hEvents, FALSE, INFINITE, QS_ALLINPUT);
// Check if this is an event we're waiting on and not a timeout or message
if (WAIT_OBJECT_0 == dwEvent)
{
Update();
}
// does not work.
bool bla = m_pNuiSensor->NuiStatus();
if (NULL == m_pNuiSensor)
{
cout << 1 << endl;
}
if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
{
// If a dialog message will be taken care of by the dialog proc
if ((hWndApp != NULL) && IsDialogMessageW(hWndApp, &msg))
{
continue;
}
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
return static_cast<int>(msg.wParam);
I've added the following bit:
// does not work, bla will always be the same value.
bool bla = m_pNuiSensor->NuiStatus();
if (NULL == m_pNuiSensor)
{
cout << 1 << endl;
}
since I was assuming that maybe NuiStatus would be a way to detect the disconnect. Unfortunately it won't work. The same is true for checking whether m_pNuiSensor is NULL.
So what's the way to detect a disconnect in the running app?
EDIT1: should I be using NuiSetDeviceStatusCallback?
In the documentation it says that NuiStatus returns HRESULT and not bool, so shouldn't it be
HRESULT bla = m_pNuiSensor->NuiStatus();
if (bla == E_NUI_NOTCONNECTED)
{
cout << 1 << endl;
}
instead?
the following solution works.
// check if m_pNuiSensor is initialized.
if (NULL != m_pNuiSensor)
{
// get current status & check if not ok.
HRESULT current_status = m_pNuiSensor->NuiStatus();
if (current_status != S_OK )
{
SetStatusMessage(L"Lost connection to Kinect!");
}
}
Related
So i'm trying to create a minimal tcp server using kqueue, assuming all the previous details of socket(), bind(), listen() is working correctly given that i've tested them using a thread-per-connection model. why it hangs unexpectedly ?
struct kevent events;
struct kevent change_list;
// create a kqueue
int kq = kqueue();
if (kq < 0) {
throw KqueueException();
}
// initialize the events we want to monitor
EV_SET(&events, sock, EVFILT_READ, EV_ADD, 0, 0, NULL);
// monitor the events
if (kevent(kq, &events, 1, NULL, 0, NULL) < 0) {
throw KqueueException();
}
int nev;
while (true) {
// wait for events to happen
nev = kevent(kq, NULL, 0, &change_list, 1, NULL);
if (nev < 0) {
throw KqueueException();
}
else if (nev > 0) {
// if the event fd is the same as the socket fd we have a new connection
if ((int)change_list.ident == sock) {
std::cout << "new connection" << std::endl;
// accept the connection
int client_fd = accept(sock, NULL, NULL);
if (client_fd < 0) {
throw AcceptException();
}
// add the new connection to the events we want to monitor
EV_SET(&events, client_fd, EVFILT_READ, EV_ADD, 0, 0, NULL);
// add the new connection to the events we want to monitor
if (kevent(kq, &events, 1, NULL, 0, NULL) < 0) {
throw KqueueException();
}
}
else if (change_list.filter == EVFILT_READ) {
char hello[] = "HTTP/1.1 200 OK\nContent-Type: text/plain; charset=UTF-8\nContent-Length: 15\n\nhello from meee\n";
send(change_list.ident, hello, strlen(hello), 0);
}
}
}
using a browser i entered localhost:8090 and the program entered the
if ((int)change_list.ident == sock) {...
the first time and then accepted the connection, went to next iteration and entered the second if condition else if (change_list.filter == EVFILT_READ) {.. (these two actions happened and i received a hello message in the browser ) but when i refreshed the browser the server just hangs with no error (which means no exceptions happen). i tried debugging and it seems like the program keeps entering the else if (change_list.filter == EVFILT_READ) {.. condition over and over until it hangs,I tried adding (naively) nev = 0 at each end of iteration to reset the events count which surely didn't resolve the problem, am i doing something wrong... ? can u give an explanation to what's happening ?
I am using CreateEvent to prevent multiple instances of my application:
CreateEvent(NULL, TRUE, FALSE, "MyEvent");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
// Do Stuff
return FALSE;
}
However, at startup I have noticed that this doesn't work:
After the desktop is shown I automatically run a batch script that attempts to launch multiple instances of my program. The batch script succeeds and I can indeed see multiple instances.
Investigation so far:
OutputDebug shows that each instance does not get ERROR_ALREADY_EXISTS
ProcessExplorer.exe shows that each instance was able to get a handle to the event "MyEvent".
Can anybody think why this might be happening, and how I could solve it?
We use the function below, which is in our common utility DLL. The method is derived from a Microsoft article explaining how to prevent multiple instances in WIN32.
#define STRICT
#include <stdheaders.h>
HANDLE ghSem;
BOOL IExist( LPSTR lpszWindowClass )
{
HWND hWndMe;
int attempt;
for( attempt=0; attempt<2; attempt++ )
{
// Create or open a named semaphore.
ghSem = CreateSemaphore( NULL, 0, 1, lpszWindowClass );
// Close handle and return NULL if existing semaphore was opened.
if( (ghSem != NULL) &&
(GetLastError() == ERROR_ALREADY_EXISTS) )
{ // Someone has this semaphore open...
CloseHandle( ghSem );
ghSem = NULL;
hWndMe = FindWindow( lpszWindowClass, NULL );
if( hWndMe && IsWindow(hWndMe) )
{ // I found the guy, try to wake him up
if( SetForegroundWindow( hWndMe ) )
{ // Windows says we woke the other guy up
return TRUE;
}
}
Sleep(100); // Maybe the semaphore will go away like the window did...
}
else
{ // If new semaphore was created, return FALSE.
return FALSE;
}
}
// We never got the semaphore, so we must
// behave as if a previous instance exists
return TRUE;
}
Just do something like this in your WinMain:
if( IExist("MyWindowClass") )
{
return 1;
}
Of course, you could replace the return with whatever you need to do when you are not the first instance (such as activating the existing instance).
I need to send one request to server more quickly and repeatedly.
So I implemented code like this.
BOOL CTestDlg::OnInitDialog()
{
...
m_hInstance = InternetOpen(L"asynchttp", INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,INTERNET_FLAG_ASYNC);
if(m_hInstance == NULL)
{
ErrorLog(L"InternetOpen Failed");
return TRUE;
}
if (InternetSetStatusCallback(m_hInstance,(INTERNET_STATUS_CALLBACK)&Callback) == INTERNET_INVALID_STATUS_CALLBACK)
{
ErrorLog(L"Set Callback Function Failed");
return TRUE;
}
m_hConnect = InternetConnect(m_hInstance, L"192.168.2.116", 8080,NULL,NULL,INTERNET_SERVICE_HTTP,INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION,1);
if(m_hConnect == NULL)
{
if(DWORD dwError = GetLastError() != ERROR_IO_PENDING)
{
ErrorLog(L"Fail to Connect Server");
return TRUE;
}
WaitForSingleObject(hConnectedEvent, INFINITE);
}
CreateThread(0 , 0 , (LPTHREAD_START_ROUTINE)SendThread , 0 , 0 , 0);
return TRUE;
}
void __stdcall Callback(HINTERNET hInternet,DWORD dwContext,DWORD dwInternetStatus,LPVOID lpStatusInfo,DWORD dwStatusInfoLen)
{
switch(dwContext)
{
case 1:
{
SetEvent(hConnectedEvent);
}
break;
}
}
DWORD SendThread(LPVOID lpParam)
{
TCHAR *szAceptType[] = {_T("*/*") , NULL};
CString szContentType = _T("Content-Type: application/x-www-form-urlencoded\r\n");
char szPostData[MAX_PATH];
sprintf(szPostData , "num=1234&str=3240");
HINTERNET hRequest = HttpOpenRequest(m_hConnect, L"POST", L"/TestWeb/index.jsp", HTTP_VERSION , NULL , (LPCTSTR*)szAceptType , 0, 2);
while(1)
{
try
{
if (!HttpSendRequest(hRequest, szContentType, (DWORD)szContentType.GetLength(), szPostData,(DWORD)strlen(szPostData)))
{
if (DWORD dwError = GetLastError() != ERROR_IO_PENDING)
ErrorLog(L"SendRequest: Error = %d" , dwError);
}
}
catch (CException* e)
{
UNREFERENCED_PARAMETER(e);
}
Sleep(100);
}
return 0;
}
When execute or debug program, I saw this "SendRequest; Error = 1" log frequently.
And Server does not record anymore to database , after one or two request data recorded
It seems like HttpSendRequest API doesn't work correctly after error occured.
I aim to send one request to server more fast and more correctly, without loss.
Please teach me what is wrong problem.
Or if you got another best way, then please tell me.
Thanks.
Error code 1 is "Invalid Parameter".
You appear to be mixing ASCII (char and sprintf) and Unicode strings in your sample above. Have you tried with all Unicode strings (making szPostData a WCHAR array)? From MSDN: "There two versions of HttpSendRequest —HttpSendRequestA (used with ANSI builds) and HttpSendRequestW (used with Unicode builds)". It goes on to talk about when ERROR_INVALID_PARAMETER is returned. http://msdn.microsoft.com/en-us/library/windows/desktop/aa384247(v=vs.85).aspx
Also, I haven't used MFC in a long time, but I remember that you should call e->Delete() in your exception handler (unless you re-throw). The CException::Delete method will delete any thrown exception created on the heap (and do nothing otherwise).
My question is in continuation to my previous question "SetSuspendState() API never returns in Win8"
I'm running my VC++ code on Win8/Win8.1 m/c.
My purpose is to put the system to sleep & again bring back the system
from sleep automatically without any manual "mouse click or keyboard
hit".
But I'm not able to achieve "taking the system to sleep and hence ofcourse not bringing the system back from sleep." With the below call SetSuspendState(), the system is going to hibernation always, instead of sleep.
I'm again pasting the code snippet for quick reference::
int wait = 100;
LARGE_INTEGER WaitTime;
WaitTime.QuadPart = wait;
WaitTime.QuadPart *= -10000000;
HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);
if(0 == SetWaitableTimer(hTimer, &WaitTime, 0, NULL, NULL, TRUE))
{
res = false;
return res;
}
if(0 == SetSuspendState(FALSE, FALSE, FALSE))
{
res = false;
return res;
}
Here I'm calling "SetSuspendState() API with the options to put the system to sleep & to get it back from sleep automatically but the system is just going to hibernation::
SetSuspendState(FALSE, FALSE, FALSE)
Can anyone kindly help me in solving this problem & how do i put my system to sleep "programatically & resume back from sleep automatically without manual "mouse click or keyboard hit".
Before performing sleep we should make sure that system supports the required sleep state and allow wake up timer should be enabled, use following code to do the same.
//Check support
SYSTEM_POWER_CAPABILITIES sysPowCab = {0};
if (CallNtPowerInformation(SystemPowerCapabilities, NULL, 0, &sysPowCab, sizeof(SYSTEM_POWER_CAPABILITIES)) != 0)
{
return false;
}
if (!sysPowCab.SystemS3)
{
return false;
}
return true;
//Enable allow wake up timer
GUID *pPwrGUID;
GUID subGUID = GUID_SLEEP_SUBGROUP;
GUID BriGUID = GUID_ALLOW_RTC_WAKE;
DWORD ret = PowerGetActiveScheme(NULL, &pPwrGUID);
if (ret != ERROR_SUCCESS)
{
return false;
}
ret = PowerWriteACValueIndex(NULL, pPwrGUID, &subGUID, &BriGUID, 1);
if (ret != ERROR_SUCCESS)
{
return false;
}
return true;
So, the code goes somehow like this:
MAIN(){
/*waiting window class declaration*/
threadinfo* oThread=new threadinfo(); //An object that will help me know when to finish the thread
QueueUserWorkItem((LPTHREAD_START_ROUTINE)waitingWindow, (void*)mThread, WT_EXECUTELONGFUNCTION);
function_that_takes_time();
oThread->setTerminated(); //set member terminated to bool true
/*continue with other things*/
}
and waitingWindow function that will run on that thread
MSG msg;
hwndWaiting=CreateWindow(...) // here the window is created
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, null, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
if(oThread->isTerminated()) // isTerminated returns bool true if terminated
{
delete oThread;
ExitThread(0);
}
}
}
ExitThread(0);
Is ExitThread a good way to remove the waiting window, and safely remove the thread? (at least I'm 100% sure this way when to end it).
I'm asking this because this works nice in Windows XP, but will crash with "the application has stopped working" on Windows 7.
Thanks for the help.
The best way to end threads in general, is to let them "gracefully" finish up by themselves. You could tell the thread to end by setting an event, for example:
HANDLE hevent_die = CreateEvent(...);
HANDLE hthread_something = CreateThread(...); // or _beginthread()
...
DWORD WINAPI thread_func (LPVOID param)
{
while(working && WaitForSingleObject(hevent_die, 0)!=WAIT_OBJECT_0)
{
...
}
return 0;
}
while (msg.message != WM_QUIT)
{
...
if(WaitForSingleObject(hthread_something, 0) == WAIT_OBJECT_0)
{
// do things if needed
}
}
SetEvent(hevent_die);
WaitForSingleObject(hthread_something, INFINITE);
CloseHandle(hthread_something);
CloseHandle(hevent_die);
hthread_something = 0;
hevent_die = 0;
If you are using nested loops inside the thread function, they too will have to end if they receive the event.
You should exit your loop and thread cleanly so that any destructors are called correctly. Don't use ExitThread(), just use a flag to indicate when to exit the loop and then just exit your waitingWindow function at the end.