Example #1
0
int
CpGetEncryptionMode(int argc, _TCHAR* argv[])
{
    HNDAS hNDAS = NULL;
    NDASCOMM_CONNECTION_INFO ci;
    BYTE DeviceID[6];
    DWORD dwUnitNo;
    NDASCOMM_VCMD_PARAM param_vcmd;
    /*	PNDASCOMM_HANDLE_CONTEXT Context;
    	UINT16 HeaderEnc=FALSE;
    	UINT16 DataEnc = FALSE;  */
    //
    //	Get arguments.
    //
    if(argc < 2) {
        _ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
        return -1;
    }

    _ftprintf(stdout, _T("Starting the operation...\n"));
    SetLastError(0);
    API_CALL(NdasCommInitialize());


    //
    //	Connect and login
    //

    ZeroMemory(&ci, sizeof(ci));
    ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
    ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */
    ci.UnitNo = 0; /* Use first Unit Device */
    ci.WriteAccess = FALSE; /* Connect with read-write privilege */
    ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
    ci.OEMCode.UI64Value = 0; /* Use default password */
    ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */
    ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */
    _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */
    _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */
    API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out);

    //
    //	Display NDAS device info
    //

    API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out);
    _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n",
             DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5],
             (int)dwUnitNo);

    _tprintf(L"This vendor operation is not supported yet\n");
    /*
    	Context = NdasHandleToContext(hNDAS);

    	lsp_get_handle_info(
    		Context->hLSP,
    		lsp_handle_info_hw_header_encrypt_algo,
    		&HeaderEnc,  sizeof(HeaderEnc));
    	lsp_get_handle_info(
    		Context->hLSP,
    		lsp_handle_info_hw_data_encrypt_algo,
    		&DataEnc,  sizeof(DataEnc));
    */

out:
    if(GetLastError()) {
        _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
    }

    if(hNDAS)
    {
        NdasCommDisconnect(hNDAS);
        hNDAS = NULL;
    }

    NdasCommUninitialize();

    _ftprintf(stdout, _T("Finished the operation.\n"));

//	_ftprintf(stderr, _T("\nRetransmission time: %d milli-seconds.\n"), param_vcmd.GET_MAX_CONN_TIME.MaxConnTime);

    return GetLastError();
}
Example #2
0
void CCDecoder::DecodeCC(BYTE* buff, int len, __int64 time)
{
    if (!m_rawfn.IsEmpty()) {
        if (FILE* f = _tfopen(m_rawfn, _T("at"))) {
            _ftprintf(f, _T("%02d:%02d:%02d.%03d\n"),
                      (int)(time / 1000 / 60 / 60),
                      (int)((time / 1000 / 60) % 60),
                      (int)((time / 1000) % 60),
                      (int)(time % 1000));

            for (int i = 0; i < len; i++) {
                _ftprintf(f, _T("%02x"), buff[i]);
                if (i < len - 1) { _ftprintf(f, _T(" ")); }
                if (i > 0 && (i & 15) == 15) { _ftprintf(f, _T("\n")); }
            }
            if (len > 0) { _ftprintf(f, _T("\n\n")); }
            fclose(f);
        }
    }

    for (int i = 0; i < len; i++) {
        BYTE c = buff[i] & 0x7f;
        if (c >= 0x20) {
            static WCHAR charmap[0x60] = {
                ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', 0xE1, '+', ',', '-', '.', '/',
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', 0x3F,
                '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
                'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', 0xE9, ']', 0xED, 0xF3,
                0xFA, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
                'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0xE7, 0xF7, 'N', 'n', 0x3F
            };

            PutChar(charmap[c - 0x20]);
        } else if (buff[i] != 0x80 && i < len - 1) {
            // codes and special characters are supposed to be doubled
            if (i < len - 3 && buff[i] == buff[i + 2] && buff[i + 1] == buff[i + 3]) {
                i += 2;
            }

            c = buff[i + 1] & 0x7f;
            if (buff[i] == 0x91 && c >= 0x20 && c < 0x30) { // formating
                // TODO
            } else if (buff[i] == 0x91 && c == 0x39) { // transparent space
                OffsetCursor(1, 0);
            } else if (buff[i] == 0x91 && c >= 0x30 && c < 0x40) { // special characters
                static WCHAR charmap[0x10] = {
                    0x00ae, // (r)egistered
                    0x00b0, // degree
                    0x00bd, // 1/2
                    0x00bf, // inverted question mark
                    0x2122, // trade mark
                    0x00a2, // cent
                    0x00a3, // pound
                    0x266a, // music
                    0x00e0, // a`
                    0x00ff, // transparent space, handled above
                    0x00e8, // e`
                    0x00e2, // a^
                    0x00ea, // e^
                    0x00ee, // i^
                    0x00f4, // o^
                    0x00fb, // u^
                };

                PutChar(charmap[c - 0x30]);
            } else if (buff[i] == 0x92 && c >= 0x20 && c < 0x40) { // extended characters
                static WCHAR charmap[0x20] = {
                    0x00c0, // A'
                    0x00c9, // E'
                    0x00d3, // O'
                    0x00da, // U'
                    0x00dc, // U:
                    0x00fc, // u:
                    0x2018, // `
                    0x00a1, // inverted !
                    0x002a, // *
                    0x2019, // '
                    0x002d, // -
                    0x00a9, // (c)opyright
                    0x2120, // SM
                    0x00b7, // . (dot in the middle)
                    0x201c, // inverted "
                    0x201d, // "

                    0x00c1, // A`
                    0x00c2, // A^
                    0x00c7, // C,
                    0x00c8, // E`
                    0x00ca, // E^
                    0x00cb, // E:
                    0x00eb, // e:
                    0x00ce, // I^
                    0x00cf, // I:
                    0x00ef, // i:
                    0x00d4, // O^
                    0x00d9, // U`
                    0x00f9, // u`
                    0x00db, // U^
                    0x00ab, // <<
                    0x00bb, // >>
                };

                PutChar(charmap[c - 0x20]);
            } else if (buff[i] == 0x13 && c >= 0x20 && c < 0x40) { // more extended characters
                static WCHAR charmap[0x20] = {
                    0x00c3, // A~
                    0x00e3, // a~
                    0x00cd, // I'
                    0x00cc, // I`
                    0x00ec, // i`
                    0x00d2, // O`
                    0x00f2, // o`
                    0x00d5, // O~
                    0x00f5, // o~
                    0x007b, // {
                    0x007d, // }
                    0x005c, // /* \ */
                    0x005e, // ^
                    0x005f, // _
                    0x00a6, // |
                    0x007e, // ~

                    0x00c4, // A:
                    0x00e4, // a:
                    0x00d6, // O:
                    0x00f6, // o:
                    0x00df, // B (ss in german)
                    0x00a5, // Y=
                    0x00a4, // ox
                    0x007c, // |
                    0x00c5, // Ao
                    0x00e5, // ao
                    0x00d8, // O/
                    0x00f8, // o/
                    0x250c, // |-
                    0x2510, // -|
                    0x2514, // |_
                    0x2518, // _|
                };

                PutChar(charmap[c - 0x20]);
            } else if (buff[i] == 0x94 && buff[i + 1] == 0xae) { // Erase Non-displayed [buffer] Memory
                memset(m_buff, 0, sizeof(m_buff));
            } else if (buff[i] == 0x94 && buff[i + 1] == 0x20) { // Resume Caption Loading
                memset(m_buff, 0, sizeof(m_buff));
            } else if (buff[i] == 0x94 && buff[i + 1] == 0x2f) { // End Of Caption
                if (memcmp(m_disp, m_buff, sizeof(m_disp)) != 0) {
                    if (m_fEndOfCaption) {
                        SaveDisp(time + (i / 2) * 1000 / 30);
                    }

                    m_fEndOfCaption = true;
                    memcpy(m_disp, m_buff, sizeof(m_disp));
                    m_time = time + (i / 2) * 1000 / 30;
                }
            } else if (buff[i] == 0x94 && buff[i + 1] == 0x2c) { // Erase Displayed Memory
                if (m_fEndOfCaption) {
                    m_fEndOfCaption = false;
                    SaveDisp(time + (i / 2) * 1000 / 30);
                }

                memset(m_disp, 0, sizeof(m_disp));
            } else if (buff[i] == 0x97 && (buff[i + 1] == 0xa1 || buff[i + 1] == 0xa2 || buff[i + 1] == 0x23)) { // Tab Over
                OffsetCursor(buff[i + 1] & 3, 0);
            } else if (buff[i] == 0x91 || buff[i] == 0x92 || buff[i] == 0x15 || buff[i] == 0x16
                       || buff[i] == 0x97 || buff[i] == 0x10 || buff[i] == 0x13 || buff[i] == 0x94) { // curpos, color, underline
                int row = 0;
                switch (buff[i]) {
                    default:
                    case 0x91:
                        row = 0;
                        break;
                    case 0x92:
                        row = 2;
                        break;
                    case 0x15:
                        row = 4;
                        break;
                    case 0x16:
                        row = 6;
                        break;
                    case 0x97:
                        row = 8;
                        break;
                    case 0x10:
                        row = 10;
                        break;
                    case 0x13:
                        row = 12;
                        break;
                    case 0x94:
                        row = 14;
                        break;
                }
                if (buff[i + 1] & 0x20) { row++; }

                int col = buff[i + 1] & 0xe;
                if (col == 0 || (col > 0 && !(buff[i + 1] & 0x10))) { col = 0; }
                else { col <<= 1; }

                MoveCursor(col, row);
            } else {
                int iiii = 0;
            }

            i++;
        }
    }
}
Example #3
0
/** Logs an unformatted message to a log file.
 * \param[in] iType - type of the log message (LT_*)
 * \param[in] bStd - log also to stdout/stderr if true
 * \param[in] pszStr - message string
 */
void log_file::logs(int_t iType, bool bStd, const tchar_t* pszStr)
{
	assert(m_pszPath);
	if(!m_pszPath)
		return;

	if (iType < m_iLogLevel || iType < 0 || iType >= sizeof(__logtype_str))
		return;
	
	// log time
	time_t t=time(NULL);
	tchar_t szData[128];
	_tcscpy(szData, _tctime(&t));
	size_t tLen=_tcslen(szData)-1;
	while(szData[tLen] == _t('\n'))
		szData[tLen--]=_t('\0');

	m_lock.lock();
	
	// check the size constraints
	truncate((int_t)(_tcslen(pszStr)+1));
#if defined(UNICODE) && (defined(_WIN32) || defined(_WIN64))
	FILE* pFile=_tfopen(m_pszPath, _t("ab"));
#else
	FILE* pFile=_tfopen(m_pszPath, _t("at"));
#endif
	bool bFailed=false;
	if (pFile)
	{
		if (_ftprintf(pFile, _t("[") TSTRFMT _t("] [") TSTRFMT _t("] ") TSTRFMT ENDL, szData, __logtype_str[iType], pszStr) < 0)
			bFailed=true;
		fclose(pFile);
	}
	else
		bFailed=true;
	if (bFailed || (m_bLogStd && !bStd))
	{
		switch(iType)
		{
		case level_error:
			_ftprintf(stderr, _t("[") TSTRFMT _t("] [") TSTRFMT _t("] ") TSTRFMT ENDL, szData, __logtype_str[iType], pszStr);
			break;
		default:
			_ftprintf(stdout, _t("[") TSTRFMT _t("] [") TSTRFMT _t("] ") TSTRFMT ENDL, szData, __logtype_str[iType], pszStr);
		}
	}
	else if (bStd)
	{
		switch(iType)
		{
		case level_error:
			_ftprintf(stderr, TSTRFMT _t(": ") TSTRFMT ENDL, __logtype_str[iType], pszStr);
			break;
		case level_info:
			_ftprintf(stdout, TSTRFMT ENDL, pszStr);
			break;
		default:
			_ftprintf(stdout, TSTRFMT _t(": ") TSTRFMT ENDL, __logtype_str[iType], pszStr);
		}
	}

	m_lock.unlock();
}
Example #4
0
// Write out the config file for the whole application
int ConfigAppSave()
{
	TCHAR szConfig[MAX_PATH];
	FILE *h;

	if (bCmdOptUsed) {
		return 1;
	}
	
#ifdef _UNICODE
	setlocale(LC_ALL, "");
#endif

	CreateConfigName(szConfig);

	if ((h = _tfopen(szConfig, _T("wt"))) == NULL) {
		return 1;
	}

	// Write title
	_ftprintf(h, _T("// ") _T(APP_TITLE) _T(" v%s --- Main Config File\n\n"), szAppBurnVer);
	_ftprintf(h, _T("// Don't edit this file manually unless you know what you're doing\n"));
	_ftprintf(h, _T("// ") _T(APP_TITLE) _T(" will restore default settings when this file is deleted\n"));

#define VAR(x) _ftprintf(h, _T(#x) _T(" %d\n"),  x)
#define VAR64(x) _ftprintf(h, _T(#x) _T(" %lf\n"),  (float)x)
#define FLT(x) _ftprintf(h, _T(#x) _T(" %lf\n"), x)
#define STR(x) _ftprintf(h, _T(#x) _T(" %s\n"),  x)

	_ftprintf(h, _T("\n// The application version this file was saved from\n"));
	// We can't use the macros for this!
	_ftprintf(h, _T("nIniVersion 0x%06X"), nBurnVer);

	_ftprintf(h, _T("\n\n\n"));
	_ftprintf(h, _T("// --- emulation --------------------------------------------------------------\n"));

	_ftprintf(h, _T("\n// If non-zero, use A68K for MC68000 emulation\n"));
	VAR(bBurnUseASMCPUEmulation);

	_ftprintf(h, _T("\n\n\n"));
	_ftprintf(h, _T("// --- Video ------------------------------------------------------------------\n"));

	// Horizontal oriented
	_ftprintf(h, _T("\n// (Horizontal Oriented) The display mode to use for fullscreen\n"));
	VAR(nVidHorWidth); VAR(nVidHorHeight);	
	_ftprintf(h, _T("\n// (Horizontal Oriented) If non-zero, use the same fullscreen resolution as the original arcade game\n"));
	VAR(bVidArcaderesHor);
	_ftprintf(h, _T("\n// (Horizontal Oriented) The preset resolutions appearing in the menu\n"));
	VAR(VidPreset[0].nWidth); VAR(VidPreset[0].nHeight);
	VAR(VidPreset[1].nWidth); VAR(VidPreset[1].nHeight);
	VAR(VidPreset[2].nWidth); VAR(VidPreset[2].nHeight);
	VAR(VidPreset[3].nWidth); VAR(VidPreset[3].nHeight);
	_ftprintf(h, _T("\n// (Horizontal Oriented) Full-screen size (0 = use display mode variables)\n"));
	VAR(nScreenSizeHor);

	// Vertical oriented
	_ftprintf(h, _T("\n// (Vertical Oriented) The display mode to use for fullscreen\n"));
	VAR(nVidVerWidth); VAR(nVidVerHeight);
	_ftprintf(h, _T("\n// (Vertical Oriented) If non-zero, use the same fullscreen resolution as the original arcade game\n"));
	VAR(bVidArcaderesVer);
	_ftprintf(h, _T("\n// (Vertical Oriented) The preset resolutions appearing in the menu\n"));
	VAR(VidPresetVer[0].nWidth); VAR(VidPresetVer[0].nHeight);
	VAR(VidPresetVer[1].nWidth); VAR(VidPresetVer[1].nHeight);
	VAR(VidPresetVer[2].nWidth); VAR(VidPresetVer[2].nHeight);
	VAR(VidPresetVer[3].nWidth); VAR(VidPresetVer[3].nHeight);
	_ftprintf(h, _T("\n// (Vertical Oriented) Full-screen size (0 = use display mode variables)\n"));
	VAR(nScreenSizeVer);

	_ftprintf(h, _T("\n// Full-screen bit depth\n"));
	VAR(nVidDepth);
	_ftprintf(h, _T("\n// Specify the refresh rate, 0 = default (changing this will not work with many video cards)\n"));
	VAR(nVidRefresh);
	_ftprintf(h, _T("\n// If non-zero, do not rotate the graphics for vertical games\n"));
	VAR(nVidRotationAdjust);
	_ftprintf(h, _T("\n// Initial window size (0 = autosize)\n"));
	VAR(nWindowSize);
	_ftprintf(h, _T("\n// Window position\n"));
	VAR(nWindowPosX); VAR(nWindowPosY);
	_ftprintf(h, _T("\n// If non-zero, perform gamma correction\n"));
	VAR(bDoGamma);
	_ftprintf(h, _T("\n// If non-zero, use the video hardware to correct gamma\n"));
	VAR(bVidUseHardwareGamma);
	_ftprintf(h, _T("\n// If non-zero, don't fall back on software gamma correction\n"));
	VAR(bHardwareGammaOnly);
	_ftprintf(h, _T("\n// Gamma to correct with\n"));
	FLT(nGamma);
	_ftprintf(h, _T("\n// If non-zero, auto-switch to fullscreen after loading game\n"));
	VAR(bVidAutoSwitchFull);
	_ftprintf(h, _T("\n// If non-zero, allow stretching of the image to any size\n"));
	VAR(bVidFullStretch);
	_ftprintf(h, _T("\n// If non-zero, stretch the image to the largest size preserving aspect ratio\n"));
	VAR(bVidCorrectAspect);
	_ftprintf(h, _T("\n// If non-zero, try to use a triple buffer in fullscreen\n"));
	VAR(bVidTripleBuffer);
	_ftprintf(h, _T("\n// If non-zero, try to synchronise blits with the display\n"));
	VAR(bVidVSync);
	_ftprintf(h, _T("\n// Transfer method:  0 = blit from system memory / use driver/DirectX texture management;\n"));
	_ftprintf(h, _T("//                   1 = copy to a video memory surface, then use bltfast();\n"));
	_ftprintf(h, _T("//                  -1 = autodetect for DirectDraw, equals 1 for Direct3D\n"));
	VAR(nVidTransferMethod);
	_ftprintf(h, _T("\n// If non-zero, draw scanlines to simulate a low-res monitor\n"));
	VAR(bVidScanlines);
	_ftprintf(h, _T("\n// Maximum scanline intensity\n"));
	VAR(nVidScanIntensity);
	_ftprintf(h, _T("\n// If non-zero, rotate scanlines and RGB effects for rotated games\n"));
	VAR(bVidScanRotate);
	_ftprintf(h, _T("\n// The selected blitter module\n"));
	VAR(nVidSelect);
	_ftprintf(h, _T("\n// Options for the blitter modules\n"));
	VAR(nVidBlitterOpt[0]);
	VAR64(nVidBlitterOpt[1]);
	VAR(nVidBlitterOpt[2]);
	VAR(nVidBlitterOpt[3]);
	_ftprintf(h, _T("\n// If non-zero, attempt to auto-detect the monitor aspect ratio\n"));
	VAR(bMonitorAutoCheck);
	_ftprintf(h, _T("\n// The aspect ratio of the monitor\n"));
	VAR(nVidScrnAspectX);
	VAR(nVidScrnAspectY);
	_ftprintf(h, _T("\n// If non-zero, force all games to use a 60Hz refresh rate\n"));
	VAR(bForce60Hz);
	_ftprintf(h, _T("\n// If non-zero, skip frames when needed to keep the emulation running at full speed\n"));
	VAR(bAlwaysDrawFrames);

	_ftprintf(h, _T("\n// If non-zero, use a placeholder image when no game is loaded\n"));
	VAR(bVidUsePlaceholder);
	_ftprintf(h, _T("\n// The filename of the placeholder image to use (empty filename = use built-in)\n"));
	STR(szPlaceHolder);

	_ftprintf(h, _T("\n"));
	_ftprintf(h, _T("// --- DirectDraw blitter module settings -------------------------------------\n"));
	_ftprintf(h, _T("\n// If non-zero, draw scanlines at 50%% intensity\n"));
	VAR(bVidScanHalf);
	_ftprintf(h, _T("\n"));
	_ftprintf(h, _T("// --- Direct3D 7 blitter module settings -------------------------------------\n"));
	_ftprintf(h, _T("\n// If non-zero, use bi-linear filtering to display the image\n"));
	VAR(bVidBilinear);
	_ftprintf(h, _T("\n// If non-zero, simulate slow phosphors (feedback)\n"));
	VAR(bVidScanDelay);
	_ftprintf(h, _T("\n// If non-zero, use bi-linear filtering for the scanlines\n"));
	VAR(bVidScanBilinear);
	_ftprintf(h, _T("\n// Feedback amount for slow phosphor simulation\n"));
	VAR(nVidFeedbackIntensity);
	_ftprintf(h, _T("\n// Oversaturation amount for slow phosphor simulation\n"));
	VAR(nVidFeedbackOverSaturation);
	_ftprintf(h, _T("\n// Angle at wich the emulated screen is tilted (in radians)\n"));
	FLT(fVidScreenAngle);
	_ftprintf(h, _T("\n// Angle of the sphere segment used for the 3D screen (in radians)\n"));
	FLT(fVidScreenCurvature);
	_ftprintf(h, _T("\n// If non-zero, force 16 bit emulation even in 32-bit screenmodes\n"));
	VAR(bVidForce16bit);
	_ftprintf(h, _T("\n"));
	_ftprintf(h, _T("// --- DirectX Graphics 9 blitter module settings -----------------------------\n"));
	_ftprintf(h, _T("\n// The filter parameters for the cubic filter\n"));
	FLT(dVidCubicB);
	FLT(dVidCubicC);

	_ftprintf(h, _T("\n\n\n"));
	_ftprintf(h, _T("// --- Sound ------------------------------------------------------------------\n"));
	_ftprintf(h, _T("\n// The selected audio plugin\n"));
	VAR(nAudSelect);
	_ftprintf(h, _T("\n// Number of frames in sound buffer (= sound lag)\n"));
	VAR(nAudSegCount);
	_ftprintf(h, _T("\n// The order of PCM/ADPCM interpolation\n"));
	VAR(nInterpolation);
	_ftprintf(h, _T("\n// The order of FM interpolation\n"));
	VAR(nFMInterpolation);
	_ftprintf(h, _T("\n"));
	_ftprintf(h, _T("// --- DirectSound plugin settings --------------------------------------------\n"));
	_ftprintf(h, _T("\n// Sample rate\n"));
	VAR(nAudSampleRate[0]);
	_ftprintf(h, _T("\n// DSP module to use for sound enhancement: 0 = none, 1 = low-pass filter\n"));
	VAR(nAudDSPModule[0]);
	_ftprintf(h, _T("\n"));
	_ftprintf(h, _T("// --- XAudio2 plugin settings ------------------------------------------------\n"));
	_ftprintf(h, _T("\n// Sample rate\n"));
	VAR(nAudSampleRate[1]);
	_ftprintf(h, _T("\n// DSP module to use for sound enhancement: 0 = none, 1 = low-pass filter, 2 = reverb\n"));
	VAR(nAudDSPModule[1]);

	_ftprintf(h, _T("\n\n\n"));
	_ftprintf(h, _T("// --- UI ---------------------------------------------------------------------\n"));

	_ftprintf(h, _T("\n// Filename of the active UI translation template\n"));
	STR(szLocalisationTemplate);
	
	_ftprintf(h, _T("\n// Filename of the active game list translation template\n"));
	STR(szGamelistLocalisationTemplate);

	_ftprintf(h, _T("\n// 1 = display pause/record/replay/kaillera icons in the upper right corner of the display\n"));
	VAR(nVidSDisplayStatus);
	_ftprintf(h, _T("\n// Minimum height (in pixels) of the font used for the Kaillera chat function (used for arcade resolution)\n"));
	VAR(nMinChatFontSize);
	_ftprintf(h, _T("\n// Maximum height (in pixels) of the font used for the Kaillera chat function (used for 1280x960 or higher).\n"));
	VAR(nMaxChatFontSize);

	_ftprintf(h, _T("\n// Make the menu modeless\n"));
	VAR(bModelessMenu);

	_ftprintf(h, _T("\n// Minimum length of time to display the splash screen (in milliseconds)\n"));
	VAR(nSplashTime);

	_ftprintf(h, _T("\n// If non-zero, load and save all ram (the state)\n"));
	VAR(bDrvSaveAll);
	_ftprintf(h, _T("\n// The thread priority for the application. Do *NOT* edit this manually\n"));
	VAR(nAppThreadPriority);
	_ftprintf(h, _T("\n// If non-zero, process keyboard input even when the application loses focus\n"));
	VAR(bAlwaysProcessKeyboardInput);
	_ftprintf(h, _T("\n// If non-zero, pause when the application loses focus\n"));
	VAR(bAutoPause);
	_ftprintf(h, _T("\n// If non-zero, save the inputs for each game\n"));
	VAR(bSaveInputs);
	_ftprintf(h, _T("\n"));
	_ftprintf(h, _T("// --- Load Game Dialog -------------------------------------------------------\n"));
	_ftprintf(h, _T("\n// Load game dialog options\n"));
	VAR(nLoadMenuShowX);
	
	_ftprintf(h, _T("\n// Load game dialog board type filter options\n"));
	VAR(nLoadMenuBoardTypeFilter);
	
	_ftprintf(h, _T("\n// Load game dialog genre filter options\n"));
	VAR(nLoadMenuGenreFilter);
	
	_ftprintf(h, _T("\n// Load game dialog family filter options\n"));
	VAR(nLoadMenuFamilyFilter);

	_ftprintf(h, _T("\n// The paths to search for rom zips (include trailing backslash)\n"));
	STR(szAppRomPaths[0]);
	STR(szAppRomPaths[1]);
	STR(szAppRomPaths[2]);
	STR(szAppRomPaths[3]);
	STR(szAppRomPaths[4]);
	STR(szAppRomPaths[5]);
	STR(szAppRomPaths[6]);
	STR(szAppRomPaths[7]);
	
	_ftprintf(h, _T("\n// The paths to search for support files (include trailing backslash)\n"));
	STR(szAppPreviewsPath);
	STR(szAppTitlesPath);
	STR(szAppSelectPath);
	STR(szAppVersusPath);
	STR(szAppHowtoPath);
	STR(szAppScoresPath);
	STR(szAppBossesPath);
	STR(szAppGameoverPath);
	STR(szAppFlyersPath);
	STR(szAppMarqueesPath);
	STR(szAppControlsPath);
	STR(szAppCabinetsPath);
	STR(szAppPCBsPath);
	STR(szAppCheatsPath);
	STR(szAppHistoryPath);
	STR(szAppListsPath);
	STR(szAppDatListsPath);
	STR(szAppIpsPath);
	STR(szAppIconsPath);
	STR(szAppArchivesPath);
	STR(szAppHiscorePath);

	_ftprintf(h, _T("\n\n\n"));
	_ftprintf(h, _T("// --- miscellaneous ---------------------------------------------------------\n"));

	_ftprintf(h, _T("\n// If non-zero, use an image menu theme.\n"));
	VAR(nMenuUITheme);
	
	_ftprintf(h, _T("\n// If non-zero, don't change the status of the Num Lock key.\n"));
	VAR(bNoChangeNumLock);
	
	_ftprintf(h, _T("\n// If non-zero, write the decrypted Neo-Geo 'C' roms to disc.\n"));
	VAR(bSaveCRoms);
	
	_ftprintf(h, _T("\n// If non-zero, enable high score saving support.\n"));
	VAR(EnableHiscores);
	
	_ftprintf(h, _T("\n// The language index to use for the IPS Patch Manager dialog.\n"));
	VAR(nSelectedLanguage);

	_ftprintf(h, _T("\n// If non-zero, display drivers icons.\n"));
	VAR(bEnableIcons);

	_ftprintf(h, _T("\n// Specify icons display size, 0 = 16x16 , 1 = 24x24, 2 = 32x32.\n"));
	VAR(nIconsSize);

	_ftprintf(h, _T("\n// Previous games list.\n"));
	STR(szPrevGames[0]);
	STR(szPrevGames[1]);
	STR(szPrevGames[2]);
	STR(szPrevGames[3]);
	STR(szPrevGames[4]);
	STR(szPrevGames[5]);
	STR(szPrevGames[6]);
	STR(szPrevGames[7]);
	STR(szPrevGames[8]);
	STR(szPrevGames[9]);
	
	_ftprintf(h, _T("\n// Player default controls, number is the index of the configuration in the input dialog\n"));
	VAR(nPlayerDefaultControls[0]);
	STR(szPlayerDefaultIni[0]);
	VAR(nPlayerDefaultControls[1]);
	STR(szPlayerDefaultIni[1]);
	VAR(nPlayerDefaultControls[2]);
	STR(szPlayerDefaultIni[2]);
	VAR(nPlayerDefaultControls[3]);
	STR(szPlayerDefaultIni[3]);

	_ftprintf(h, _T("\n\n\n"));

#undef STR
#undef FLT
#undef VAR

	fclose(h);
	return 0;
}
Example #5
0
int 
CpInfo(int argc, _TCHAR* argv[])
{
	HNDAS hNDAS = NULL;
	NDASCOMM_CONNECTION_INFO ci;
	BOOL bResults;
	NDAS_DEVICE_ID SrcAddr1;
	NDASOP_RAID_INFO RaidInfo = {0};
	PTCHAR str;
	PTCHAR EmptyStr=_T("");
	DWORD MemberCount;
	DWORD i, j;
	DWORD Flags;
	PNDAS_OOS_BITMAP_BLOCK BmpBuffer = NULL;
	
	//
	//	Get arguments.
	//
	if(argc < 1) {
		_ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
		return -1;
	}
	_ftprintf(stderr, _T("RAID Info using %s as primary device \n"), argv[0]);

	// Argv[0]: SrcAddr1
	bResults = ConvertMacToNodeId(argv[0], &SrcAddr1);
	if (!bResults) {
		_ftprintf(stderr, _T("Invalid device ID.\n"));
		return -1;
	}
	SrcAddr1.VID = 1; // to do: get VID as parameter

	SetLastError(0);
	API_CALL(NdasCommInitialize());

	ZeroMemory(&ci, sizeof(ci));
	ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
	ci.AddressType = NDASCOMM_CIT_DEVICE_ID; 
	ci.UnitNo = 0; /* Use first Unit Device */
	ci.WriteAccess = FALSE; /* Connect with read-write privilege */
	ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
	ci.OEMCode.UI64Value = 0; /* Use default password */
	ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */
	ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */

	ci.Address.DeviceId = SrcAddr1;
	ci.Address.DeviceId.VID = 1;
	
	hNDAS = NdasCommConnect(&ci);
	if (!hNDAS) {
		_ftprintf(stdout, _T("Cannot connect\n"));
		goto out;
	}

	//
	// Get and dump RAID info
	//
	RaidInfo.Size = sizeof(RaidInfo);
 	bResults = NdasOpGetRaidInfo(hNDAS,&RaidInfo);
	switch(RaidInfo.Type) {
		case NMT_SINGLE:		str=_T("Single"); break;
		case NMT_MIRROR:		str=_T("Mirror without repair info"); break;
		case NMT_AGGREGATE:		str=_T("Aggregation"); break;
		case NMT_RAID0:			str=_T("RAID0"); break;
		case NMT_RAID1:			str=_T("RAID1R1(~3.10)"); break;
		case NMT_RAID4:			str=_T("RAID4R1(~3.10)"); break;
		case NMT_RAID1R2:		str=_T("RAID1R2(3.11~)"); break;
		case NMT_RAID4R2:		str=_T("RAID4R2(3.11~)"); break;
		case NMT_RAID1R3:		str=_T("RAID1R3(3.20~)"); break;
		case NMT_RAID4R3:		str=_T("RAID4R3(3.20~)"); break;
		case NMT_AOD:			str=_T("Append only disk"); break;
		case NMT_VDVD:			str=_T("Virtual DVD"); break;
		case NMT_CDROM:		str=_T("packet device, CD / DVD"); break;
		case NMT_OPMEM:			str=_T("packet device, Magnetic Optical"); break;
		case NMT_FLASH:			str=_T("flash card"); break;
		case NMT_CONFLICT:		str=_T("DIB is conflicting"); break;
		default: str=_T("Unknown"); break;
	}
	_ftprintf(stdout, _T("Type: %s\n"), str);
	
	_ftprintf(stdout, _T("Mountability Flags: %x(%s%s%s%s%s%s)\n"), RaidInfo.MountablityFlags, 
		(RaidInfo.MountablityFlags & NDAS_RAID_MOUNTABILITY_UNMOUNTABLE)?_T("Unmountable "):EmptyStr,
		(RaidInfo.MountablityFlags & NDAS_RAID_MOUNTABILITY_MOUNTABLE)?_T("Mountable "):EmptyStr,
		(RaidInfo.MountablityFlags & NDAS_RAID_MOUNTABILITY_NORMAL)?_T("in normal mode "):EmptyStr,
		(RaidInfo.MountablityFlags & NDAS_RAID_MOUNTABILITY_DEGRADED)?_T("in degraded mode "):EmptyStr,
		(RaidInfo.MountablityFlags & NDAS_RAID_MOUNTABILITY_MISSING_SPARE)?_T("with missing spare"):EmptyStr,
		(RaidInfo.MountablityFlags & NDAS_RAID_MOUNTABILITY_SPARE_EXIST)?_T("with spare"):EmptyStr
	);

	_ftprintf(stdout, _T("Fail reason: %x(%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n"), RaidInfo.FailReason, 
		(RaidInfo.FailReason == NDAS_RAID_FAIL_REASON_NONE)?_T("None"):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_RMD_CORRUPTED)?_T("RMD corrupted "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_MEMBER_OFFLINE)?_T("Offline "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_DIB_MISMATCH)?_T("DIB mismatch "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_SPARE_USED)?_T("Spare used "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_INCONSISTENT_DIB)?_T("Inconsistent DIB "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_UNSUPPORTED_DIB_VERSION)?_T("Unsupported DIB version "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_MIGRATION_REQUIRED)?_T("Migration required"):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_UNSUPPORTED_RAID)?_T("Unsupported RAID type"):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_DEFECTIVE)?_T("Defective disk "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_DIFFERENT_RAID_SET)?_T("RAID set ID mismatch "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_MEMBER_NOT_REGISTERED)?_T("Unregistered "):EmptyStr,		
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_MEMBER_IO_FAIL)?_T("IO failure "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_NOT_A_RAID)?_T("Not a RAID "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_IRRECONCILABLE)?_T("Irreconcilable "):EmptyStr,
		(RaidInfo.FailReason & NDAS_RAID_FAIL_REASON_MEMBER_DISABLED)?_T("Disabled member "):EmptyStr
	);

	MemberCount = RaidInfo.MemberCount;
	
	_ftprintf(stdout, _T("RAID Set ID  = %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x\n"),
		RaidInfo.RaidSetId.Data1, RaidInfo.RaidSetId.Data2, RaidInfo.RaidSetId.Data3,
		RaidInfo.RaidSetId.Data4[0], RaidInfo.RaidSetId.Data4[1], RaidInfo.RaidSetId.Data4[2], RaidInfo.RaidSetId.Data4[3], 
		RaidInfo.RaidSetId.Data4[4], RaidInfo.RaidSetId.Data4[5], RaidInfo.RaidSetId.Data4[6], RaidInfo.RaidSetId.Data4[7]
	);
	_ftprintf(stdout, _T("Config Set ID= %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x\n"),
		RaidInfo.ConfigSetId.Data1, RaidInfo.ConfigSetId.Data2, RaidInfo.ConfigSetId.Data3,
		RaidInfo.ConfigSetId.Data4[0], RaidInfo.ConfigSetId.Data4[1], RaidInfo.ConfigSetId.Data4[2], RaidInfo.ConfigSetId.Data4[3], 
		RaidInfo.ConfigSetId.Data4[4], RaidInfo.ConfigSetId.Data4[5], RaidInfo.ConfigSetId.Data4[6], RaidInfo.ConfigSetId.Data4[7]
	);

	for(i=0;i<MemberCount;i++) {
		_ftprintf(stdout, _T(" * Member %d - DeviceId %02x:%02x:%02x:%02x:%02x:%02x-%02x Unit %d\n"),
			i, 
			RaidInfo.Members[i].DeviceId.Node[0], RaidInfo.Members[i].DeviceId.Node[1], RaidInfo.Members[i].DeviceId.Node[2], 
			RaidInfo.Members[i].DeviceId.Node[3], RaidInfo.Members[i].DeviceId.Node[4], RaidInfo.Members[i].DeviceId.Node[5], 
			RaidInfo.Members[i].DeviceId.VID, RaidInfo.Members[i].UnitNo
		);
		Flags = RaidInfo.Members[i].Flags;
		_ftprintf(stdout, _T("                Flags: %x(%s%s%s%s%s%s%s%s%s%s%s%s%s)\n"),
			Flags,
			(Flags & NDAS_RAID_MEMBER_FLAG_ACTIVE)?_T("Active member "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_SPARE)?_T("Spare "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_ONLINE)?_T("Online "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_OFFLINE)?_T("Offline "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_DIFFERENT_RAID_SET)?_T("Different RAID Set ID "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_IO_FAILURE)?_T("IO failure "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_RMD_CORRUPTED)?_T("RMD corrupted "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_DIB_MISMATCH)?_T("DIB mismatch "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_OUT_OF_SYNC)?_T("Out-of-sync "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_BAD_SECTOR)?_T("Bad sector "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_BAD_DISK)?_T("Bad disk "):EmptyStr,			
			(Flags & NDAS_RAID_MEMBER_FLAG_REPLACED_BY_SPARE)?_T("Replaced by spare "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_IRRECONCILABLE)?_T("Irreconcilable "):EmptyStr,
			(Flags & NDAS_RAID_MEMBER_FLAG_NOT_REGISTERED)?_T("Unregistered "):EmptyStr
		);
	}

	// Dump Bitmap info.
	if (RaidInfo.Type == NMT_RAID1R3) {
		NDAS_DIB_V2 DIB_V2;
		UINT32 OnBitCount;
		UINT32 BitCount;
		UINT32 BmpSectorCount;
		UINT32 CurBitCount;
		UCHAR OnBits[] = {1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7};
		UINT32 BitOn, BitOnStart, BitOnEnd;
		
		bResults = NdasCommBlockDeviceRead(
			hNDAS, 
			NDAS_BLOCK_LOCATION_DIB_V2, 
			1, 
			(PBYTE)&DIB_V2);
		if (!bResults) {
			goto out;
		}
		BitCount = (UINT32)((DIB_V2.sizeUserSpace + DIB_V2.iSectorsPerBit - 1)/DIB_V2.iSectorsPerBit);
		BmpSectorCount = (BitCount + NDAS_BIT_PER_OOS_BITMAP_BLOCK -1)/NDAS_BIT_PER_OOS_BITMAP_BLOCK;
		OnBitCount = 0;
		_ftprintf(stdout, _T("Bitmap sector per bit=0x%x, Bit count =0x%x, BmpSector count=0x%x\n"), 
			DIB_V2.iSectorsPerBit, BitCount, BmpSectorCount);
		BmpBuffer = (PNDAS_OOS_BITMAP_BLOCK) malloc(BmpSectorCount* 512);

		bResults =NdasCommBlockDeviceRead(hNDAS, NDAS_BLOCK_LOCATION_BITMAP, BmpSectorCount, (PBYTE)BmpBuffer);
		if (!bResults) {
			_ftprintf(stdout, _T("Failed to read BMP.\n"));
			goto out;
		}
		CurBitCount = 0;
		for(i=0;i<BmpSectorCount;i++) {
			_ftprintf(stdout, _T("  Bitmap sector %d, Seq head=%I64x, tail=%I64x\n"), i, BmpBuffer[i].SequenceNumHead,BmpBuffer[i].SequenceNumTail);
			BitOn = FALSE;
			BitOnStart = BitOnEnd = 0;
			for(j=0;j<NDAS_BYTE_PER_OOS_BITMAP_BLOCK * 8;j++) {
				if (BitOn == FALSE && (BmpBuffer[i].Bits[j/8] & OnBits[j%8])) {
					BitOn = TRUE;
					BitOnStart = i * NDAS_BYTE_PER_OOS_BITMAP_BLOCK * 8 + j;
					_ftprintf(stdout, _T("    Bit on from bit %x ~ "), BitOnStart);
				}
				if (BitOn == TRUE && (BmpBuffer[i].Bits[j/8] & OnBits[j%8]) == 0) {
					BitOn = FALSE;
					BitOnEnd = i * NDAS_BYTE_PER_OOS_BITMAP_BLOCK * 8 + j;
					_ftprintf(stdout, _T("%x\n"), BitOnEnd-1);
				}
				if (BmpBuffer[i].Bits[j/8] & OnBits[j%8]) 
					OnBitCount++;
				CurBitCount++;
				if (CurBitCount >= BitCount)
					break;
			}
			if (BitOn == TRUE) {
				_ftprintf(stdout, _T("%x\n"), i * NDAS_BYTE_PER_OOS_BITMAP_BLOCK * 8 + j);
			}
		}
		_ftprintf(stdout, _T("%d bit is on out of %d bits. %.1lf%% out-of-sync.\n"), OnBitCount, BitCount, ((double)OnBitCount)/BitCount*100);
	}
out:
	if(GetLastError()) {
		_ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
	}
	if(hNDAS)
	{
		NdasCommDisconnect(hNDAS);
		hNDAS = NULL;
	}
	if (BmpBuffer)
	{
		free(BmpBuffer);
	}
	NdasCommUninitialize();

	return GetLastError();


}
Example #6
0
int Blockporter::DoExport(const TCHAR* name, ExpInterface* ei, Interface* i, BOOL supressPrompts, DWORD options)
{
	INode* root;
	//caption and message for MessagesBoxes
	TCHAR msg[MB_BUFFER_LENGTH];
	TCHAR cap[MB_BUFFER_LENGTH];

	//Get the root node
	root = i->GetRootNode();

	//the node of our object should be a groupnode, which contains every object
	//we want to export
	i->PushPrompt(_T("Searching for Group..."));
	bool found = false;
	for(int idx = 0; idx < root->NumberOfChildren(); idx++)
	{
		if(root->GetChildNode(idx)->IsGroupHead())
		{
			//we found our group
			//next step is to make the group node our new root, because every object
			//we want is part of this group

			found = true;
			root = root->GetChildNode(idx);
			break;
		}
	}

	if(!found)
	{
		MessageBox(nullptr, GetString(IDS_ERROR_NO_GROUP, msg), GetString(IDS_GENERAL_ERROR, cap), MB_OK | MB_ICONERROR);
		return 0;
	}

	//Now that we have the groupnode let's compare the fileversions
	if(!IsNewModelVersion(name, root->GetName()))
	{
		if(MessageBox(nullptr, GetString(IDS_VER_TO_LOW_MSG, msg), GetString(IDS_VER_TO_LOW_CAP, cap), MB_YESNO | MB_ICONEXCLAMATION) == IDNO)
			return 1;
	}

	i->PushPrompt(_T("Opening File"));
	Interface14* iface = GetCOREInterface14();
	UINT code = iface->DefaultTextSaveCodePage(true);
	MaxSDK::Util::Path storageNamePath(name);
	storageNamePath.SaveBaseFile();
	switch (code & MaxSDK::Util::MaxStringDataEncoding::MSDE_CP_MASK)
	{
	case CP_UTF8:
		mStream = _tfopen(name, _T("wt, ccs=UFT-8"));
		break;
	case MaxSDK::Util::MaxStringDataEncoding::MSDE_CP_UTF16:
		mStream = _tfopen(name, _T("wt, ccs=UTF-16BE"));
		break;
	default:
		mStream = _tfopen(name, _T("wt"));
	}
	if(!mStream)
		return 0;

	//now we have our file stream, so let's write the header
	i->PushPrompt(_T("Writing Header"));
	WriteHeader(root->GetName(), root->NumberOfChildren());

	//now that we have the header written, let's iterate through the objects in the
	//group and export the meshes and lights

	INode* child;
    Point3 pMin(0,0,0), pMax(0,0,0);

	for(int idx = 0; idx < root->NumberOfChildren(); idx++)
	{
		child = root->GetChildNode(idx);
		i->PushPrompt(_T("Processing Object %s", child->GetName()));
		if(child->IsGroupHead())
		{
			MessageBox(nullptr, GetString(IDS_ERROR_TO_MANY_GROUPS, msg), GetString(IDS_GENERAL_ERROR, cap), MB_OK | MB_ICONERROR);
			continue;
		}

		ObjectState os = child->EvalWorldState(0);

		//let's take a look at the SuperClassID of the object
		//so we find out if it's a mesh or a light
		if(!os.obj)
			continue; //somehow this node doesn't have an object

        Box3 boundBox;

		switch(os.obj->SuperClassID())
		{
		case GEOMOBJECT_CLASS_ID:
			_ftprintf(mStream, _T("<ObjectID=%i>\n"), idx);
			i->PushPrompt(_T("Writing MeshData for Object %s", child->GetName()));
			boundBox = WriteMeshData(child, idx);
            pMin.x = (boundBox.Min().x < pMin.x) ? boundBox.Min().x : pMin.x;
            pMin.y = (boundBox.Min().y < pMin.y) ? boundBox.Min().y : pMin.y;
            pMax.x = (boundBox.Max().x > pMax.x) ? boundBox.Max().x : pMax.x;
            pMax.y = (boundBox.Max().y > pMax.y) ? boundBox.Max().y : pMax.y;
			i->PushPrompt(_T("Writing MaterialData for Object %s", child->GetName()));
			WriteMaterialData(child);
			_ftprintf(mStream, _T("</Object>\n"));
			break;
		//case LIGHT_CLASS_ID:
		//	WriteLightData(child, idx);
		//	break;
		}
	}

    //Write the Bounding Box
    _ftprintf(mStream, _T("<BoundingBox>\n"));
    _ftprintf(mStream, _T("\t<Min=%f,%f>\n"), pMin.x, pMin.y);
    _ftprintf(mStream, _T("\t<Max=%f,%f>\n"), pMax.x, pMax.y);
    _ftprintf(mStream, _T("</BoundingBox>\n"));
	//we are done exporting, so close the stream
	i->PushPrompt(_T("Closing file..."));
	fclose(mStream);

	MessageBox(nullptr, GetString(IDS_FINISH_MSG, msg), GetString(IDS_FINISH_CAP, cap), MB_OK | MB_ICONINFORMATION);

	return 1;
}
Example #7
0
int main( int argc, _TCHAR* argv[] )
{
    _TCHAR*  errorMsg;
    _TCHAR*  program;
    _TCHAR*  iniFile;
    _TCHAR*  ch;
    _TCHAR** configArgv = NULL;
    int 	 configArgc = 0;
    int      exitCode = 0;
    int      ret = 0;
    void *	 handle = 0;
    RunMethod 		runMethod;
    SetInitialArgs  setArgs;

    setlocale(LC_ALL, "");

    initialArgc = argc;
    initialArgv = malloc((argc + 1) * sizeof(_TCHAR*));
    memcpy(initialArgv, argv, (argc + 1) * sizeof(_TCHAR*));

    /*
     * Strip off any extroneous <CR> from the last argument. If a shell script
     * on Linux is created in DOS format (lines end with <CR><LF>), the C-shell
     * does not strip off the <CR> and hence the argument is bogus and may
     * not be recognized by the launcher or eclipse itself.
     */
    ch = _tcschr( argv[ argc - 1 ], _T_ECLIPSE('\r') );
    if (ch != NULL)
    {
        *ch = _T_ECLIPSE('\0');
    }

    /* Determine the full pathname of this program. */
    program = findProgram(argv);

    /* Parse configuration file arguments */
    iniFile = checkForIni(argc, argv);
    if (iniFile != NULL)
        ret = readConfigFile(iniFile, &configArgc, &configArgv);
    else
        ret = readIniFile(program, &configArgc, &configArgv);
    if (ret == 0)
    {
        parseArgs (&configArgc, configArgv);
    }

    /* Parse command line arguments           */
    /* Overrides configuration file arguments */
    parseArgs( &argc, argv );

    /* Special case - user arguments specified in the config file
     * are appended to the user arguments passed from the command line.
     */
    if (configArgc > 0)
    {
        createUserArgs(configArgc, configArgv, &argc, &argv);
    }

    /* Initialize official program name */
    officialName = name != NULL ? _tcsdup( name ) : getDefaultOfficialName(program);

    /* Find the directory where the Eclipse program is installed. */
    programDir = getProgramDir(program);

    /* Find the eclipse library */
    eclipseLibrary = findLibrary(eclipseLibrary, program);

    if(eclipseLibrary != NULL)
        handle = loadLibrary(eclipseLibrary);
    if(handle == NULL) {
        errorMsg = malloc( (_tcslen(libraryMsg) + _tcslen(officialName) + 10) * sizeof(_TCHAR) );
        _stprintf( errorMsg, libraryMsg, officialName );
        if (!suppressErrors)
            displayMessage( officialName, errorMsg );
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, errorMsg);
        free( errorMsg );
        exit( 1 );
    }

    setArgs = (SetInitialArgs)findSymbol(handle, SET_INITIAL_ARGS);
    if(setArgs != NULL)
        setArgs(initialArgc, initialArgv, eclipseLibrary);
    else {
        if(!suppressErrors)
            displayMessage(officialName, entryMsg);
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, entryMsg);
        exit(1);
    }

    runMethod = (RunMethod)findSymbol(handle, RUN_METHOD);
    if(runMethod != NULL)
        exitCode = runMethod(argc, argv, userVMarg);
    else {
        if(!suppressErrors)
            displayMessage(officialName, entryMsg);
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, entryMsg);
        exit(1);
    }
    unloadLibrary(handle);

    free( eclipseLibrary );
    free( programDir );
    free( program );
    free( officialName );

    return exitCode;
}
Example #8
0
    /*
     * Write error message to event log, console or pop-up window.
     *
     * If useGetLastError is 1, the last error returned from GetLastError()
     * is appended to pszMessage, separated by a ": ".
     *
     * eventLogType:                 MessageBox equivalent:
     * 
     * EVENTLOG_INFORMATION_TYPE     MB_ICONASTERISK
     * EVENTLOG_WARNING_TYPE         MB_ICONEXCLAMATION
     * EVENTLOG_ERROR_TYPE           MB_ICONSTOP
     * 
     */
VOID
ProcessError (WORD eventLogType, LPCTSTR pszMessage, int useGetLastError, int quiet)
{
  HANDLE hEventSource = NULL;
  TCHAR pszMessageFull[MAX_STR_SIZE]; /* Combined pszMessage and GetLastError */

  /*
   * If useGetLastError enabled, generate text from GetLastError() and append to
   * pszMessageFull
   */
  if (useGetLastError) {
  LPTSTR pErrorMsgTemp = NULL;
  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
		 FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),
		 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) & pErrorMsgTemp, 0, NULL);

    _sntprintf (pszMessageFull, CountOf(pszMessageFull), _T("%s: %s"), pszMessage, pErrorMsgTemp);
    if (pErrorMsgTemp) {
      LocalFree (pErrorMsgTemp);
      pErrorMsgTemp = NULL;
    }
  }
  else {
    _sntprintf (pszMessageFull, CountOf(pszMessageFull), _T("%s"), pszMessage);
  }
  
  hEventSource = RegisterEventSource (NULL, app_name_long);
  if (hEventSource != NULL) {
    LPCTSTR LogStr[1];
    LogStr[0] = pszMessageFull;
    
    if (ReportEvent (hEventSource, 
          eventLogType, 
          0,
          DISPLAY_MSG,	/* just output the text to the event log */
          NULL, 
          1, 
          0, 
          LogStr, 
          NULL)) {
    }
    else {
      LPTSTR pErrorMsgTemp = NULL;
      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
          FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),
          MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
          (LPTSTR) & pErrorMsgTemp, 0, NULL);
      _ftprintf(stderr,_T("Could NOT lot to Event Log.  Error returned from ReportEvent(): %s\n"),pErrorMsgTemp);
      if (pErrorMsgTemp) {
        LocalFree (pErrorMsgTemp);
        pErrorMsgTemp = NULL;
      }
    }
    DeregisterEventSource (hEventSource);
    }

      if (quiet) {
    _ftprintf(stderr,_T("%s\n"),pszMessageFull);
      }
      else {
    switch (eventLogType) {
      case EVENTLOG_INFORMATION_TYPE:
        MessageBox (NULL, pszMessageFull, app_name_long, MB_ICONASTERISK);
        break;
      case EVENTLOG_WARNING_TYPE:
        MessageBox (NULL, pszMessageFull, app_name_long, MB_ICONEXCLAMATION);
        break;
      case EVENTLOG_ERROR_TYPE:
        MessageBox (NULL, pszMessageFull, app_name_long, MB_ICONSTOP);
        break;
      default:
        MessageBox (NULL, pszMessageFull, app_name_long, EVENTLOG_WARNING_TYPE);
        break;
      }
    }
}
Example #9
0
int _tmain(int argc, _TCHAR* argv[])
{
	if ( argc < 4 )
	{
		_tprintf( _T("SkinUpdate ") _VERSION_
			_T("\nUsage: SkinUpdate.exe input.h input.rc output.xml\n") );
		return 1;
	}

	LPCTSTR szOutput = NULL;

	for ( int i = 1 ; i < argc ; i++ )
	{
		LPCTSTR szFilename = PathFindFileName( argv[ i ] );
		LPCTSTR szExt = PathFindExtension( szFilename );
		if ( _tcscmp( szExt, _T(".h") ) == 0 )
		{
			if ( ! LoadIDs( argv[ i ] ) )
			{
				_tprintf( _T("Error: Filed to load IDs from: %s\n"), szFilename );
				return 1;
			}
			_tprintf(
				_T("Loaded from %s:\n")
				_T("  %d IDs\n"),
				szFilename, g_oIDs.GetCount() );
		}
		else if ( _tcscmp( szExt, _T(".rc") ) == 0 )
		{
			if ( ! LoadResources( argv[ i ] ) )
			{
				_tprintf( _T("Error: Filed to load strings from: %s\n"), szFilename );
				return 1;
			}
			_tprintf(
				_T("Loaded from %s:\n")
				_T("  %d strings\n")
				_T("  %d guidelines\n")
				_T("  %d dialogs\n")
				_T("  %d icons\n")
				_T("  %d bitmaps\n")
				_T("  %d htmls\n"),
				szFilename,
				g_oStrings.GetCount(),
				g_oGuidelines.GetCount(),
				g_oDialogs.GetCount(),
				g_oIcons.GetCount(),
				g_oBitmaps.GetCount(),
				g_oHtmls.GetCount() );
		}
		else if ( _tcscmp( szExt, _T(".xml") ) == 0 )
		{
			szOutput = argv[ i ];
		}
		else
		{
			_tprintf( _T("Error: Unknown file extension: %s\n"), szExt );
			return 1;
		}
	}

	for ( POSITION pos = g_oDialogs.GetStartPosition() ; pos ; )
	{
		CStringA sID;
		UINT nID;
		g_oDialogs.GetNextAssoc( pos, sID, nID );

		if ( ! g_oGuidelines.Lookup( sID, nID ) )
			_tprintf( _T("Warning: Found dialog \"%hs\" without guideline\n"), sID );
	}

	for ( POSITION pos = g_oIDs.GetStartPosition() ; pos ; )
	{
		CStringA sID;
		UINT nID;
		g_oIDs.GetNextAssoc( pos, sID, nID );

		if ( _strnicmp( sID, "IDI_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oIcons.Lookup( sID, nFoo ) )
				_tprintf( _T("Warning: Found orphan icon ID \"%hs\"\n"), sID );
		}
		else if ( _strnicmp( sID, "IDR_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oBitmaps.Lookup( sID, nFoo ) &&
				 ! g_oIcons.Lookup( sID, nFoo ) &&
				 ! g_oHtmls.Lookup( sID, nFoo ) )
			{
				_tprintf( _T("Warning: Found orphan bitmap/icon/html ID \"%hs\"\n"), sID );
			}
		}
		else if ( _strnicmp( sID, "IDB_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oBitmaps.Lookup( sID, nFoo ) )
				_tprintf( _T("Warning: Found orphan bitmap ID \"%hs\"\n"), sID );
		}
		else if ( _strnicmp( sID, "IDD_", 4 ) == 0 )
		{
			UINT nFoo;
			if ( ! g_oDialogs.Lookup( sID, nFoo ) )
				_tprintf( _T("Warning: Found orphan dialog ID \"%hs\"\n"), sID );
		}
		else if ( _strnicmp( sID, "IDS_", 4 ) == 0 )
		{
			CSSPair oFoo;
			if ( ! g_oStrings.Lookup( nID, oFoo ) )
				_tprintf( _T("Warning: Found orphan string ID \"%hs\"\n"), sID );
		}
		//else if ( _strnicmp( sID, "ID_", 3 ) == 0 )
		//{
		//	CSSPair oFoo;
		//	if ( ! g_oStrings.Lookup( nID, oFoo ) )
		//		_tprintf( _T("Warning: Found orphan string ID \"%hs\"\n"), sID );
		//}
	}

	// Sort by ID
	std::list< CStringA > indexTips;
	std::list< UINT > indexStrings;
	for ( POSITION pos = g_oStrings.GetStartPosition() ; pos ; )
	{
		UINT nID;
		CSSPair oPair;
		g_oStrings.GetNextAssoc( pos, nID, oPair );
		if ( nID < 30000 )	// Strings
			indexStrings.push_back( nID );
		else	// Tips
			indexTips.push_back( oPair.sSecond );
	}
	indexStrings.sort();
	indexTips.sort();

	if ( ! szOutput )
		szOutput = _T("default-en.xml");

	FILE* pFile = NULL;
	if ( _tfopen_s( &pFile, szOutput, _T("wt") ) != 0 )
	{
		_tprintf( _T("Error: Can't create output XML-file: %s\n"), szOutput );
		return 1;
	}

	// File header
	_ftprintf( pFile,
		_T("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n")
		_T("<skin xmlns=\"http://schemas.peerproject.org/Skin.xsd\" version=\"1.0\">\n\n") );

	// Manifest
	_ftprintf( pFile,
		_T("<!-- Manifest -->\n")
		_T("<manifest\tname=\"(translation language: English)\"\n")
		_T("\t\tauthor=\"(translation author)\"\n")
		_T("\t\tupdatedBy=\"(translation updaters)\"\n")
		_T("\t\tdescription=\"(translation description: PeerProject English Skin File)\"\n")
		_T("\t\tlink=\"(translation URL: http://peerproject.org)\"\n")
		_T("\t\temail=\"(author e-mail)\"\n")
		_T("\t\tversion=\"(PeerProject version)\"\n")
		_T("\t\ttype=\"Language\"\n")
		_T("\t\tlanguage=\"(translation language code: en)\"\n")
		_T("\t\tprompt=\"(translation prompt: Click here to select English as your natural language.)\"\n")
		_T("\t\tdir=\"(translation language direction: ltr or rtl)\"\n")
		_T("/>\n\n") );

	// Toolbars
	_ftprintf( pFile,
		_T("\t<!-- Toolbar Definitions -->\n\t<toolbars>\n")
		_T("\t</toolbars>\n\n") );

	// Menus
	_ftprintf( pFile,
		_T("\t<!-- Menu Definitions -->\n\t<menus>\n")
		_T("\t</menus>\n\n") );

	// Documents
	_ftprintf( pFile,
		_T("\t<!-- Documents -->\n\t<documents>\n")
		_T("\t</documents>\n\n") );

	// Command Tips
	_ftprintf( pFile,
		_T("\t<!-- Localised Command Tip Text. The \"message\" is displayed in the status bar, while the \"tip\" is shown in a tooltip -->\n\t<commandTips>\n") );
	for ( std::list< CStringA >::iterator i = indexTips.begin() ; i != indexTips.end() ; ++i )
	{
		UINT nID;
		ATLVERIFY( g_oIDs.Lookup( (*i), nID ) );
		CSSPair oPair;
		ATLVERIFY( g_oStrings.Lookup( nID, oPair ) );
		ATLASSERT( oPair.sSecond == (*i) );
		oPair.sFirst.Replace( "&", "&amp;" );
		oPair.sFirst.Replace( "�", "&#160;" );	// Not a space
		oPair.sFirst.Replace( "\"\"", "&quot;" );
		oPair.sFirst.Replace( "\\r\\n", "\\n" );
		int nPos = oPair.sFirst.Find( "\\n" );
		if ( nPos == -1 )
			_ftprintf( pFile, _T("\t\t<tip id=\"%hs\" message=\"%hs\"/>\n"), oPair.sSecond, oPair.sFirst );
		else
			_ftprintf( pFile, _T("\t\t<tip id=\"%hs\" message=\"%hs\" tip=\"%hs\"/>\n"), oPair.sSecond, oPair.sFirst.Left( nPos ), oPair.sFirst.Mid( nPos + 2 ) );
	}
	_ftprintf( pFile,
		_T("\t</commandTips>\n\n") );

	// Control Tips
	_ftprintf( pFile,
		_T("\t<!-- Tips displayed when mouse is moved over controls in the dialogs -->\n\t<controlTips>\n")
		_T("\t</controlTips>\n\n") );

	// Strings
	_ftprintf( pFile,
		_T("\t<!-- Localised Strings -->\n\t<strings>\n") );
	for ( std::list< UINT >::iterator i = indexStrings.begin() ; i != indexStrings.end() ; ++i )
	{
		CSSPair oPair;
		ATLVERIFY( g_oStrings.Lookup( (*i), oPair ) );
		oPair.sFirst.Replace( "&", "&amp;" );
		oPair.sFirst.Replace( "�", "&#160;" );	// Not a space
		oPair.sFirst.Replace( "\"\"", "&quot;" );
		oPair.sFirst.Replace( "\\r\\n", "\\n" );
		if ( (*i) < 7000 )	// Frames
			_ftprintf( pFile, _T("\t\t<string id=\"WINDOW_%hs\" value=\"%hs\"/>\n"), oPair.sSecond.Left( oPair.sSecond.GetLength() - 5 ).Mid( 4 ), oPair.sFirst );
		else
			_ftprintf( pFile, _T("\t\t<string id=\"%u\" value=\"%hs\"/>\n"), (*i), oPair.sFirst );
	}
	_ftprintf( pFile,
		_T("\t</strings>\n\n") );

	// Dialogs
	_ftprintf( pFile,
		_T("\t<!-- Localised Dialog Text, the \"cookie\" verifies that the dialog matches the skin -->\n")
		_T("\t<!-- Use DialogScan feature, do not edit dialogs manually -->\n\t<dialogs>\n")
		_T("\t</dialogs>\n\n") );

	// Columns
	_ftprintf( pFile,
		_T("\t<!-- Columns Definitions -->\n\t<listColumns>\n")
		_T("\t</listColumns>\n\n") );

	// EOF
	_ftprintf( pFile,
		_T("</skin>\n") );

	fclose( pFile );

	_tprintf( _T("Saved output XML-file: %s\n"), szOutput );

	return 0;
}
Example #10
0
int
CpSetMacAddress(int argc, _TCHAR* argv[])
{
    HNDAS hNDAS = NULL;
    NDASCOMM_CONNECTION_INFO ci;
    BYTE DeviceID[6];
    DWORD dwUnitNo;
    NDASCOMM_VCMD_PARAM param_vcmd;
    _TCHAR *MacAddress;
    size_t argv_len;
    ULONG	MacAddressSegs[6];

    //
    //	Get arguments.
    //
    if(argc < 3) {
        _ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
        return -1;
    }

    // Mac address : XX:XX:XX:XX:XX:XX
    MacAddress = argv[2];

    if(17 != _tcslen(MacAddress) ||
            _T(':') != MacAddress[2] ||
            _T(':') != MacAddress[5] ||
            _T(':') != MacAddress[8] ||
            _T(':') != MacAddress[11] ||
            _T(':') != MacAddress[14])
    {
        _ftprintf(stderr, _T("ERROR: Invalid MAC address. \n"));
        return -1;
    }

    if(6 != _stscanf(MacAddress, _T("%02X:%02X:%02X:%02X:%02X:%02X"),
                     &MacAddressSegs[0],
                     &MacAddressSegs[1],
                     &MacAddressSegs[2],
                     &MacAddressSegs[3],
                     &MacAddressSegs[4],
                     &MacAddressSegs[5]))
    {
        _ftprintf(stderr, _T("ERROR: Invalid MAC address. \n"));
        return -1;
    }

    _ftprintf(stdout, _T("Starting the operation...\n"));
    SetLastError(0);
    API_CALL(NdasCommInitialize());


    //
    //	Connect and login
    //

    ZeroMemory(&ci, sizeof(ci));
    ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
    ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */
    ci.UnitNo = 0; /* Use first Unit Device */
    ci.WriteAccess = FALSE; /* Connect with read-write privilege */
    ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
    ci.OEMCode.UI64Value = 0; /* Use default password */

    /* Log in as super user */
    ci.PrivilegedOEMCode = NDAS_DEFAULT_PRIVILEGED_OEM_CODE;
    /* Privileged Connection cannot use lock commands */
    ci.Flags = NDASCOMM_CNF_DISABLE_LOCK_CLEANUP_ON_CONNECT;

    ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */
    _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */
    _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */
    API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out);

    //
    //	Display NDAS device info
    //

    API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out);
    _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n",
             DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5],
             (int)dwUnitNo);


    //
    //	Set Mac address
    //

    _ftprintf(stderr, _T("Applying setting to the device...\n"));
    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));

    param_vcmd.SET_LPX_ADDRESS.AddressLPX[0] = (BYTE)MacAddressSegs[0];
    param_vcmd.SET_LPX_ADDRESS.AddressLPX[1] = (BYTE)MacAddressSegs[1];
    param_vcmd.SET_LPX_ADDRESS.AddressLPX[2] = (BYTE)MacAddressSegs[2];
    param_vcmd.SET_LPX_ADDRESS.AddressLPX[3] = (BYTE)MacAddressSegs[3];
    param_vcmd.SET_LPX_ADDRESS.AddressLPX[4] = (BYTE)MacAddressSegs[4];
    param_vcmd.SET_LPX_ADDRESS.AddressLPX[5] = (BYTE)MacAddressSegs[5];
    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_set_lpx_address, &param_vcmd, NULL, 0, NULL, 0), out);

    _ftprintf(stderr, _T("Resetting the device...\n"));
    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));
    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_reset, &param_vcmd, NULL, 0, NULL, 0), out);

out:
    if(GetLastError()) {
        _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
    }

    if(hNDAS)
    {
        NdasCommDisconnect(hNDAS);
        hNDAS = NULL;
    }

    NdasCommUninitialize();

    _ftprintf(stdout, _T("Finished the operation.\n"));

    return GetLastError();
}
Example #11
0
int
CpSetRetTime(int argc, _TCHAR* argv[])
{
    HNDAS hNDAS = NULL;
    NDASCOMM_CONNECTION_INFO ci;
    BYTE DeviceID[6];
    DWORD dwUnitNo;
    NDASCOMM_VCMD_PARAM param_vcmd;
    ULONG				retTime;

    //
    //	Get arguments.
    //
    if(argc < 3) {
        _ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
        return -1;
    }

    retTime = _tcstoul(argv[2], NULL, 10);
    if(retTime == 0) {

        //
        //	Check to see if a user inputs the zero.
        //

        if( argv[2][0] != _T('0') ||
                argv[2][1] != _T('\0')
          ) {
            _ftprintf(stderr, _T("ERROR: Invalid timeout value.\n"));
            return -1;
        }
    }



    _ftprintf(stdout, _T("Starting the operation...\n"));
    SetLastError(0);
    API_CALL(NdasCommInitialize());


    //
    //	Connect and login
    //

    ZeroMemory(&ci, sizeof(ci));
    ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
    ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */
    ci.UnitNo = 0; /* Use first Unit Device */
    ci.WriteAccess = FALSE; /* Connect with read-write privilege */
    ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
    ci.OEMCode.UI64Value = 0; /* Use default password */

    /* Log in as super user */
    ci.PrivilegedOEMCode = NDAS_DEFAULT_PRIVILEGED_OEM_CODE;
    /* Privileged Connection cannot use lock commands */
    ci.Flags = NDASCOMM_CNF_DISABLE_LOCK_CLEANUP_ON_CONNECT;

    ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */
    _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */
    _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */
    API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out);

    //
    //	Display NDAS device info
    //

    API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out);
    _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n",
             DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5],
             (int)dwUnitNo);


    //
    //	Set connection timeout
    //

    _ftprintf(stderr, _T("Applying setting to the device...\n"));
    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));

    param_vcmd.SET_RET_TIME.RetTime = retTime;
    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_set_ret_time, &param_vcmd, NULL, 0, NULL, 0), out);

    _ftprintf(stderr, _T("Resetting the device...\n"));
    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));
    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_reset, &param_vcmd, NULL, 0, NULL, 0), out);

out:
    if(GetLastError()) {
        _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
    }

    if(hNDAS)
    {
        NdasCommDisconnect(hNDAS);
        hNDAS = NULL;
    }

    NdasCommUninitialize();

    _ftprintf(stdout, _T("Finished the operation.\n"));

    return GetLastError();
}
Example #12
0
int
CpQueryConTimeout(int argc, _TCHAR* argv[])
{
    HNDAS hNDAS = NULL;
    NDASCOMM_CONNECTION_INFO ci;
    BYTE DeviceID[6];
    DWORD dwUnitNo;
    NDASCOMM_VCMD_PARAM param_vcmd;

    //
    //	Get arguments.
    //
    if(argc < 2) {
        _ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
        return -1;
    }

    _ftprintf(stdout, _T("Starting the operation...\n"));
    SetLastError(0);
    API_CALL(NdasCommInitialize());


    //
    //	Connect and login
    //

    ZeroMemory(&ci, sizeof(ci));
    ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
    ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */
    ci.UnitNo = 0; /* Use first Unit Device */
    ci.WriteAccess = FALSE; /* Connect with read-write privilege */
    ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
    ci.OEMCode.UI64Value = 0; /* Use default password */
    ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */
    ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */
    _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */
    _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */
    API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out);

    //
    //	Display NDAS device info
    //

    API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out);
    _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n",
             DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5],
             (int)dwUnitNo);


    //
    //	Query Connection timeout
    //

    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));
    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_get_max_conn_time, &param_vcmd, NULL, 0, NULL, 0), out);

out:
    if(GetLastError()) {
        _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
    }

    if(hNDAS)
    {
        NdasCommDisconnect(hNDAS);
        hNDAS = NULL;
    }

    NdasCommUninitialize();

    _ftprintf(stdout, _T("Finished the operation.\n"));

    _ftprintf(stderr, _T("\nConnection timeout: %d.\n"), param_vcmd.GET_MAX_CONN_TIME.MaxConnTime);

    return GetLastError();
}
Example #13
0
int
CpQueryLockOwner(int argc, _TCHAR* argv[])
{
    HNDAS hNDAS = NULL;
    NDASCOMM_CONNECTION_INFO ci;
    BYTE DeviceID[6];
    DWORD dwUnitNo;
    NDASCOMM_VCMD_PARAM param_vcmd;
    ULONG		lockIdx;

    //
    //	Get arguments.
    //
    if(argc < 3) {
        _ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
        return -1;
    }

    lockIdx = _tcstoul(argv[2], NULL, 10);
    if(lockIdx == 0) {

        //
        //	Check to see if a user inputs the zero.
        //

        if( argv[2][0] != _T('0') ||
                argv[2][1] != _T('\0')
          ) {
            _ftprintf(stderr, _T("ERROR: Invalid timeout value.\n"));
            return -1;
        }
    }



    _ftprintf(stdout, _T("Starting the operation...\n"));
    SetLastError(0);
    API_CALL(NdasCommInitialize());


    //
    //	Connect and login
    //

    ZeroMemory(&ci, sizeof(ci));
    ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
    ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */
    ci.UnitNo = 0; /* Use first Unit Device */
    ci.WriteAccess = FALSE; /* Connect with read-only privilege */
    ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
    ci.OEMCode.UI64Value = 0; /* Use default password */
    ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */
    ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */
    _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */
    _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */
    API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out );

    //
    //	Display NDAS device info
    //

    API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out);
    _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n",
             DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5],
             (int)dwUnitNo);


    //
    //	Query lock owner
    //

    _ftprintf(stderr, _T("Querying lock #%u's owner of  the device...\n"), (ULONG)(UINT8)lockIdx);
    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));
    param_vcmd.GET_OWNER_SEMA.Index = (UINT8)lockIdx;
    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_get_owner_sema, &param_vcmd, NULL, 0, NULL, 0), out);


out:
    if(GetLastError()) {
        _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
    } else {
        _ftprintf(stdout, _T("Owner's addr:%02X%02X%02X%02X%02X%02X%02X%02X\n"),
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[0],
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[1],
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[2],
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[3],
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[4],
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[5],
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[6],
                  param_vcmd.GET_OWNER_SEMA.AddressLPX[7]);
    }

    if(hNDAS)
    {
        NdasCommDisconnect(hNDAS);
        hNDAS = NULL;
    }

    NdasCommUninitialize();

    _ftprintf(stdout, _T("Finished the operation.\n"));

    return GetLastError();
}
Example #14
0
int
CpDeviceStandby(int argc, _TCHAR* argv[])
{
    HNDAS hNDAS = NULL;
    NDASCOMM_CONNECTION_INFO ci;
    BYTE DeviceID[6];
    DWORD dwUnitNo;
    NDASCOMM_IDE_REGISTER IdeRegister;

    //
    //	Get arguments.
    //
    if(argc < 2) {
        _ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
        return -1;
    }

    _ftprintf(stdout, _T("Starting the operation...\n"));
    SetLastError(0);
    API_CALL(NdasCommInitialize());


    //
    //	Connect and login
    //

    ZeroMemory(&ci, sizeof(ci));
    ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
    ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID*/
    ci.UnitNo = 0; /* Use first Unit Device */
    ci.WriteAccess = TRUE; /* Connect with read-write privilege */
    ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
    ci.OEMCode.UI64Value = 0; /* Use default password */
    ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */
    ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */
    _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */
    _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */
    API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out);

    //
    //	Display NDAS device info
    //

    API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out);
    _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n",
             DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5],
             (int)dwUnitNo);


    //
    //	Request the NDAS device to enter Standby mode
    //
    ZeroMemory(&IdeRegister, sizeof(NDASCOMM_IDE_REGISTER));
    IdeRegister.command.command = 0xE0; /* WIN_STANDBYNOW1 */
    IdeRegister.device.dev = 0;
    API_CALL_JMP(NdasCommIdeCommand(hNDAS, &IdeRegister, NULL, 0, NULL, 0), out);

out:
    if(GetLastError()) {
        _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
    }

    if(hNDAS)
    {
        NdasCommDisconnect(hNDAS);
        hNDAS = NULL;
    }

    NdasCommUninitialize();

    _ftprintf(stdout, _T("Finished the operation.\n"));

    return GetLastError();
}
Example #15
0
int initializeGageAS()
{
	fprintf(stdout, ("\nInitializing Gage card... "));

	/*
	Initializes the CompuScope boards found in the system. If the
	system is not found a message with the error code will appear.
	Otherwise i32Status will contain the number of systems found.
	*/
	i32Status = CsInitialize();

	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		return (-1);
	}

	/*
	Get the system. This sample program only supports one system. If
	2 systems or more are found, the first system that is found
	will be the system that will be used. hSystem will hold a unique
	system identifier that is used when referencing the system.
	*/
	i32Status = CsGetSystem(&g_hSystem, 0, 0, 0, 0);

	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		return (-1);
	}

	/*
	Get the handle for the events.
	Instead of polling for the system status, we will wait for specific events to occur.
	If the call did fail, (i.e. Events not supported) we should free the CompuScope system
	so it's available for another application
	*/
	i32Status = CsGetEventHandle(g_hSystem, ACQ_EVENT_TRIGGERED, &hTriggerEvent);
	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		CsFreeSystem(g_hSystem);
		return (-1);
	}

	i32Status = CsGetEventHandle(g_hSystem, ACQ_EVENT_END_BUSY, &hEndAcqEvent);
	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		CsFreeSystem(g_hSystem);
		return (-1);
	}

	/*
	Get System information. The u32Size field must be filled in
	prior to calling CsGetSystemInfo
	*/
	CsSysInfo.u32Size = sizeof(CSSYSTEMINFO);
	i32Status = CsGetSystemInfo(g_hSystem, &CsSysInfo);

	/*
	Display the system name from the driver
	*/
	_ftprintf(stdout, _T("Board Name: %s\n\n"), CsSysInfo.strBoardName);

	i32Status = CsAs_ConfigureSystem(g_hSystem, (int)CsSysInfo.u32ChannelCount, 1, (LPCTSTR)szIniFile, &u32Mode);

	if (CS_FAILED(i32Status))
	{
		if (CS_INVALID_FILENAME == i32Status)
		{
			/*
			Display message but continue on using defaults.
			*/
			_ftprintf(stdout, _T("\nCannot find %s - using default parameters."), szIniFile);
		}
		else
		{
			/*
			Otherwise the call failed.  If the call did fail we should free the CompuScope
			system so it's available for another application
			*/
			DisplayErrorString(i32Status);
			CsFreeSystem(g_hSystem);
			return(-1);
		}
	}
	/*
	If the return value is greater than  1, then either the application,
	acquisition, some of the Channel and / or some of the Trigger sections
	were missing from the ini file and the default parameters were used.
	*/
	if (CS_USING_DEFAULT_ACQ_DATA & i32Status)
		_ftprintf(stdout, _T("\nNo ini entry for acquisition. Using defaults."));

	if (CS_USING_DEFAULT_CHANNEL_DATA & i32Status)
		_ftprintf(stdout, _T("\nNo ini entry for one or more Channels. Using defaults for missing items."));

	if (CS_USING_DEFAULT_TRIGGER_DATA & i32Status)
		_ftprintf(stdout, _T("\nNo ini entry for one or more Triggers. Using defaults for missing items."));

	i32Status = CsAs_LoadConfiguration(g_hSystem, szIniFile, APPLICATION_DATA, &CsAppData);

	if (CS_FAILED(i32Status))
	{
		if (CS_INVALID_FILENAME == i32Status)
			_ftprintf(stdout, _T("\nUsing default application parameters."));
		else
		{
			DisplayErrorString(i32Status);
			CsFreeSystem(g_hSystem);
			return (-1);
		}
	}
	else if (CS_USING_DEFAULT_APP_DATA & i32Status)
	{
		/*
		If the return value is CS_USING_DEFAULT_APP_DATA (defined in ConfigSystem.h)
		then there was no entry in the ini file for Application and we will use
		the application default values, which were set in CsAs_LoadConfiguration.
		*/
		_ftprintf(stdout, _T("\nNo ini entry for application data. Using defaults"));
	}

	/*
	Commit the values to the driver.  This is where the values get sent to the
	hardware.  Any invalid parameters will be caught here and an error returned.
	*/
	i32Status = CsDo(g_hSystem, ACTION_COMMIT);
	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		CsFreeSystem(g_hSystem);
		return (-1);
	}
	/*
	Get acquisition config info for use afterwards.
	*/
	CsAcqCfg.u32Size = sizeof(CsAcqCfg);
	i32Status = CsGet(g_hSystem, CS_ACQUISITION, CS_ACQUISITION_CONFIGURATION, &CsAcqCfg);
	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		CsFreeSystem(g_hSystem);
		return (-1);
	}

	hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCtrlHandler(ControlHandler, TRUE);
	/*
	We need to allocate a buffer
	for transferring the data
	*/
	pBuffer = VirtualAlloc(NULL, (size_t)(CsAppData.i64TransferLength * CsAcqCfg.u32SampleSize), MEM_COMMIT, PAGE_READWRITE);
	if (NULL == pBuffer)
	{
		_ftprintf(stderr, _T("\nUnable to allocate memory\n"));
		CsFreeSystem(g_hSystem);
		return (-1);
	}

	/*
	We also need to allocate a buffer for transferring the timestamp
	*/
	pTimeStamp = (int64 *)VirtualAlloc(NULL, (size_t)(CsAppData.u32TransferSegmentCount * sizeof(int64)), MEM_COMMIT, PAGE_READWRITE);
	if (NULL == pTimeStamp)
	{
		_ftprintf(stderr, _T("\nUnable to allocate memory\n"));
		if (NULL != pBuffer)
			VirtualFree(pBuffer, 0, MEM_RELEASE);
		return (-1);
	}
	if (TYPE_FLOAT == CsAppData.i32SaveFormat)
	{
		/*
		Allocate another buffer to pass the data that is going to be converted
		into voltages
		*/
		pVBuffer = (float *)VirtualAlloc(NULL, (size_t)(CsAppData.i64TransferLength * sizeof(float)), MEM_COMMIT, PAGE_READWRITE);
		if (NULL == pVBuffer)
		{
			_ftprintf(stderr, _T("\nUnable to allocate memory\n"));
			CsFreeSystem(g_hSystem);
			if (NULL != pBuffer)
				VirtualFree(pBuffer, 0, MEM_RELEASE);
			if (NULL != pTimeStamp)
				VirtualFree(pTimeStamp, 0, MEM_RELEASE);
			return (-1);
		}
	}
	pDoubleData = (double *)VirtualAlloc(NULL, (size_t)(CsAppData.u32TransferSegmentCount * sizeof(double)), MEM_COMMIT, PAGE_READWRITE);

	/*
	We need to create the event in order to be notified of the completion
	*/
	hTransferEvent = CreateEvent(NULL, FALSE, FALSE, NULL);


	// Initialize savin variables

	nMeasureSize = (int)CsAppData.i64TransferLength;
	nMeasureTotal = (int)CsAppData.u32TransferSegmentCount;


	iRawData = new int16[nMeasureSize*nMeasureTotal];


	return 0;
}
Example #16
0
//******************************************************************
void Get_Call_Stack(PEXCEPTION_POINTERS pException, FILE* fp)
//******************************************************************
// Fill Str with call stack info.
// pException can be either GetExceptionInformation() or NULL.
// If pException = NULL - get current call stack.
{
	TCHAR	Module_Name[MAX_PATH];
	PBYTE	Module_Addr = 0;
	PBYTE	Module_Addr_1;
	
#pragma warning(disable: 4200)	//nonstandard extension used : zero-sized array in struct/union
	typedef struct STACK
	{
		STACK *	Ebp;
		PBYTE	Ret_Addr;
		DWORD	Param[0];
	} STACK, * PSTACK;
#pragma warning(default: 4200)

	STACK	Stack = {0, 0};
	PSTACK	Ebp;

	if (pException)		//fake frame for exception address
	{
		Stack.Ebp = (PSTACK)(DWORD_PTR)pException->ContextRecord->Ebp;
		Stack.Ret_Addr = (PBYTE)pException->ExceptionRecord->ExceptionAddress;
		Ebp = &Stack;
	}
	else
	{
		Ebp = (PSTACK)&pException - 1;	//frame addr of Get_Call_Stack()

		// Skip frame of Get_Call_Stack().
		if (!IsBadReadPtr(Ebp, sizeof(PSTACK)))
			Ebp = Ebp->Ebp;		//caller ebp
	}

	// Trace CALL_TRACE_MAX calls maximum - not to exceed DUMP_SIZE_MAX.
	// Break trace on wrong stack frame.
	for (int Ret_Addr_I = 0;
		(Ret_Addr_I < CALL_TRACE_MAX) && !IsBadReadPtr(Ebp, sizeof(PSTACK)) && !IsBadCodePtr(FARPROC(Ebp->Ret_Addr));
		Ret_Addr_I++, Ebp = Ebp->Ebp)
	{
		// If module with Ebp->Ret_Addr found.
		if (Get_Module_By_Ret_Addr(Ebp->Ret_Addr, Module_Name, Module_Addr_1))
		{
			if (Module_Addr_1 != Module_Addr)	//new module
			{
				// Save module's address and full path.
				Module_Addr = Module_Addr_1;
				_ftprintf(fp, _T("%08X  %s")NL, (LONG_PTR)Module_Addr, Module_Name);
			}

			// Save call offset.
			_ftprintf(fp, _T("  +%08X"), Ebp->Ret_Addr - Module_Addr);

			// Save 5 params of the call. We don't know the real number of params.
			if (pException && !Ret_Addr_I)	//fake frame for exception address
				_ftprintf(fp, _T("  Exception Offset") NL);
			else if (!IsBadReadPtr(Ebp, sizeof(PSTACK) + 5 * sizeof(DWORD)))
			{
				_ftprintf(fp, _T("  (%X, %X, %X, %X, %X)") NL,
					Ebp->Param[0], Ebp->Param[1], Ebp->Param[2], Ebp->Param[3], Ebp->Param[4]);
			}
		}
		else
			_ftprintf(fp, _T("%08X")NL, (LONG_PTR)(Ebp->Ret_Addr));
	}

} //Get_Call_Stack
Example #17
0
int saveGageData()
{

	/*
	Acquisition is now complete.
	Call the function TransferTimeStamp. This function is used to transfer the timestamp
	data. The i32TickFrequency, which is returned from this fuction, is the clock rate
	of the counter used to acquire the timestamp data.
	*/
	_ftprintf(stdout, "Transfering... ", u32ChannelNumber);
	_ftprintf(stdout, "Expected to take %d s... ", (int)((float)CsAppData.u32TransferSegmentCount*(94.0/1e6)));
	clock_t startClockTime = clock(), endClockTime;
	i32TickFrequency = TransferTimeStamp(hSystem, CsAppData.u32TransferSegmentStart, CsAppData.u32TransferSegmentCount, pTimeStamp);

	/*
	If TransferTimeStamp fails, i32TickFrequency will be negative,
	which represents an error code. If there is an error we'll set
	the time stamp info in pDoubleData to 0.
	*/
	ZeroMemory(pDoubleData, CsAppData.u32TransferSegmentCount * sizeof(double));
	if (CS_SUCCEEDED(i32TickFrequency))
	{
		/*
		Allocate a buffer of doubles to store the the timestamp data after we have
		converted it to microseconds.
		*/
		for (u32Count = 0; u32Count < CsAppData.u32TransferSegmentCount; u32Count++)
		{
			/*
			The number of ticks that have ocurred / tick count(the number of ticks / second)
			= the number of seconds elapsed. Multiple by 1000000 to get the number of
			mircoseconds
			*/
			pDoubleData[u32Count] = (double)(*(pTimeStamp + u32Count)) * 1.e6 / (double)(i32TickFrequency);
		}
	}

	/*
	Now transfer the actual acquired data for each desired multiple group.
	Fill in the InData structure for transferring the data
	*/
	InData.u32Mode = TxMODE_DEFAULT;
	InData.i64StartAddress = CsAppData.i64TransferStartPosition;
	InData.i64Length = CsAppData.i64TransferLength;
	InData.pDataBuffer = pBuffer;
	//u32ChannelIndexIncrement = CsAs_CalculateChannelIndexIncrement(&CsAcqCfg, &CsSysInfo);


	// transfer channel 1
	u32ChannelNumber = 1;


	int nMulRecGroup;
	int nTimeStampIndex;
	nRawMeasureCount = 0;

	/*
	Variable that will contain either raw data or data in Volts depending on requested format
	*/
	void* pSrcBuffer = NULL;

	ZeroMemory(pBuffer, (size_t)(CsAppData.i64TransferLength * CsAcqCfg.u32SampleSize));
	InData.u16Channel = (uInt16)u32ChannelNumber;



	for (nMulRecGroup = CsAppData.u32TransferSegmentStart, nTimeStampIndex = 0; nMulRecGroup < (int)(CsAppData.u32TransferSegmentStart + CsAppData.u32TransferSegmentCount);
		nMulRecGroup++, nTimeStampIndex++)
	{
		/*
		Transfer the captured data
		*/
		InData.u32Segment = (uInt32)nMulRecGroup;
		i32Status = CsTransfer(hSystem, &InData, &OutData);

		if (CS_FAILED(i32Status))
		{
			DisplayErrorString(i32Status);
			if (NULL != pBuffer)
				VirtualFree(pBuffer, 0, MEM_RELEASE);
			if (NULL != pVBuffer)
				VirtualFree(pVBuffer, 0, MEM_RELEASE);
			if (NULL != pTimeStamp)
				VirtualFree(pTimeStamp, 0, MEM_RELEASE);
			if (NULL != pDoubleData)
				VirtualFree(pDoubleData, 0, MEM_RELEASE);
			CsFreeSystem(hSystem);
			return (-1);
		}

		int16 *actualData = (int16 *)pBuffer;
		int nSkipSize = nRawMeasureCount*nMeasureSize;

		for (int i = 0; i < nMeasureSize; i++)
		{
			iRawData[i + nSkipSize] = actualData[i];
		}
		nRawMeasureCount++;
	}

	// transfer is finished
	endClockTime = clock() - startClockTime;
	_ftprintf(stdout, "Completed (%4.2f MB)\n", (float)(244*(float)InData.u32Segment) / 1000000.0);
	_ftprintf(stdout, "Transfer Completed in %d s.\n\n", (int)(endClockTime / (double)CLOCKS_PER_SEC));
	_ftprintf(stdout, "Saving Data... ");


	// Open Save files
	int nCount = 0;
	while (1)
	{		
		nCount++;
		_stprintf(PeakFileName, _T("E:\\GageData\\MechPeakDataScan%d.txt"),nCount);
		fidPeak = fopen(PeakFileName, "r");
			if (fidPeak)
			{
				fclose(fidPeak);
			}
			else
			{
				fidPeak = fopen(PeakFileName, "wb");
				break;
			}
	}		

	//_stprintf(PeakFileName, _T("E:\\GageData\\MechPeakData.txt"));
	//fidPeak = fopen(PeakFileName, "w");

	// Write depth
	_ftprintf(fidPeak, _T("%d\n"), nMeasureSize);

	int nSkipSize = nMeasureTotal*nMeasureSize;	

	fwrite(iRawData, sizeof(int16), (size_t)nSkipSize, fidPeak);	
	fclose(fidPeak);

	
	/*_stprintf(PeakFileName, _T("E:\\GageData\\MechPeakDataTest.txt"));
	fidPeak = fopen(PeakFileName, "w");
	_ftprintf(fidPeak, _T("%d\n"), nMeasureSize);
	
	for (int n = 0; n < nSkipSize; n++)
	{
	_ftprintf(fidPeak, _T("%d\n"), iRawData[n]); // print peakData
	}

	fclose(fidPeak); */ 
	fidPeak = NULL;

	_ftprintf(stdout, "Complete!\n\n");

	delete iRawData;
	return 0;
}
Example #18
0
void CreateExceptionDesc(PEXCEPTION_POINTERS pException, FILE* fp, DWORD dwLastError)
{
	if (!pException || !fp) return;

	EXCEPTION_RECORD &	E = *pException->ExceptionRecord;
	CONTEXT &			C = *pException->ContextRecord;

	//取得异常发生地
	TCHAR		szModeleInfo[MAX_PATH];
	TCHAR		Module_Name[MAX_PATH];
	PBYTE		Module_Addr;
	if (Get_Module_By_Ret_Addr((PBYTE)E.ExceptionAddress, Module_Name, Module_Addr))
	{
		_sntprintf(szModeleInfo, MAX_PATH, _T("%s"), Module_Name);
	}
	else
	{
		_sntprintf(szModeleInfo, MAX_PATH, _T("%08X"), (DWORD_PTR)(E.ExceptionAddress));
	}

	switch(E.ExceptionCode)
	{
	//核心软异常
	case 0XE000C0DE:
		{
			tException* pException = (tException*)E.ExceptionInformation[0];
			if(!pException) return;

			//断言错误
			if(pException->m_bAssert) 
			{
				_ftprintf(fp,
					_T("\t\tAssert  \n")
					_T("\n")
					_T("File:      %s\n")
					_T("Line:      %d\n")
					_T("Expr:      %s\n")
					_T("LastError: 0X%08X\n"),

					pException->m_strFileName.c_str(), 
					pException->m_nLineNum, 
					pException->m_strMessage.c_str(),
					pException->m_dwLastError);
			}
			else
			{
				_ftprintf(fp,
					_T("\t\tGeneral  \n")
					_T("\n")
					_T("Expr:      %s\n")
					_T("LastError: 0x%08X\n"),

					pException->m_strMessage.c_str(),
					pException->m_dwLastError);
			}
		}
		break;

		//试图对一个虚地址进行读写
	case EXCEPTION_ACCESS_VIOLATION:
		{
			// Access violation type - Write/Read.
			_ftprintf(fp,
				_T("\t\tAccess violation\n")
				_T("\n")
				_T("@:         %s\n")
				_T("Operate:   %s\n")
				_T("Address:   0x%08X\n")
				_T("LastError: 0x%08X\n"),
				szModeleInfo,
				(E.ExceptionInformation[0]) ? _T("Write") : _T("Read"), 
				E.ExceptionInformation[1], dwLastError);
		}
		break;

	default:
		{
			_ftprintf(fp,
				_T("\t\tOTHER\n")
				_T("\n")
				_T("@:         %s\n")
				_T("Code:      0x%08X\n")
				_T("LastError: 0x%08X\n"),
				szModeleInfo,
				E.ExceptionCode, dwLastError);
		}
		break;
	}

}
 inline void dump(FILE *f = stdout) const {
   _ftprintf(f, _T("%s"), toString().cstr());
 }
Example #20
0
//*************************************************************
void Get_Exception_Info(PEXCEPTION_POINTERS pException, FILE* fp, DWORD dwLastError)
//*************************************************************
// Allocate Str[DUMP_SIZE_MAX] and return Str with dump, if !pException - just return call stack in Str.
{
	int			i;
	TCHAR		Module_Name[MAX_PATH];
	PBYTE		Module_Addr;
	HANDLE		hFile;
	FILETIME	Last_Write_Time;
	FILETIME	Local_File_Time;
	SYSTEMTIME	T;
	
	Get_Version_Str(fp);

	_ftprintf(fp, _T("------------------------------------------------------------------------------")NL);
	_ftprintf(fp, _T("Process:  ") );

	GetModuleFileName(NULL, Module_Name, MAX_PATH);
	_ftprintf(fp, _T("%s") NL, Module_Name);

	// If exception occurred.
	if (pException)
	{
		EXCEPTION_RECORD &	E = *pException->ExceptionRecord;
		CONTEXT &			C = *pException->ContextRecord;

		// If module with E.ExceptionAddress found - save its path and date.
		if (Get_Module_By_Ret_Addr((PBYTE)E.ExceptionAddress, Module_Name, Module_Addr))
		{
			_ftprintf(fp, _T("Module:   %s") NL, Module_Name);

			if ((hFile = CreateFile(Module_Name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE)
			{
				if (GetFileTime(hFile, NULL, NULL, &Last_Write_Time))
				{
					FileTimeToLocalFileTime(&Last_Write_Time, &Local_File_Time);
					FileTimeToSystemTime(&Local_File_Time, &T);

					_ftprintf(fp, _T("Date Modified:  %02d/%02d/%d") NL, 
						T.wMonth, T.wDay, T.wYear);
				}
				CloseHandle(hFile);
			}
		}
		else
		{
			_ftprintf(fp, _T("Exception Addr:  %08X") NL , (LONG_PTR)(E.ExceptionAddress));
		}
		
		_ftprintf(fp, _T("------------------------------------------------------------------------------")NL);

		//加入具体异常解释信息
		CreateExceptionDesc(pException, fp, dwLastError);
		
		_ftprintf(fp, _T("------------------------------------------------------------------------------")NL);

		// Save instruction that caused exception.
		if(E.ExceptionAddress)
		{
			_ftprintf(fp, _T("Instruction: ")NL);
			for (i = 0; i < 16; i++)
				_ftprintf(fp, _T(" %02X"), PBYTE(E.ExceptionAddress)[i]);
		}
		// Save registers at exception.
		_ftprintf(fp, NL _T("Registers:") NL);
		_ftprintf(fp, _T("EAX: %08X  EBX: %08X  ECX: %08X  EDX: %08X") NL, C.Eax, C.Ebx, C.Ecx, C.Edx);
		_ftprintf(fp, _T("ESI: %08X  EDI: %08X  ESP: %08X  EBP: %08X")NL, C.Esi, C.Edi, C.Esp, C.Ebp);
		_ftprintf(fp, _T("EIP: %08X  EFlags: %08X")NL, C.Eip, C.EFlags);
	} //if (pException)
	
	_ftprintf(fp, _T("------------------------------------------------------------------------------")NL);

	// Save call stack info.
	_ftprintf(fp, _T("Call Stack:")NL);
	Get_Call_Stack(pException, fp);
} //Get_Exception_Info
Example #21
0
static void usage() {
  _ftprintf(stderr,_T("usage:sun [-platitude,longitude] [-ztimezone] [-yyear|-ddate]\n"));
  exit(-1);
}
Example #22
0
// 记录日志
int CLogMgr::LogEventArgs(int nLevel, LPCTSTR lpFormat, va_list argp)
{
	const int nBufLen = MAX_PATH * 2;
	TCHAR szBuf[nBufLen];

	int nStrLen=_vsntprintf_s(szBuf, nBufLen-1, lpFormat, argp);
	if(nStrLen>0) szBuf[nStrLen] = 0;

	FILE* lpFile = _tfopen(m_strLogFile, _T("a+"));
	if ( lpFile != NULL )
	{
		// 获取文件大小
		int nResult = -1;
		struct _stat FileBuff;
		nResult = T_STAT(m_strLogFile, &FileBuff);
		if (0 != nResult)
		{
			return -1;	// 获取文件大小失败
		}

		long lSize = FileBuff.st_size;

		// 文件大于设定大小需要进行转储,默认最大1MB
		if (lSize > m_nMaxLogFileSize)
		{
			fclose(lpFile);

			// 进行日志文件转储,转储时保证只保存指定个数的备份文件
			FileReName(m_strLogFile, m_strLogFileName + _T(".") + LOG_CONVEY_FILE_NAME);

			// 删除多余文件(规矩通配符规则和时间顺序删除,保留最新的若干文件)
			FileConveySave(m_strLogPath, m_strLogFileName + _T(".") + LOG_CONVEY_RULE, m_nMaxLogFileNumber);

			// 删除备份文件
			//_tunlink(m_strLogFile + _T(".bak"));
			// 重命名文件名为备份文件名
			//_trename(m_strLogFile, m_strLogFile + _T(".bak"));

			// 打开新文件
			lpFile = _tfopen(m_strLogFile, _T("w+"));//,ccs=UTF-8"));
			if (lpFile == NULL)
			{
				return -2;	// 打开可写的新文件失败
			}
		}

		SYSTEMTIME st;
		GetLocalTime(&st);

		CString strLevel;
		if (nLevel == LOG_LEVEL_DEBUG)
		{
			strLevel = __DEBUG;
		}
		else if (nLevel == LOG_LEVEL_INFO)
		{
			strLevel = __INFO;
		}
		else if (nLevel == LOG_LEVEL_ERROR)
		{
			strLevel = __ERROR;
		}
		else if (nLevel == LOG_LEVEL_CRITICAL)
		{
			strLevel = __CRITICAL;
		}
		else
		{
			strLevel = __DEBUG;
		}

		LPCTSTR lpStr = _tcschr(lpFormat, _T('\n'));
		if ( lpStr != NULL )
		{
			lpStr = _T("%s %02d-%02d-%02d %02d:%02d:%02d[%u] : %s");
		}
		else
		{
			lpStr = _T("%s %02d-%02d-%02d %02d:%02d:%02d[%u] : %s\n");
		}

		DWORD dwCurThreadID = GetCurrentThreadId();

		_ftprintf(lpFile, lpStr, strLevel, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, dwCurThreadID, szBuf);
		fclose(lpFile);
	}

	return 0;
}
Example #23
0
int 
CpComare(int argc, _TCHAR* argv[])
{
	HNDAS hNDAS1 = NULL;
	HNDAS hNDAS2 = NULL;	
	NDASCOMM_CONNECTION_INFO ci;
	BOOL bResults;
	PBYTE Buffer1 = NULL, Buffer2 = NULL;
	NDAS_DIB_V2 Dib;
	static const SectorPerOp = 64;
	NDAS_DEVICE_ID SrcAddr1, SrcAddr2;
	UINT64 StartAddr;
	UINT64 IoLength;
	UINT32 MisMatchCount;
	//
	//	Get arguments.
	//
	if(argc < 2) {
		_ftprintf(stderr, _T("ERROR: More parameter needed.\n"));
		return -1;
	}
	
	_ftprintf(stderr, _T("%s %s\n"), argv[0], argv[1]);
	
	// Argv[0]: SrcAddr1
	bResults = ConvertMacToNodeId(argv[0], &SrcAddr1);
	if (!bResults) {
		_ftprintf(stderr, _T("Invalid device ID.\n"));
		return -1;
	}
	SrcAddr1.VID = 1;
	
	bResults = ConvertMacToNodeId(argv[1], &SrcAddr2);
	if (!bResults) {
		_ftprintf(stderr, _T("Invalid device ID.\n"));
		return -1;
	}
	SrcAddr2.VID = 1;
	
	Buffer1 = (PBYTE)malloc(SectorPerOp * 512);
	Buffer2 = (PBYTE)malloc(SectorPerOp * 512);
	
	SetLastError(0);
	API_CALL(NdasCommInitialize());

	//
	//	Connect and login to source 1
	//

	ZeroMemory(&ci, sizeof(ci));
	ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
	ci.AddressType = NDASCOMM_CIT_DEVICE_ID; 
	ci.UnitNo = 0; /* Use first Unit Device */
	ci.WriteAccess = FALSE; /* Connect with read-write privilege */
	ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
	ci.OEMCode.UI64Value = 0; /* Use default password */
	ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */
	ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */

	ci.Address.DeviceId = SrcAddr1;
	
	API_CALL_JMP( hNDAS1 = NdasCommConnect(&ci), out);

	//
	//	Connect and login to source 2
	//

	ZeroMemory(&ci, sizeof(ci));
	ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
	ci.AddressType = NDASCOMM_CIT_DEVICE_ID; 
	ci.UnitNo = 0; /* Use first Unit Device */
	ci.WriteAccess = FALSE; /* Connect with read-write privilege */
	ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
	ci.OEMCode.UI64Value = 0; /* Use default password */
	ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */
	ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */

	ci.Address.DeviceId = SrcAddr2;
	
	API_CALL_JMP( hNDAS2 = NdasCommConnect(&ci), out);

	bResults = NdasCommBlockDeviceRead(
		hNDAS1, 
		NDAS_BLOCK_LOCATION_DIB_V2, 
		1, 
		(PBYTE)&Dib);
	if (!bResults) {
		goto out;
	}
	if (Dib.Signature != NDAS_DIB_V2_SIGNATURE) {
		_ftprintf(stdout, _T("Dib not found\n"));
		goto out;
	}
	// Compare 
	_ftprintf(stdout, _T("Comparing 0x%I64x sectors\n"), Dib.sizeUserSpace);
	StartAddr = 0;
	IoLength = SectorPerOp;
	MisMatchCount = 0;
	while(TRUE) {
		if (StartAddr + IoLength >= Dib.sizeUserSpace) {
			// Last part.
			IoLength = Dib.sizeUserSpace - StartAddr;
		} 
		bResults = NdasCommBlockDeviceRead(
			hNDAS1, 
			StartAddr, 
			IoLength, 
			Buffer1);
		if (!bResults) {
			_ftprintf(stdout, _T("Failed to read from source 1\n"));
			goto out;
		}
		bResults = NdasCommBlockDeviceRead(
			hNDAS2, 
			StartAddr, 
			IoLength, 
			Buffer2);
		if (!bResults) {
			_ftprintf(stdout, _T("Failed to read from source 2\n"));
			goto out;
		}
		if (memcmp(Buffer1, Buffer2, (size_t)IoLength * 512) == 0) {
			
		} else {
			MisMatchCount++;
			_ftprintf(stdout, _T("Mismatch at 0x%I64x:%x\n"), StartAddr, IoLength);
			if (MisMatchCount > 20) {
				_ftprintf(stdout, _T("Too much mismatch. Exiting\n"));	
				break;
			}
		}
		if (StartAddr%(100 * 1024 * 2)==0) { // Print progress in every 100M
			_ftprintf(stdout, _T("%d%%\n"), StartAddr*100/Dib.sizeUserSpace);
		}
		StartAddr += IoLength;
		if (StartAddr >= Dib.sizeUserSpace) {
			break;
		}
	}
out:
	if(GetLastError()) {
		_ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
	}
	if (Buffer1)
		free(Buffer1);
	if (Buffer2)
		free(Buffer2);
	if(hNDAS1)
	{
		NdasCommDisconnect(hNDAS1);
		hNDAS1 = NULL;
	}

	if(hNDAS2)
	{
		NdasCommDisconnect(hNDAS2);
		hNDAS2 = NULL;
	}

	NdasCommUninitialize();

	return GetLastError();
}
Example #24
0
static int Error(LPCTSTR str, LPCTSTR s, DWORD err) {
	if (s == NULL) { _ftprintf(stderr, str); }
	else { _ftprintf(stderr, str, s); }
	_ftprintf(stderr, TEXT(": %u\n\n"), err);
	return err;
}
Example #25
0
 void Visit(const Waypoint &wp) {
   _ftprintf(stdout, _T("%s, %f, %f, %.0fm\n"), wp.name.c_str(),
             (double)wp.location.latitude.Degrees(),
             (double)wp.location.longitude.Degrees(),
             (double)wp.elevation);
 }
Example #26
0
int initializeGage(float stepSize)
{
	/*
	Initializes the CompuScope boards found in the system. If the
	system is not found a message with the error code will appear.
	Otherwise i32Status will contain the number of systems found.
	*/
	i32Status = CsInitialize();

	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		return (-1);
	}
	/*
	Get the system. This sample program only supports one system. If
	2 systems or more are found, the first system that is found
	will be the system that will be used. hSystem will hold a unique
	system identifier that is used when referencing the system.
	*/
	i32Status = CsGetSystem(&hSystem, 0, 0, 0, 0);

	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		return (-1);
	}
	/*
	Get System information. The u32Size field must be filled in
	prior to calling CsGetSystemInfo
	*/
	CsSysInfo.u32Size = sizeof(CSSYSTEMINFO);
	i32Status = CsGetSystemInfo(hSystem, &CsSysInfo);

	/*
	Display the system name from the driver
	*/
	_ftprintf(stdout, _T("Gage Board Name: %s\n"), CsSysInfo.strBoardName);

	i32Status = CsAs_ConfigureSystem(hSystem, (int)CsSysInfo.u32ChannelCount, 1, (LPCTSTR)szIniFile, &u32Mode);

	if (CS_FAILED(i32Status))
	{
		if (CS_INVALID_FILENAME == i32Status)
		{
			/*
			Display message but continue on using defaults.
			*/
			_ftprintf(stdout, _T("\nCannot find %s - using default parameters."), szIniFile);
		}
		else
		{
			/*
			Otherwise the call failed.  If the call did fail we should free the CompuScope
			system so it's available for another application
			*/
			DisplayErrorString(i32Status);
			CsFreeSystem(hSystem);
			return(-1);
		}
	}
	/*
	If the return value is greater than  1, then either the application,
	acquisition, some of the Channel and / or some of the Trigger sections
	were missing from the ini file and the default parameters were used.
	*/
	if (CS_USING_DEFAULT_ACQ_DATA & i32Status)
		_ftprintf(stdout, _T("\nNo ini entry for acquisition. Using defaults."));

	if (CS_USING_DEFAULT_CHANNEL_DATA & i32Status)
		_ftprintf(stdout, _T("\nNo ini entry for one or more Channels. Using defaults for missing items."));

	if (CS_USING_DEFAULT_TRIGGER_DATA & i32Status)
		_ftprintf(stdout, _T("\nNo ini entry for one or more Triggers. Using defaults for missing items."));

	i32Status = CsAs_LoadConfiguration(hSystem, szIniFile, APPLICATION_DATA, &CsAppData);

	if (CS_FAILED(i32Status))
	{
		if (CS_INVALID_FILENAME == i32Status)
		{
			_ftprintf(stdout, _T("\nUsing default application parameters."));
		}
		else
		{
			DisplayErrorString(i32Status);
			CsFreeSystem(hSystem);
			return -1;
		}
	}
	else if (CS_USING_DEFAULT_APP_DATA & i32Status)
	{
		/*
		If the return value is CS_USING_DEFAULT_APP_DATA (defined in ConfigSystem.h)
		then there was no entry in the ini file for Application and we will use
		the application default values, which have already been set.
		*/
		_ftprintf(stdout, _T("\nNo ini entry for application data. Using defaults."));
	}

	/*
	Commit the values to the driver.  This is where the values get sent to the
	hardware.  Any invalid parameters will be caught here and an error returned.
	*/
	i32Status = CsDo(hSystem, ACTION_COMMIT);
	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		CsFreeSystem(hSystem);
		return (-1);
	}

	/*
	Get the current sample size, resolution and offset parameters from the driver
	by calling CsGet for the ACQUISTIONCONFIG structure. These values are used
	when saving the file.
	*/
	CsAcqCfg.u32Size = sizeof(CsAcqCfg);
	i32Status = CsGet(hSystem, CS_ACQUISITION, CS_ACQUISITION_CONFIGURATION, &CsAcqCfg);
	if (CS_FAILED(i32Status))
	{
		DisplayErrorString(i32Status);
		CsFreeSystem(hSystem);
		return (-1);
	}

	/*
	We need to allocate a buffer
	for transferring the data
	*/
	pBuffer = VirtualAlloc(NULL, (size_t)(CsAppData.i64TransferLength * CsAcqCfg.u32SampleSize), MEM_COMMIT, PAGE_READWRITE);
	if (NULL == pBuffer)
	{
		_ftprintf(stderr, _T("\nUnable to allocate memory\n"));
		CsFreeSystem(hSystem);
		return (-1);
	}

	/*
	We also need to allocate a buffer for transferring the timestamp
	*/
	pTimeStamp = (int64 *)VirtualAlloc(NULL, (size_t)(CsAppData.u32TransferSegmentCount * sizeof(int64)), MEM_COMMIT, PAGE_READWRITE);
	if (NULL == pTimeStamp)
	{
		_ftprintf(stderr, _T("\nUnable to allocate memory\n"));
		if (NULL != pBuffer)
			VirtualFree(pBuffer, 0, MEM_RELEASE);
		return (-1);
	}
	if (TYPE_FLOAT == CsAppData.i32SaveFormat)
	{
		/*
		Allocate another buffer to pass the data that is going to be converted
		into voltages
		*/
		pVBuffer = (float *)VirtualAlloc(NULL, (size_t)(CsAppData.i64TransferLength * sizeof(float)), MEM_COMMIT, PAGE_READWRITE);
		if (NULL == pVBuffer)
		{
			_ftprintf(stderr, _T("\nUnable to allocate memory\n"));
			CsFreeSystem(hSystem);
			if (NULL != pBuffer)
				VirtualFree(pBuffer, 0, MEM_RELEASE);
			if (NULL != pTimeStamp)
				VirtualFree(pTimeStamp, 0, MEM_RELEASE);
			return (-1);
		}
	}
	pDoubleData = (double *)VirtualAlloc(NULL, (size_t)(CsAppData.u32TransferSegmentCount * sizeof(double)), MEM_COMMIT, PAGE_READWRITE);


	// Initialize output variables
	nMeasureSize = (int)CsAppData.i64TransferLength;
	nMeasureTotal = (int)CsAppData.u32TransferSegmentCount;

	iRawData = new int16[nMeasureSize*nMeasureTotal];

	saveStage = new int*[2];
	for (int n = 0; n < 2; n++)
	{
		saveStage[n] = new int[nMeasureTotal];
	}


	// Open Save file
	_stprintf(SaveFileName, _T("E:\\GageData\\WideFOVData.txt"));
	fid = fopen(SaveFileName, "w");
	_ftprintf(fid, _T("%d\n%d\n"), nMeasureSize, (int)stepSize); // print stage location as first line
	fclose(fid);


	return (0);
}
static void usage() {
  _ftprintf( stderr, _T("Usage:CheckMnemonics [-rv] files\n"));
  exit(-1);
}
Example #28
0
int saveGageDataAS()
{
	int nMulRecGroup;
	int nTimeStampIndex;

	i32TickFrequency = TransferTimeStamp(g_hSystem, CsAppData.u32TransferSegmentStart, CsAppData.u32TransferSegmentCount, pTimeStamp);

	/*
	If TransferTimeStamp fails, i32TickFrequency will be negative,
	which represents an error code. If there is an error we'll set
	the time stamp info in pDoubleData to 0.
	*/
	ZeroMemory(pDoubleData, CsAppData.u32TransferSegmentCount * sizeof(double));
	if (CS_SUCCEEDED(i32TickFrequency))
	{
		/*
		Allocate a buffer of doubles to store the the timestamp data after we have
		converted it to microseconds.
		*/
		for (u32Count = 0; u32Count < CsAppData.u32TransferSegmentCount; u32Count++)
		{
			/*
			The number of ticks that have ocurred / tick count(the number of ticks / second)
			= the number of seconds elapsed. Multiple by 1000000 to get the number of
			mircoseconds
			*/
			pDoubleData[u32Count] = (double)(*(pTimeStamp + u32Count)) * 1.e6 / (double)(i32TickFrequency);
		}
	}

	/*
	Now transfer the actual acquired data for each desired multiple group.
	Fill in the InData structure for transferring the data
	*/
	InData.u32Mode = TxMODE_DEFAULT;
	InData.i64StartAddress = CsAppData.i64TransferStartPosition;
	InData.i64Length = CsAppData.i64TransferLength;
	InData.pDataBuffer = pBuffer;
	InData.hNotifyEvent = &hTransferEvent;

	u32ChannelIndexIncrement = CsAs_CalculateChannelIndexIncrement(&CsAcqCfg, &CsSysInfo);


	for (u32ChannelNumber = 1; u32ChannelNumber <= 1; u32ChannelNumber += u32ChannelIndexIncrement)
	{

		nRawMeasureCount = 0;

		InData.u16Channel = (uInt16)u32ChannelNumber;

		_ftprintf(stdout, "\tTransfer from channel %i: ", u32ChannelNumber);
		GetConsoleScreenBufferInfo(hConsole, &ScreenInfo);


		/*
		Variable that will contain either raw data or data in Volts depending on requested format
		*/
		void* pSrcBuffer = NULL;
		ZeroMemory(pBuffer, (size_t)(CsAppData.i64TransferLength * CsAcqCfg.u32SampleSize));
		InData.u16Channel = (uInt16)u32ChannelNumber;


		for (nMulRecGroup = CsAppData.u32TransferSegmentStart, nTimeStampIndex = 0; nMulRecGroup < (int)(CsAppData.u32TransferSegmentStart + CsAppData.u32TransferSegmentCount);
			nMulRecGroup++, nTimeStampIndex++)
		{
			InData.u32Segment = (uInt32)nMulRecGroup;

			/*
			Asynchronous Transfer Operation. Keep the token for progress report
			The token will be used further down to retrieve the status of the transfer.
			*/
			i32Status = CsTransferAS(g_hSystem, &InData, &OutData, &i32Token);
			if (CS_FAILED(i32Status))
			{
				DisplayErrorString(i32Status);
				CsFreeSystem(g_hSystem);
				CloseHandle(hTransferEvent);
				VirtualFree(pBuffer, 0, MEM_RELEASE);
				return (-1);
			}

			for (;;)
			{
				/*
				Wait 100 ms with the event created before
				Returning with WAIT_OBJECT_0 implies that the whole transfer has been completed
				Returning with WAIT_TIMEOUT implies that 100 ms have passed and the transfer is still going
				*/
				dwRet = WaitForSingleObject(hTransferEvent, 100);

				if (WAIT_OBJECT_0 == dwRet)
				{
					break;
				}
			}

			// Save to output variable
			int16 *actualData = (int16 *)pBuffer;
			int nSkipSize1 = nRawMeasureCount*nMeasureSize;

			if (u32ChannelNumber == 1)
			{
				for (int i = 0; i < nMeasureSize; i++)
				{
					iRawData[i + nSkipSize1] = actualData[i];
				}
			}
			nRawMeasureCount++;
		}

		i32Status = CsGetTransferASResult(g_hSystem, i32Token, &i64Bytes);
		_ftprintf(stdout, "Completed (%4.2f MB)\n", (float)(i64Bytes*InData.u32Segment) / 1000000.0);
	}


	// Open Save files
	_stprintf(PeakFileName, _T("E:\\GageData\\MechPeakData.txt"));
	fidPeak = fopen(PeakFileName, "w");

	// Write depth
	_ftprintf(fidPeak, _T("%d\n"), nMeasureSize);

	int nSkipSize = nMeasureTotal*nMeasureSize;

	/*
	for (int n = 0; n < nSkipSize; n++)
	{
		_ftprintf(fidPeak, _T("%d\n"), iRawData[n]); // print peakData
	}*/

	fwrite(iRawData, sizeof(int16), nSkipSize, fidPeak);


	fclose(fidPeak);
	fidPeak = NULL;


	delete iRawData;
	return 0;
}
Example #29
0
/////////////////////////////////////////////////////////////////////////////////////////
//// Enumerates through the values of the given key and store the values into the file.
//// Invokes "FormatDataWithDataType" function to format the data
//// 
//// Inputs	:	1. Handle to the key
////			2. Key name
////			3. File pointer
////			4. Full path of the key to store in the file
/////////////////////////////////////////////////////////////////////////////////////////
void CRegisterExport::EnumerateValues(HKEY hKey, CString cstrKey, FILE *fp, CString cstrFullPath)
{
	static HKEY hLastKey = hKey;
	LONG lResult;
	DWORD dwIndex = 0;
	HKEY hCurKey = hKey;
	DWORD dwKeyType; 
	DWORD dwKeyDataLength, dwKeyNameLen;
	LPBYTE pbbinKeyData = NULL; 
	TCHAR *tcKeyName = NULL;
	TCHAR tcDataType[1024] = _T("");

	lResult = RegOpenKeyEx(hCurKey, cstrKey, 0, KEY_QUERY_VALUE , &hKey);
	if(lResult != ERROR_SUCCESS)
		return;

	DWORD lNoOfValues = 0;
	DWORD lLongestKeyNameLen = 1;
	DWORD lLongestDataLen = 1;

	lResult = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &lNoOfValues, &lLongestKeyNameLen, &lLongestDataLen,
							NULL, NULL);
	
	if(lResult != ERROR_SUCCESS)
		return;

	_ftprintf(fp, _T("\n[%s]\n"), cstrFullPath);

	hLastKey = hKey;

	lLongestKeyNameLen++;
	lLongestDataLen++;

	tcKeyName =	new TCHAR[lLongestKeyNameLen];
	pbbinKeyData = new BYTE[lLongestDataLen];

	CString cstrFinalData, cstrTemp;

	while(TRUE)
	{
		memset(pbbinKeyData, 0, lLongestDataLen);
		memset(tcKeyName, 0, lLongestKeyNameLen);
		dwKeyType = dwKeyDataLength = dwKeyNameLen = 0;

		dwKeyNameLen = lLongestKeyNameLen;
		dwKeyDataLength = lLongestDataLen;

		lResult = RegEnumValue(hKey, dwIndex, tcKeyName, &dwKeyNameLen, NULL, &dwKeyType, pbbinKeyData, &dwKeyDataLength);
		if(lResult == ERROR_NO_MORE_ITEMS)
			break;

		FormatDataWithDataType(dwKeyType, pbbinKeyData, dwKeyDataLength, cstrFinalData);
	
		//// For (default) key names the tcKeyName is empty and dwKeyNameLen is zero ...in such case we need to 
		//// have assignment like @ = "value"
		CString cstrTest;
		cstrTest = tcKeyName;
		if(cstrTest.IsEmpty())
		{
			cstrTemp.Format(_T("@ = "));
		}
		else
		{
			cstrTemp.Format(_T("\"%s\" = "), tcKeyName);
		}
		cstrTemp += cstrFinalData;

		_ftprintf(fp, _T("%s"), (LPCTSTR)cstrTemp);
		dwIndex++;
	}
	RegCloseKey(hKey);
	delete tcKeyName;
	delete pbbinKeyData;
}
Example #30
0
int
CpSetEncryptionMode(int argc, _TCHAR* argv[])
{
    HNDAS hNDAS = NULL;
    NDASCOMM_CONNECTION_INFO ci;
    BYTE DeviceID[6];
    DWORD dwUnitNo;
    NDASCOMM_VCMD_PARAM param_vcmd;
    ULONG				HeaderEnc;
    ULONG				DataEnc;

    //
    //	Get arguments.
    //
    if(argc < 4) {
        _ftprintf(stderr, _T("ERROR: Header encryption mode and data encryption mode is required.\n"));
        return -1;
    }

    HeaderEnc = _tcstoul(argv[2], NULL, 10);
    if(HeaderEnc != 0 && HeaderEnc!=1) {
        _ftprintf(stderr, _T("ERROR: Avaiable header encryption mode is 0 (off) or 1 (hash encryption).\n"));
        return -1;
    }

    DataEnc = _tcstoul(argv[2], NULL, 10);
    if(DataEnc != 0 && DataEnc!=1) {
        _ftprintf(stderr, _T("ERROR: Avaiable header encryption mode is 0 (off) or 1 (hash encryption).\n"));
        return -1;
    }

    SetLastError(0);
    API_CALL(NdasCommInitialize());


    //
    //	Connect and login
    //

    ZeroMemory(&ci, sizeof(ci));
    ci.Size = sizeof(NDASCOMM_CONNECTION_INFO);
    ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */
    ci.UnitNo = 0; /* Use first Unit Device */
    ci.WriteAccess = FALSE; /* Connect with read-write privilege */
    ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */
    ci.OEMCode.UI64Value = 0; /* Use default password */

    /* Log in as super user */
    ci.PrivilegedOEMCode = NDAS_DEFAULT_PRIVILEGED_OEM_CODE;
    /* Privileged Connection cannot use lock commands */
    ci.Flags = NDASCOMM_CNF_DISABLE_LOCK_CLEANUP_ON_CONNECT;

    ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */
    _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */
    _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */
    API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out);

    //
    //	Display NDAS device info
    //

    API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out);
    _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n",
             DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5],
             (int)dwUnitNo);


    //
    //	Set encryption mode
    //

    _ftprintf(stderr, _T("Applying setting to the device...\n"));
    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));

    param_vcmd.SET_ENC_OPT.EncryptHeader = HeaderEnc;
    param_vcmd.SET_ENC_OPT.EncryptData = DataEnc;

    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_set_enc_opt, &param_vcmd, NULL, 0, NULL, 0), out);

    _ftprintf(stderr, _T("Resetting the device...\n"));
    ZeroMemory(&param_vcmd, sizeof(NDASCOMM_VCMD_PARAM));
    API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_reset, &param_vcmd, NULL, 0, NULL, 0), out);

out:
    if(GetLastError()) {
        _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError());
    }

    if(hNDAS)
    {
        NdasCommDisconnect(hNDAS);
        hNDAS = NULL;
    }

    NdasCommUninitialize();

    _ftprintf(stdout, _T("Finished the operation.\n"));

    return GetLastError();
}