//-------------------------------------------------------------------
// GM_trap_PwrFail.cpp
//
//
// This application demonstrates how to trap the power
// failure event on the Graphics Master.
//
// History
// 8mar05 720020-11901 ak
// - Initial release created based on 
//
//-------------------------------------------------------------------

#include "stdafx.h"

//-------------------------------------------------------------------
//-------------------------------------------------------------------
int ShowError()
{
    LPVOID lpMsgBuf;
    int err = GetLastError();

    FormatMessage( 
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM | 
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        err,
        0, // Default language
        (LPTSTR) &lpMsgBuf,
        0,
        NULL);

	DEBUGMSG (1,(L"     Error #%d: %s\r\n",err,lpMsgBuf));

    LocalFree( lpMsgBuf );

    return err;
}


//-------------------------------------------------------------------
//-------------------------------------------------------------------
int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPTSTR    lpCmdLine,
					int       nCmdShow)
{
    int j;
	BOOL done=FALSE;

	RETAILMSG(1,(L"* 720020-11901 Demonstration of trapping the power failure event.\r\n"));
 	RETAILMSG(1,(L"  Reduce 5V input power slowly to cause power fail circuit to trip.\r\n"));

    HANDLE hPowerIsFailing = CreateEvent( 
                    NULL,       // no security attributes in CE
                    TRUE,       // application will reset J1 event as needed
                    FALSE,      // initial state is unsignalled
                    L"VDDPWROFF"); // name of power fail event

    if (hPowerIsFailing == INVALID_HANDLE_VALUE)
    {
     	RETAILMSG(1,(L"! Error: Unable to create power fail event.\r\n"));
        ShowError();
        return(2);
    }


    while (!done)
    {
        // Wait for power to fail
        if (!ResetEvent (hPowerIsFailing))
            ShowError();
        else
//            WaitForSingleObject(hJ1_pressed,2000);  
          WaitForSingleObject(hPowerIsFailing,INFINITE); // can use INFINITE timeout, too

        // Put system to sleep
        RETAILMSG(1,(L"  Going to sleep "));
        keybd_event(VK_OFF,0,0,0);

        // See how long system takes to go to sleep
        // Each z character represents 25ms, except for first, 
        //   which is displayed almost immediately
        for (j=0;j<20;j++)
        {
          RETAILMSG(1,(L"z"));
          Sleep(25);
        }

        // When it reaches this line, system has been reawakened
 	    RETAILMSG(1,(L" app is awake.\r\n"));

    } // while !done

    RETAILMSG(1,(L"  Power_fail: Program end.\r\n"));

	return 0;

}
