Пример #1
0
DaemonConfig::DaemonConfig(std::string config_file, std::string config_defaults_file) {
  CSimpleIniA ini;
  ini.SetMultiKey();
  ini.LoadFile(config_file.c_str());
  
  CSimpleIniA defaultIni;
  defaultIni.SetMultiKey();
  defaultIni.LoadFile(config_defaults_file.c_str());
  
  // Stream will only be in the user override config, never in the defaults
  CSimpleIniA::TNamesDepend values;
  ini.GetAllValues("daemon", "stream", values);

  // sort the values into the original load order
  values.sort(CSimpleIniA::Entry::LoadOrder());

  // output all of the items
  CSimpleIniA::TNamesDepend::const_iterator i;
  for (i = values.begin(); i != values.end(); ++i) { 
      stream_urls.push_back(i->pItem);
  }

  country = getString(&ini, &defaultIni, "daemon", "country", "us");
  topn = getInt(&ini, &defaultIni, "daemon", "topn", 20);
  
  storePlates = getBoolean(&ini, &defaultIni, "daemon", "store_plates", false);
  imageFolder = getString(&ini, &defaultIni, "daemon", "store_plates_location", "/tmp/");
  uploadData = getBoolean(&ini, &defaultIni, "daemon", "upload_data", false);
  upload_url = getString(&ini, &defaultIni, "daemon", "upload_address", "");
  company_id = getString(&ini, &defaultIni, "daemon", "company_id", "");
  site_id = getString(&ini, &defaultIni, "daemon", "site_id", "");
  pattern = getString(&ini, &defaultIni, "daemon", "pattern", "");
}
Пример #2
0
////////////////////////////////////////////////////////////
/// Load & apply some settings
////////////////////////////////////////////////////////////
void MainClient::_loadGameSettings(void)
{
	CSimpleIniA ini;
	if(	ini.LoadFile("settings.ini") < 0 ){
		throw "Could not open the settings file!";
	}

	//Input .ini file settings
	info.debug			= ini.GetBoolValue("Settings", "debug");
	info.mapfile 		= ini.GetValue("Settings", "map");
	info.demoFile		= ini.GetValue("Settings", "demo");
	info.demoPlay		= ini.GetBoolValue("Settings", "play");
	info.demoRecord		= ini.GetBoolValue("Settings", "record");
	info.texturefile	= ini.GetValue("Settings", "textures");

	info.fullscreen 	= ini.GetBoolValue("Window", "fullscreen");
	info.window_width	= ini.GetLongValue("Window", "width");
	info.window_height	= ini.GetLongValue("Window", "height");
	info.cursorfile 	= ini.GetValue("Window", "cursor");

	info.fpslimit 		= ini.GetLongValue("Graphics", "fpslimit");
	info.frameskip 		= ini.GetLongValue("Graphics", "frameskip");

	/* Load the weapon list */
	CSimpleIniA weaponlist;
	weaponlist.LoadFile("assets/weaponlist.ini");

	CSimpleIniA::TNamesDepend keys;
	weaponlist.GetAllKeys("Weapons", keys);

	//Build Weapon definitions
	CSimpleIniA::TNamesDepend::const_iterator i;
	for(i = keys.begin(); i != keys.end(); ++i){
		//corresponds to the weapon select menu
		WeaponList.push_back(weaponlist.GetValue("Weapons", i->pItem));

		{
			//Push back a weapon info
			object::Weapon::Info winfo;
			std::string	path = WeaponList.back() + "/weapon.ini";

			object::Weapon::Info::Load(path.c_str(), &winfo);

			WeaponInfo.push_back(winfo);
		}
	}

} //void MainClient::_loadGameSettings(void)
Пример #3
0
int _tmain(int argc, _TCHAR* argv[])
{
	lua_State *L = lua_open();  /* create state */
	if (L != NULL) {		

		luaL_openlibs(L);  /* open libraries */
		luamodule_cjson(L);
		luamodule_cjson_safe(L);
		luamodule_md5(L);
		luamodule_des56(L);

		CSimpleIniA ini;
		ini.LoadFile("app.ini");

		const char* tmp;
		tmp = ini.GetValue("Application","libs.dir",NULL);
		if(tmp!=NULL) {
			std::string s(tmp);
			size_t last = 0;
			size_t index=s.find_first_of(";",last);
			while (index!=std::string::npos)
			{
				addSearchPath(L, s.substr(last,index-last).c_str());
				last=index+1;
				index=s.find_first_of(";",last);
			}
			if (index-last>0)
			{
				addSearchPath(L, s.substr(last,index-last).c_str());
			}			
		}
	}
	return luamain(L, argc,argv);
}
Пример #4
0
// ***********************************************************************
//
// INI FILE
//
bool GetOTAppDataFolderLocation(OTString strIniFileDefault, OTString & strOTServerDataLocation)
{
    CSimpleIniA ini;
    SI_Error rc = ini.LoadFile(strIniFileDefault.Get());
    if (rc >=0)
    {
        {
            const char * pVal = ini.GetValue("paths", "server_path", SERVER_PATH_DEFAULT); // todo stop hardcoding.
            
            if (NULL != pVal)
            {
                strOTServerDataLocation.Set(pVal);
                OTLog::vOutput(0, "Reading ini file (%s). \n Found Server data_folder path: %s \n", 
                               strIniFileDefault.Get(), strOTServerDataLocation.Get());
                return true;
            }
            
            OTLog::vOutput(0, "Reading ini file (%s) \n", strIniFileDefault.Get());
            return false;
        }            
    }
    else 
    {
        OTLog::vOutput(0, "Unable to load ini file (%s) to find data_folder path \n", 
                       strIniFileDefault.Get());
        return false;
    }
}
int AvgChoiceModule::init() {
  std::string config_path = "config.ini";

  CSimpleIniA ini;
  ini.SetMultiKey(true);

  if (ini.LoadFile(config_path.c_str()) < 0) {
    colorPrintf(ConsoleColor(ConsoleColor::red), "Can't load '%s' file!",
                config_path.c_str());
    return 1;
  }

  const char *db_path = ini.GetValue("statisctic", "db_path", NULL);
  if (!db_path) {
    colorPrintf(ConsoleColor(ConsoleColor::red), "Can't read db_path value");
    return 1;
  }

  int rc = sqlite3_open(db_path, &db);
  if (rc) {
    colorPrintf(ConsoleColor(ConsoleColor::red), "Can't open database: %s\n",
                sqlite3_errmsg(db));
    sqlite3_close(db);
    return (1);
  }
  return 0;
}
void ScriptSettings::Save() const {
	CSimpleIniA ini;
	ini.SetUnicode();
	ini.LoadFile(SETTINGSFILE);
	ini.SetValue("OPTIONS", "Enable", EnableManual ? " 1" : " 0");
	ini.SetLongValue("OPTIONS", "ShiftMode", ShiftMode);
	ini.SaveFile(SETTINGSFILE);
}
ApplicationConfiguration::ApplicationConfiguration(LPCSTR configurationFile)
{
    CSimpleIniA ini;
    ini.SetUnicode();
    ini.LoadFile(configurationFile);
    
    _isInViewSourceMode = ini.GetBoolValue("Debug", "ViewSource", false, false);
}
Пример #8
0
inline bool Filecache::reread() {
    if(stlplus::file_exists(filename)) {
        ini.LoadFile(filename.c_str());
        return true;
    } else {
        // File doesnt exist.
        return false;
    }
}
// ***********************************************************************
//
// INI FILE
//
bool GetOTAppDataFolderLocation(const OTString & strIniFileDefault, OTString & strOTServerDataLocation)
{
    CSimpleIniA ini;
    SI_Error rc = ini.LoadFile(strIniFileDefault.Get());
    if (rc >=0)
    {
        {
            const char * pVal = ini.GetValue("paths", "prefix_path", OT_PREFIX_DEFAULT); // todo stop hardcoding.
            
            if (NULL != pVal)
            {
                OTLog::SetPrefixPath(pVal);
                OTLog::vOutput(0, "server main: Reading ini file (%s). \n Found prefix_path: %s \n", 
                               strIniFileDefault.Get(), OTLog::PrefixPath());
            }
            else
                OTLog::vOutput(0, "server main:Ini file: %s: Failed to find prefix_path. \n", strIniFileDefault.Get());
        }            
        {
            const char * pVal = ini.GetValue("paths", "init_path", OT_FOLDER_DEFAULT); // todo stop hardcoding.
            
            if (NULL != pVal)
            {
                OTLog::SetConfigPath(pVal);
                OTLog::vOutput(0, "server main: Reading ini file (%s). \n Found Server init_path: %s \n", 
                               strIniFileDefault.Get(), OTLog::ConfigPath());
            }
            else
                OTLog::vOutput(0, "server main:Ini file: %s: Failed to find init_path. \n", strIniFileDefault.Get());
        }            
        {
            const char * pVal = ini.GetValue("paths", "server_path", SERVER_PATH_DEFAULT); // todo stop hardcoding.
            
            if (NULL != pVal)
            {
                strOTServerDataLocation.Set(pVal);
                OTLog::vOutput(0, "server main: Reading ini file (%s). \n Found Server data_folder path: %s \n", 
                               strIniFileDefault.Get(), strOTServerDataLocation.Get());
                return true;
            }
            
            OTLog::vOutput(0, "server main: Reading ini file (%s) \n", strIniFileDefault.Get());
            return false;
        }            
    }
    else 
    {
        OTLog::vOutput(0, "server main: Unable to load ini file (%s) to find data_folder path \n", 
                       strIniFileDefault.Get());
        return false;
    }
}
Пример #10
0
int main(int argc, const char *argv[])
{
    CSimpleIniA ini;
    ini.SetUnicode();
    ini.LoadFile("myfile.ini");
    const char * pVal = ini.GetValue("section", "key", "default");
    ini.SetValue("section", "key", "newvalue");

    std::string strData;
    ini.Save(strData);    
    printf("strData.c_str(): %s\n", strData.c_str());

    return 0;
}
Пример #11
0
void OneTweakConfig::ReadConfig()
{
	_MESSAGE(__FUNCTION__);

	inifilename = FullPathFromPath("OneTweak.ini");

	CSimpleIniA ini;
	ini.LoadFile(inifilename.c_str());

	version = ini.GetLongValue("Version", "Config");
	if (version != CONFIG_VERSION)
	{
		SaveConfig(&ini);
	}

	borderless.enabled = ini.GetBoolValue("Global", "BorderlessWindow");
	double_cursor_fix.enabled = ini.GetBoolValue("Global", "DoubleCursorFix");

	priority.enabled = ini.GetBoolValue("Global", "Priority");

	if (priority.enabled)
	{
		DWORD id_fg = ini.GetLongValue("Priority", "Foreground");
		DWORD id_bg = ini.GetLongValue("Priority", "Background");

		priority.high = PriorityIdToClass(id_fg);
		priority.low = PriorityIdToClass(id_bg);
	}

	if (borderless.enabled)
	{
		borderless.active = ini.GetBoolValue("BorderlessWindow", "Active");

		borderless.flags = ini.GetLongValue("BorderlessWindow", "StyleFlags");
		borderless.flagsEx = ini.GetLongValue("BorderlessWindow", "StyleFlagsEx");

		borderless.posX = ini.GetLongValue("BorderlessWindow", "WindowPosX");
		borderless.posY = ini.GetLongValue("BorderlessWindow", "WindowPosY");

		borderless.WindowWidth = ini.GetLongValue("BorderlessWindow", "WindowWidth");
		borderless.WindowHeight = ini.GetLongValue("BorderlessWindow", "WindowHeight");

		borderless.RenderWidth = ini.GetLongValue("BorderlessWindow", "RenderWidth");
		borderless.RenderHeight = ini.GetLongValue("BorderlessWindow", "RenderHeight");
	}

	directinput.nonexclusive = ini.GetBoolValue("DirectInput", "NonExclusive");

	OnReadConfig(&ini);
}
Пример #12
0
int main(void)
{
	CSimpleIniA ini;
	const char* filename="test.ini";
	ini.SetUnicode();
	ini.LoadFile(filename);
	ini.SetValue("node1","foo","foonew");
	const char* inivalue=ini.GetValue("node1","foo",NULL);
	printf("%s\n",inivalue);
	printf("end!\n");
	bool b=false;
	ini.SaveFile(filename,b);
	ini.Reset();
	return 0;
}
Пример #13
0
void parseIniFile(const string& filepath) throw(TCLAP::ArgException)
{
    CSimpleIniA inireader;
    inireader.SetUnicode();
    inireader.LoadFile(filepath.c_str());
    if(inireader.IsEmpty())
        throw(TCLAP::ArgException("Ini-File not found!", "-i"));

    _RESULT_DIRECTORY_NAME_ =       inireader.GetValue("detection", "result_directory_name", DEFAULT_RESULT_DIRECTORY_NAME);
    _WRITE_PROBABILITY_MAPS_ =      inireader.GetBoolValue("detection", "write_probability_maps", DEFAULT_WRITE_PROBABILITY_MAPS);
    _FILENAME_RESULT_SUFFIX_ =      inireader.GetValue("detection", "filename_result_suffix", DEFAULT_FILENAME_RESULT_SUFFIX);
    _PROB_MAP_RESULT_SUFFIX_ =      inireader.GetValue("detection", "prob_map_result_suffix", DEFAULT_PROB_MAP_RESULT_SUFFIX);
    _MAX_BOUNDINGBOX_OVERLAP_ =     inireader.GetDoubleValue("detection", "max_boundingbox_overlap", DEFAULT_MAX_BOUNDINGBOX_OVERLAP);

#ifndef PERFORM_EVALUATION
    _DETECTION_DEFAULT_THRESHOLD_ = inireader.GetValue("detection", "detection_default_threshold", DEFAULT_DETECTION_DEFAULT_THRESHOLD);
    _DETECTION_LABEL_THRESHOLDS_ =  inireader.GetValue("detection", "detection_label_thresholds", DEFAULT_DETECTION_LABEL_THRESHOLDS);
    _DETECTION_LABELS_ =            inireader.GetValue("detection", "detection_labels", DEFAULT_DETECTION_LABELS);
#else
    _DETECTION_DEFAULT_THRESHOLD_ = "0.15";
    _DETECTION_LABEL_THRESHOLDS_ = "";
    _DETECTION_LABELS_ = "";
#endif
    _LABEL_DELIMITER_ =      inireader.GetValue("training", "label_delimiter", DEFAULT_LABEL_DELIMITER);
    _MAX_BOOTSTRAP_STAGES_ = inireader.GetLongValue("training", "max_bootstrap_stages", DEFAULT_MAX_BOOTSTRAP_STAGES);

    _PATCH_WINDOW_SIZE_ = inireader.GetLongValue("common", "patch_window_size", DEFAULT_PATCH_SIZE);
    _IMG_FILE_EXTENTIONS_ = inireader.GetValue("common", "file_extentions", DEFAULT_IMG_FILE_EXTENTIONS);
    _BACKGROUND_LABEL_ = inireader.GetLongValue("common", "background_label", DEAFULT_BACKGROUND_LABEL);

//    cout << "Ini-file: " << endl;
//    DEBUG_COUT_VAR(_RESULT_DIRECTORY_NAME_);
//    DEBUG_COUT_VAR(_WRITE_PROBABILITY_MAPS_);
//    DEBUG_COUT_VAR(_FILENAME_RESULT_SUFFIX_);
//    DEBUG_COUT_VAR(_PROB_MAP_RESULT_SUFFIX_);
//    DEBUG_COUT_VAR(_MAX_BOUNDINGBOX_OVERLAP_);
//    DEBUG_COUT_VAR(_DETECTION_DEFAULT_THRESHOLD_);
//    DEBUG_COUT_VAR(_DETECTION_LABEL_THRESHOLDS_);
//    DEBUG_COUT_VAR(_DETECTION_LABELS_);
//    DEBUG_COUT_VAR(_LABEL_DELIMITER_);
//    DEBUG_COUT_VAR(_MAX_BOOTSTRAP_STAGES_);
//    DEBUG_COUT_VAR(_PATCH_WINDOW_SIZE_);
//    DEBUG_COUT_VAR(_IMG_FILE_EXTENTIONS_);
//    DEBUG_COUT_VAR(_BACKGROUND_LABEL_);
//    exit(-1);


}
int main(int argc, char *argv[])
{
    map<EVENT_TYPE, string> stringByEventType;
    stringByEventType[LICENSE_OK                      ] = "OK ";
    stringByEventType[LICENSE_FILE_NOT_FOUND          ] = "license file not found ";
    stringByEventType[LICENSE_SERVER_NOT_FOUND        ] = "license server can't be contacted ";
    stringByEventType[ENVIRONMENT_VARIABLE_NOT_DEFINED] = "environment variable not defined ";
    stringByEventType[FILE_FORMAT_NOT_RECOGNIZED      ] = "license file has invalid format (not .ini file) ";
    stringByEventType[LICENSE_MALFORMED               ] = "some mandatory field are missing, or data can't be fully read. ";
    stringByEventType[PRODUCT_NOT_LICENSED            ] = "this product was not licensed ";
    stringByEventType[PRODUCT_EXPIRED                 ] = "license expired ";
    stringByEventType[LICENSE_CORRUPTED               ] = "license signature didn't match with current license ";
    stringByEventType[IDENTIFIERS_MISMATCH            ] = "Calculated identifier and the one provided in license didn't match";
    stringByEventType[LICENSE_FILE_FOUND              ] = "license file not found ";
    stringByEventType[LICENSE_VERIFIED                ] = "license verified ";
    
    const string licLocation("example.lic");
    
    LicenseInfo licenseInfo;
    LicenseLocation licenseLocation;
    licenseLocation.openFileNearModule = false;
    licenseLocation.licenseFileLocation = licLocation.c_str();
    licenseLocation.environmentVariableName = "";
    EVENT_TYPE result = acquire_license("example", licenseLocation, &licenseInfo);
    PcSignature signature;
    FUNCTION_RETURN generate_ok = generate_user_pc_signature(signature, DEFAULT);

	if (result == LICENSE_OK && licenseInfo.linked_to_pc) {
        CSimpleIniA ini;
    	SI_Error rc = ini.LoadFile(licLocation.c_str());
        string IDinLicense = ini.GetValue("example", "client_signature", "");
		if (IDinLicense == "") {
            cout << "No client signature in license file, generate license with -s <id>";
			result = IDENTIFIERS_MISMATCH;
		} else if (IDinLicense != signature) {
			result = IDENTIFIERS_MISMATCH;
		}
	}

    if (result != LICENSE_OK) {
        cout << "license ERROR :" << endl;
        cout << "    " << stringByEventType[result].c_str() << endl;
        cout << "the pc signature is :" << endl;
        cout << "    " << signature << endl;
    }
    else
        cout << "license OK" << endl;
}
Пример #15
0
bool loadConfig(void)
{
	CSimpleIniA ini;
	ini.SetUnicode();
	ini.LoadFile("config.ini");
	const char* url = ini.GetValue("config", "url", "http://127.0.0.1/jieshui.php");
	if (NULL == url) {
		return false;
	}
	const char* timer = ini.GetValue("config", "timer", "10");
	if (NULL == timer) {
		return false;
	}
	g_jieshuiURL = new string(url);
	g_timer = atoi(timer);
	g_timer *= 1000;
	//cout << *g_jieshuiURL << endl << g_timer << endl;
	return true;
}
Пример #16
0
  void Config::loadCountryValues(string configFile, string country)
  {
    CSimpleIniA iniObj;
    iniObj.LoadFile(configFile.c_str());
    CSimpleIniA* ini = &iniObj;
    
    minPlateSizeWidthPx = getInt(ini, "", "min_plate_size_width_px", 100);
    minPlateSizeHeightPx = getInt(ini, "", "min_plate_size_height_px", 100);

    multiline = 	getBoolean(ini, "", "multiline",		false);

    plateWidthMM = getFloat(ini, "", "plate_width_mm", 100);
    plateHeightMM = getFloat(ini, "", "plate_height_mm", 100);

    charHeightMM = getFloat(ini, "", "char_height_mm", 100);
    charWidthMM = getFloat(ini, "", "char_width_mm", 100);
    charWhitespaceTopMM = getFloat(ini, "", "char_whitespace_top_mm", 100);
    charWhitespaceBotMM = getFloat(ini, "", "char_whitespace_bot_mm", 100);

    templateWidthPx = getInt(ini, "", "template_max_width_px", 100);
    templateHeightPx = getInt(ini, "", "template_max_height_px", 100);

    charAnalysisMinPercent = getFloat(ini, "", "char_analysis_min_pct", 0);
    charAnalysisHeightRange = getFloat(ini, "", "char_analysis_height_range", 0);
    charAnalysisHeightStepSize = getFloat(ini, "", "char_analysis_height_step_size", 0);
    charAnalysisNumSteps = getInt(ini, "", "char_analysis_height_num_steps", 0);

    segmentationMinBoxWidthPx = getInt(ini, "", "segmentation_min_box_width_px", 0);
    segmentationMinCharHeightPercent = getFloat(ini, "", "segmentation_min_charheight_percent", 0);
    segmentationMaxCharWidthvsAverage = getFloat(ini, "", "segmentation_max_segment_width_percent_vs_average", 0);

    plateLinesSensitivityVertical = getFloat(ini, "", "plateline_sensitivity_vertical", 0);
    plateLinesSensitivityHorizontal = getFloat(ini, "", "plateline_sensitivity_horizontal", 0);

    ocrLanguage = getString(ini, "", "ocr_language", "none");
    
    ocrImageWidthPx = round(((float) templateWidthPx) * ocrImagePercent);
    ocrImageHeightPx = round(((float)templateHeightPx) * ocrImagePercent);
    stateIdImageWidthPx = round(((float)templateWidthPx) * stateIdImagePercent);
    stateIdimageHeightPx = round(((float)templateHeightPx) * stateIdImagePercent);
    
  }
	void load(const char* filename) {
		CSimpleIniA ini;
		ini.SetUnicode();
		ini.LoadFile(filename);

		_mouseSensitivity = static_cast<float>(ini.GetDoubleValue("Controls", "Mouse Sensitivity", 0.5f));
		_displayWidth = ini.GetLongValue("Graphics", "Width", 640);
		_displayHeight = ini.GetLongValue("Graphics", "Height", 480);
		_fullscreen = ini.GetBoolValue("Graphics", "Fullscreen");
		_borderless = ini.GetBoolValue("Graphics", "Borderless");
		_fieldOfView = static_cast<float>(ini.GetDoubleValue("Graphics", "Field of View", 45.f));
		_showConsole = ini.GetBoolValue("Debug", "Show Console");
		_logging = ini.GetBoolValue("Debug", "Logging");
		_showMouseCursor = ini.GetBoolValue("Debug", "Show Mouse Cursor");
		_centerMouseCursor = ini.GetBoolValue("Debug", "Center Mouse Cursor", true);
		_showFPS = ini.GetBoolValue("Debug", "Show FPS", true);
		_showCursorCoordinates = ini.GetBoolValue("Debug", "Show Cursor Coords", true);
		_debugContext = ini.GetBoolValue("Debug", "Debug Context", false);
		*_startingScene = ini.GetValue("Debug", "Starting Scene", "default");
	}
void generate_license(const string& fname, const vector<string>& other_args) {
	int argc = 4+other_args.size();
	const char** argv = new const char*[argc + 1];
	unsigned int i=0;
	argv[i++] = "lic-generator";
	for(;i<=other_args.size();i++){
		argv[i] = other_args[i-1].c_str();
	}
	argv[i++] = "-o";
	argv[i++] = fname.c_str();
	argv[i++] = "TEST";
	int retCode = LicenseGenerator::generateLicense(argc, argv);
	delete[] (argv);
	BOOST_CHECK_EQUAL(retCode, 0);
	BOOST_ASSERT(fs::exists(fname));
	CSimpleIniA ini;
	SI_Error rc = ini.LoadFile(fname.c_str());
	BOOST_CHECK_GE(rc,0);
	int sectionSize = ini.GetSectionSize("TEST");
	BOOST_CHECK_GT(sectionSize,0);
}
Пример #19
0
bool SettingsManager::saveSettings()
{
	
	CSimpleIniA ini;
	ini.SetUnicode();
	ini.LoadFile("CONFIG.ini");

	if(ini.IsEmpty())
		{return false;}

	ini.SetValue("HIGHSCORE", "NAME", m_settings->HIGHSCORE_NAME.c_str());
	ini.SetLongValue("HIGHSCORE", "SCORE", m_settings->HIGHSCORE_SCORE);
	ini.SetValue("HIGHSCORE2", "NAME", m_settings->HIGHSCORE2_NAME.c_str());
	ini.SetLongValue("HIGHSCORE2", "SCORE", m_settings->HIGHSCORE2_SCORE);
	ini.SetValue("HIGHSCORE3", "NAME", m_settings->HIGHSCORE3_NAME.c_str());
	ini.SetLongValue("HIGHSCORE3", "SCORE", m_settings->HIGHSCORE3_SCORE);

	//Save the file
	if(ini.SaveFile("CONFIG.ini") < 0)
		{return false;}
	return true;
}
Пример #20
0
void MainClient::_loadObjectSprites(void)
{
	gs.MercTexture.resize(mercGFX::COUNT, 0);
    glGenTextures(mercGFX::COUNT, &gs.MercTexture[0]);

	CSimpleIniA texini;
	texini.LoadFile(info.texturefile.c_str());

	std::string texpath;

	//Manualy load merc sprites into one default mercGFX object
	LoadTex(gs.MercTexture[mercGFX::IDLE], texini.GetValue("Merc", "still"));
	LoadTex(gs.MercTexture[mercGFX::RUN], texini.GetValue("Merc", "run"));
	LoadTex(gs.MercTexture[mercGFX::JET], texini.GetValue("Merc", "jets"));
	LoadTex(gs.MercTexture[mercGFX::JETFLAME], texini.GetValue("Merc", "jetflame"));
	LoadTex(gs.MercTexture[mercGFX::SHOOT], texini.GetValue("Merc", "shoot"));

	gs.MercSprite.Idle = Sprite("assets/sprite/merc/still.sprh", gs.MercTexture[mercGFX::IDLE]);
	gs.MercSprite.Run = Sprite("assets/sprite/merc/run.sprh", gs.MercTexture[mercGFX::RUN]);
	gs.MercSprite.Jet = Sprite("assets/sprite/merc/jet.sprh", gs.MercTexture[mercGFX::JET]);
	gs.MercSprite.JetFlame = Sprite("assets/sprite/merc/jetflame.sprh", gs.MercTexture[mercGFX::JETFLAME]);
	gs.MercSprite.Shoot = Sprite("assets/sprite/merc/shoot.sprh", gs.MercTexture[mercGFX::SHOOT]);
}
Пример #21
0
int main (int argc, char **argv) 
{
	OTLog::vOutput(0, "\n\nWelcome to Open Transactions... Test Server -- version %s\n"
				   "(transport build: OTMessage -> TCP -> SSL)\n"
				   "IF YOU PREFER TO USE XmlRpc with HTTP, then rebuild from main folder like this:\n\n"
				   "cd ..; make clean; make rpc\n\n", 
				   OTLog::Version());
	
	// -----------------------------------------------------------------------
	
	// This object handles all the actual transaction notarization details.
	// (This file you are reading is a wrapper for OTServer, which adds the transport layer.)
	OTServer theServer;

	// -----------------------------------------------------------------------
	
#ifdef _WIN32
	WSADATA wsaData;
	WORD wVersionRequested = MAKEWORD( 2, 2 );
	int err = WSAStartup( wVersionRequested, &wsaData );

	/* Tell the user that we could not find a usable		*/
	/* Winsock DLL.											*/		

	OT_ASSERT_MSG((err == 0), "WSAStartup failed!\n");


	/*	Confirm that the WinSock DLL supports 2.2.			*/
	/*	Note that if the DLL supports versions greater		*/
	/*	than 2.2 in addition to 2.2, it will still return	*/
	/*	2.2 in wVersion since that is the version we		*/
	/*	requested.											*/

	bool bWinsock = (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2);

	/* Tell the user that we could not find a usable */
	/* WinSock DLL.                                  */

	if (!bWinsock) WSACleanup();  // do cleanup.
	OT_ASSERT_MSG((!bWinsock), "Could not find a usable version of Winsock.dll\n");

	/* The Winsock DLL is acceptable. Proceed to use it. */
	/* Add network programming using Winsock here */
	/* then call WSACleanup when done using the Winsock dll */
	OTLog::vOutput(0,"The Winsock 2.2 dll was found okay\n");
#endif

	OTLog::vOutput(0, "\n\nWelcome to Open Transactions, version %s.\n\n", OTLog::Version());
	
	// -----------------------------------------------------------------------
	// The beginnings of an INI file!!
	
#ifndef _WIN32 // if UNIX (NOT windows)
	wordexp_t exp_result;
	wordexp(OT_INI_FILE_DEFAULT, &exp_result, 0);
	
	const OTString strIniFileDefault(exp_result.we_wordv[0]);
	
	wordfree(&exp_result); 
#else
	const OTString strIniFileDefault(OT_INI_FILE_DEFAULT);
#endif
	
	OTString strPath(SERVER_PATH_DEFAULT);
	
	{
		CSimpleIniA ini;
		
		SI_Error rc = ini.LoadFile(strIniFileDefault.Get());
		
		if (rc >=0)
		{
			const char * pVal = ini.GetValue("paths", "server_path", SERVER_PATH_DEFAULT); // todo stop hardcoding.
			
			if (NULL != pVal)
			{
				strPath.Set(pVal);
				OTLog::vOutput(0, "Reading ini file (%s). \n Found Server data_folder path: %s \n", 
							   strIniFileDefault.Get(), strPath.Get());
			}
			else
			{
				strPath.Set(SERVER_PATH_DEFAULT);
				OTLog::vOutput(0, "Reading ini file (%s): \n Failed reading Server data_folder path. Using: %s \n", 
							   strIniFileDefault.Get(), strPath.Get());
			}
		}
		else 
		{
			strPath.Set(SERVER_PATH_DEFAULT);
			OTLog::vOutput(0, "Unable to load ini file (%s) to find data_folder path\n Will assume that server data_folder is at path: %s \n", 
						   strIniFileDefault.Get(), strPath.Get());
		}
	}
	// -----------------------------------------------------------------------
	
	OTString strCAFile, strDHFile, strKeyFile;
	//, strSSLPassword;
	
	if (argc < 1)
	{
		OTLog::vOutput(0, "\n==> USAGE:    %s  [absolute_path_to_data_folder]\n\n"
					   
//		OTLog::vOutput(0, "\n==> USAGE:    %s  <SSL-password>  [absolute_path_to_data_folder]\n\n"
#if defined (FELLOW_TRAVELER)					   
//					   "(Password defaults to '%s' if left blank.)\n"
					   "(Folder defaults to '%s' if left blank.)\n"
#else
					   "The test password is always 'test'.\n"
					   "OT will try to read the data_folder path from your ini file. If you prefer\n"
					   "to specify it at the command line, and you want to see the exact path, type:\n"
					   "     cd data_folder && pwd && cd ..\n"
#endif
					   "\n\n", argv[0]
#if defined (FELLOW_TRAVELER)					   
//					   , KEY_PASSWORD, 
					   , strPath.Get()
#endif					   
					   );
		
#if defined (FELLOW_TRAVELER)
//		strSSLPassword.Set(KEY_PASSWORD);
		OTLog::SetMainPath(strPath.Get());
#else
		exit(1);
#endif
	}
	else if (argc < 2)
	{		
//		strSSLPassword.Set(argv[1]);
		OTLog::SetMainPath(strPath.Get());
	}
	else 
	{
//		strSSLPassword.Set(argv[1]);
		OTLog::SetMainPath(argv[1]); // formerly [2]
	}
	
	OTLog::vOutput(0, "Using as path to data folder:  %s\n", OTLog::Path());

	strCAFile. Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), CA_FILE);
	strDHFile. Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), DH_FILE);
	strKeyFile.Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), KEY_FILE);
	
	
	// -----------------------------------------------------------------------

	// Init loads up server's nym so it can decrypt messages sent in envelopes.
	// It also does various other initialization work.
	//
	// (Envelopes prove that ONLY someone who actually had the server contract,
	// and had loaded it into his wallet, could ever connect to the server or 
	// communicate with it. And if that person is following the contract, there
	// is only one server he can connect to, and one key he can use to talk to it.)
	
	OTLog::Output(0, 
				  "\n\nNow loading the server nym, which will also ask you for a password, to unlock\n"
				  "its private key. (Default password is \"test\".)\n");

	// Initialize SSL -- This MUST occur before any Private Keys are loaded!
    SFSocketGlobalInit(); // Any app that uses OT has to initialize SSL first.

	theServer.Init(); // Keys, etc are loaded here.

	// -----------------------------------------------------------------------

	// We're going to listen on the same port that is listed in our server contract.
	//
	//
	OTString	strHostname;	// The hostname of this server, according to its own contract.
	int			nPort=0;		// The port of this server, according to its own contract.

	OT_ASSERT_MSG(theServer.GetConnectInfo(strHostname, nPort),
				  "Unable to find my own connect info (which is in my server contract BTW.)\n");
	
	const int	nServerPort = nPort;
	
	// -----------------------------------------------------------------------
	
	
	SFSocket *socket = NULL;
	listOfConnections theConnections;
	
    // Alloc Socket
	socket = SFSocketAlloc();
	OT_ASSERT_MSG(NULL != socket, "SFSocketAlloc Failed\n");
	
    // Initialize SSL Socket
	int nSFSocketInit = SFSocketInit(socket,
					 strCAFile.Get(), 
					 strDHFile.Get(), 
					 strKeyFile.Get(),
					 strSSLPassword.Get(), 
									 NULL);
	
	OT_ASSERT_MSG(nSFSocketInit >= 0, "SFSocketInit Context Failed\n");
	
    // Listen on Address/Port
	int nSFSocketListen = SFSocketListen(socket, INADDR_ANY, nServerPort);
	
	OT_ASSERT_MSG(nSFSocketListen >= 0, "nSFSocketListen Failed\n");
	
	
	theServer.ActivateCron();
	
    do 
	{
        SFSocket * clientSocket = NULL;

        // Accept Client Connection
        if (NULL != (clientSocket = SFSocketAccept(socket)))
		{
			OTClientConnection * pClient = new OTClientConnection(*clientSocket, theServer);
			theConnections.push_back(pClient);
			OTLog::Output(0, "Accepting new connection.\n");
		}
		
		// READ THROUGH ALL CLIENTS HERE, LOOP A LIST
		// AND process in-buffer onto our list of messages.
		
		OTClientConnection * pConnection = NULL;
		
		for (listOfConnections::iterator ii = theConnections.begin(); 
			 ii != theConnections.end(); ++ii)
		{
			if (pConnection = *ii)
			{
				// Here we read the bytes from the pipe into the client's buffer
				// As necessary this function also processes those bytes into OTMessages
				// and adds them to the Input List for that client.
				pConnection->ProcessBuffer();
			}
		}
		
		
		
		// Now loop through them all again, and process their messages onto the reply list.
		
		pConnection = NULL;
		
		for (listOfConnections::iterator ii = theConnections.begin(); 
			 ii != theConnections.end(); ++ii)
		{
			if (pConnection = *ii)
			{
				OTMessage * pMsg = NULL;
				
				while (pMsg = pConnection->GetNextInputMessage())
				{
					OTMessage * pReply = new OTMessage;
					
					OT_ASSERT(NULL != pReply);
					
					if (theServer.ProcessUserCommand(*pMsg, *pReply, pConnection))
					{
						OTLog::vOutput(0, "Successfully processed user command: %s.\n", 
								pMsg->m_strCommand.Get());
						
						pConnection->AddToOutputList(*pReply);
					}
					else
					{
						OTLog::Output(0, "Unable to process user command in XML, or missing payload, in main.\n");
						delete pReply;
						pReply = NULL;
					}
					
					// I am responsible to delete this here.
					delete pMsg;
					pMsg = NULL;
				}
			}
		}
		
		
		// Now loop through them all again, and process their replies down the pipe
		
		pConnection = NULL;
		
		for (listOfConnections::iterator ii = theConnections.begin(); 
			 ii != theConnections.end(); ++ii)
		{
			if (pConnection = *ii)
			{
				OTMessage * pMsg = NULL;
				
				while (pMsg = pConnection->GetNextOutputMessage())
				{
					pConnection->ProcessReply(*pMsg);
						
					// I am responsible to delete this here.
					delete pMsg;
					pMsg = NULL;
				}
			}
		}
		
		
		
		
		
		// The Server now processes certain things on a regular basis.
		// This method call is what gives it the opportunity to do that.
	
		theServer.ProcessCron();
		
		
		
		
		// Now go to sleep for a tenth of a second.
		// (Main loop processes ten times per second, currently.)
		
		OTLog::SleepMilliseconds(100); // 100 ms == (1 second / 10)
		
		
		
		
    } while (1);

    // Close and Release Socket Resources
    SFSocketRelease(socket);

#ifdef _WIN32
	WSACleanup();
#endif

    return(0);
}
Пример #22
0
int main( int argc, const char** argv )
{
  daemon_active = true;

  bool noDaemon = false;
  bool clockOn = false;
  std::string logFile;
  int topn;
  
  std::string configFile;
  std::string country;

  TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion());

  TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe).  Default=us",false, "us" ,"country_code");
  TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file.",false, "" ,"config_file");
  TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return.  Default=25",false, 25 ,"topN");
  TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to.  Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN");

  TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging.  Disables forking the process as a daemon and runs in the foreground.  Default=off", cmd, false);
  TCLAP::SwitchArg clockSwitch("","clock","Display timing information to log.  Default=off", cmd, false);

  try
  {
    
    cmd.add( countryCodeArg );
    cmd.add( topNArg );
    cmd.add( configFileArg );
    cmd.add( logFileArg );

    
    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    country = countryCodeArg.getValue();
    configFile = configFileArg.getValue();
    logFile = logFileArg.getValue();
    topn = topNArg.getValue();
    noDaemon = daemonOffSwitch.getValue();
    clockOn = clockSwitch.getValue();
  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }
  
  log4cplus::BasicConfigurator config;
  config.configure();
    
  if (noDaemon == false)
  {
    // Fork off into a separate daemon
    daemon(0, 0);
    
    
    log4cplus::SharedAppenderPtr myAppender(new log4cplus::RollingFileAppender(logFile));
    myAppender->setName("alprd_appender");
    // Redirect std out to log file
    logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd"));
    logger.addAppender(myAppender);
    
    
    LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in daemon mode.");
  }
  else
  {
    //log4cplus::SharedAppenderPtr myAppender(new log4cplus::ConsoleAppender());
    //myAppender->setName("alprd_appender");
    // Redirect std out to log file
    logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("alprd"));
    //logger.addAppender(myAppender);
    
    LOG4CPLUS_INFO(logger, "Running OpenALPR daemon in the foreground.");
  }
  
  CSimpleIniA ini;
  ini.SetMultiKey();
  
  ini.LoadFile(DAEMON_CONFIG_FILE_PATH.c_str());
  
  std::vector<std::string> stream_urls;
  
  
  CSimpleIniA::TNamesDepend values;
  ini.GetAllValues("daemon", "stream", values);

  // sort the values into the original load order
  values.sort(CSimpleIniA::Entry::LoadOrder());

  // output all of the items
  CSimpleIniA::TNamesDepend::const_iterator i;
  for (i = values.begin(); i != values.end(); ++i) { 
      stream_urls.push_back(i->pItem);
  }
  
  
  if (stream_urls.size() == 0)
  {
    LOG4CPLUS_FATAL(logger, "No video streams defined in the configuration.");
    return 1;
  }
  
  bool storePlates = ini.GetBoolValue("daemon", "store_plates", false);
  std::string imageFolder = ini.GetValue("daemon", "store_plates_location", "/tmp/");
  bool uploadData = ini.GetBoolValue("daemon", "upload_data", false);
  std::string upload_url = ini.GetValue("daemon", "upload_address", "");
  std::string site_id = ini.GetValue("daemon", "site_id", "");
  
  LOG4CPLUS_INFO(logger, "Using: " << imageFolder << " for storing valid plate images");
  
  pid_t pid;
  
  for (int i = 0; i < stream_urls.size(); i++)
  {
    pid = fork();
    if (pid == (pid_t) 0)
    {
      // This is the child process, kick off the capture data and upload threads
      CaptureThreadData* tdata = new CaptureThreadData();
      tdata->stream_url = stream_urls[i];
      tdata->camera_id = i + 1;
      tdata->config_file = configFile;
      tdata->output_images = storePlates;
      tdata->output_image_folder = imageFolder;
      tdata->country_code = country;
      tdata->site_id = site_id;
      tdata->top_n = topn;
      tdata->clock_on = clockOn;
      
      tthread::thread* thread_recognize = new tthread::thread(streamRecognitionThread, (void*) tdata);
      
      if (uploadData)
      {
	// Kick off the data upload thread
	UploadThreadData* udata = new UploadThreadData();
	udata->upload_url = upload_url;
	tthread::thread* thread_upload = new tthread::thread(dataUploadThread, (void*) udata );
      }
      
      break;
    }

    // Parent process will continue and spawn more children
  }



  while (daemon_active)
  {
    usleep(30000);
  }

}
Пример #23
0
bool SettingsManager::loadSettings()
{
	CSimpleIniA ini;
	ini.SetUnicode();
	ini.LoadFile("CONFIG.ini");

	if(ini.IsEmpty())
		{return false;}

	m_settings = new SettingsObject();

	m_settings->FRAME_TITLE = ini.GetValue("FRAME", "TITLE", "");
	m_settings->FRAME_FULLSCREEN = ini.GetBoolValue("FRAME", "FULLSCREEN", false);
	m_settings->FRAME_RESOLUTION_FULLSCREEN_X = ini.GetLongValue("FRAME", "RESOLUTION_FULLSCREEN_X", 0);
	m_settings->FRAME_RESOLUTION_FULLSCREEN_Y = ini.GetLongValue("FRAME", "RESOLUTION_FULLSCREEN_Y", 0);
	m_settings->FRAME_RESOLUTION_WINDOWED_X = ini.GetLongValue("FRAME", "RESOLUTION_WINDOWED_X", 0);
	m_settings->FRAME_RESOLUTION_WINDOWED_Y = ini.GetLongValue("FRAME", "RESOLUTION_WINDOWED_Y", 0);
	m_settings->FRAME_VIEW_X = ini.GetLongValue("FRAME", "VIEW_X", 0);
	m_settings->FRAME_VIEW_Y = ini.GetLongValue("FRAME", "VIEW_Y", 0);

	m_settings->WORLD_GRAVITY = (float)ini.GetDoubleValue("WORLD", "GRAVITY", 0);

	m_settings->PLAYER_SPEED_SIDE = (float)ini.GetDoubleValue("PLAYER", "SPEED_SIDE", 0);
	m_settings->PLAYER_SPEED_SIDE_HALTING = (float)ini.GetDoubleValue("PLAYER", "SPEED_SIDE_HALTING", 0);
	m_settings->PLAYER_SPEED_JUMP = (float)ini.GetDoubleValue("PLAYER", "SPEED_JUMP", 0);
	m_settings->PLAYER_SPEED_DOWN = (float)ini.GetDoubleValue("PLAYER", "SPEED_DOWN", 0);
	m_settings->PLAYER_HEALTH = (float)ini.GetDoubleValue("PLAYER", "HEALTH", 0);
	m_settings->PLAYER_SWORD_SWING_TIME = (float)ini.GetDoubleValue("PLAYER", "SWORD_SWING_TIME", 0);
	m_settings->PLAYER_HIT_TIME_LIMIT_MELEE = (float)ini.GetDoubleValue("PLAYER", "HIT_TIME_LIMIT_MELEE", 0);
	m_settings->PLAYER_KNOCKBACK_SPEED_X_INIT = (float)ini.GetDoubleValue("PLAYER", "KNOCKBACK_SPEED_X_INIT", 0);
	m_settings->PLAYER_KNOCKBACK_SPEED_X_DECREASE = (float)ini.GetDoubleValue("PLAYER", "KNOCKBACK_SPEED_X_DECREASE", 0);
	m_settings->PLAYER_KNOCKBACK_SPEED_Y = (float)ini.GetDoubleValue("PLAYER", "KNOCKBACK_SPEED_Y", 0);

	m_settings->DAMAGE_ENEMY_PLACEHOLDER_TO_PLAYER = (float)ini.GetDoubleValue("DAMAGE", "ENEMY_PLACEHOLDER_TO_PLAYER", 0);
	m_settings->DAMAGE_ENEMY_TROLL_TO_PLAYER = (float)ini.GetDoubleValue("DAMAGE", "ENEMY_TROLL_TO_PLAYER", 0);
	m_settings->DAMAGE_PLAYER_TO_ENEMY_PLACEHOLDER = (float)ini.GetDoubleValue("DAMAGE", "PLAYER_TO_ENEMY_PLACEHOLDER", 0);
	m_settings->DAMAGE_PLAYER_TO_ENEMY_TROLL = (float)ini.GetDoubleValue("DAMAGE", "PLAYER_TO_ENEMY_TROLL", 0);
	m_settings->DAMAGE_ENEMY_PROJECTILE_TO_PLAYER = (float)ini.GetDoubleValue("DAMAGE", "ENEMY_PROJECTILE_TO_PLAYER", 0);
	m_settings->DAMAGE_PLAYER_TO_ENEMY_SHOOTER = (float)ini.GetDoubleValue("DAMAGE", "PLAYER_TO_ENEMY_SHOOTER", 0);
	m_settings->DAMAGE_ENEMY_BASE_TO_PLAYER = (float)ini.GetDoubleValue("DAMAGE", "ENEMY_BASE_TO_PLAYER", 0);
	m_settings->DAMAGE_PLAYER_TO_ENEMY_GOBLIN = (float)ini.GetDoubleValue("DAMAGE", "PLAYER_TO_ENEMY_TROLL", 0);

	m_settings->ENEMY_TROLL_HEALTH = (float)ini.GetDoubleValue("ENEMY_TROLL", "HEALTH", 0);
	m_settings->ENEMY_TROLL_HIT_TIME_LIMIT_MELEE = (float)ini.GetDoubleValue("ENEMY_TROLL", "HIT_TIME_LIMIT_MELEE", 0);
	m_settings->ENEMY_TROLL_SPEED_SIDE = (float)ini.GetDoubleValue("ENEMY_TROLL", "SPEED_SIDE", 0);
	m_settings->ENEMY_TROLL_HITBOX_SIZE_X = (float)ini.GetDoubleValue("ENEMY_TROLL", "HITBOX_SIZE_X", 0);
	m_settings->ENEMY_TROLL_HITBOX_SIZE_Y = (float)ini.GetDoubleValue("ENEMY_TROLL", "HITBOX_SIZE_Y", 0);
	m_settings->ENEMY_TROLL_HITBOX_LOCAL_POSITION_X = (float)ini.GetDoubleValue("ENEMY_TROLL", "HITBOX_LOCAL_POSITION_X", 0);
	m_settings->ENEMY_TROLL_HITBOX_LOCAL_POSITION_Y = (float)ini.GetDoubleValue("ENEMY_TROLL", "HITBOX_LOCAL_POSITION_Y", 0);
	m_settings->ENEMY_TROLL_AI_CHANGE_LIMIT_TIME = (float)ini.GetDoubleValue("ENEMY_TROLL", "AI_CHANGE_LIMIT_TIME", 0);
	m_settings->ENEMY_TROLL_AI_WALKING_BACKWARDS_DISTANCE_LIMIT = (float)ini.GetDoubleValue("ENEMY_TROLL", "AI_WALKING_BACKWARDS_DISTANCE_LIMIT", 0);
	m_settings->ENEMY_TROLL_ATTACK_STAGE_1_TIME = (float)ini.GetDoubleValue("ENEMY_TROLL", "ATTACK_STAGE_1_TIME", 0);
	m_settings->ENEMY_TROLL_ATTACK_STAGE_2_TIME = (float)ini.GetDoubleValue("ENEMY_TROLL", "ATTACK_STAGE_2_TIME", 0);

	m_settings->ENEMY_GOBLIN_HEALTH = (float)ini.GetDoubleValue("ENEMY_GOBLIN", "HEALTH", 0);
	m_settings->ENEMY_GOBLIN_SPEED_SIDE = (float)ini.GetDoubleValue("ENEMY_GOBLIN", "SPEED_SIDE", 0);
	m_settings->ENEMY_GOBLIN_BOMB_SPAWN_TIME = (float)ini.GetDoubleValue("ENEMY_GOBLIN", "BOMB_SPAWN_TIME", 0);
	m_settings->ENEMY_GOBLIN_BOMB_AOE_DURATION = (float)ini.GetDoubleValue("ENEMY_GOBLIN", "BOMB_AOE_DURATION", 0);
	m_settings->ENEMY_GOBLIN_BOMB_BLAST_AREA_SIZE = (float)ini.GetDoubleValue ("ENEMY_GOBLIN", "BOMB_BLAST_AREA_SIZE", 0);

	m_settings->ENEMY_SHOOTER_SHOOT_TIME = (float)ini.GetDoubleValue("ENEMY_SHOOTER", "SHOOT_TIME", 0);
	m_settings->ENEMY_SHOOTER_PROJECTILE_PARTICLE_SPAWN_TIME = (float)ini.GetDoubleValue("ENEMY_SHOOTER", "PROJECTILE_PARTICLE_SPAWN_TIME", 0);
	m_settings->ENEMY_SHOOTER_PROJETILE_SPEED = (float)ini.GetDoubleValue("ENEMY_SHOOTER", "PROJETILE_SPEED", 0);
	m_settings->ENEMY_SHOOTER_PROJECTILE_LIFE_TIME = (float)ini.GetDoubleValue("ENEMY_SHOOTER", "PROJECTILE_LIFE_TIME", 0);

	m_settings->ENEMY_BASE_HEALTH = (float)ini.GetDoubleValue("ENEMY_BASE", "HEALTH", 0);
	m_settings->ENEMY_BASE_SPEED_BASE = (float)ini.GetDoubleValue("ENEMY_BASE", "SPEED_BASE", 0);
	m_settings->ENEMY_BASE_SPEED_MIN_MULTIPLIER = (float)ini.GetDoubleValue("ENEMY_BASE", "SPEED_MIN_MULTIPLIER", 0);
	m_settings->ENEMY_BASE_SPEED_MAX_MULTIPLIER = (float)ini.GetDoubleValue("ENEMY_BASE", "SPEED_MAX_MULTIPLIER", 0);

	m_settings->PARTICLES_MAX_INIT_SPEED = (float)ini.GetDoubleValue("PARTICLES", "MAX_INIT_SPEED", 0);

	m_settings->SCORE_KILL_TROLL = ini.GetLongValue("SCORE", "KILL_TROLL", 0);
	m_settings->SCORE_KILL_GOBLIN = ini.GetLongValue("SCORE", "KILL_GOBLIN", 0);
	m_settings->SCORE_KILL_SHOOTER = ini.GetLongValue("SCORE", "KILL_SHOOTER", 0);
	m_settings->SCORE_KILL_BASE = ini.GetLongValue("SCORE", "KILL_BASE", 0);
	m_settings->SCORE_TIME_LIMIT = (float)ini.GetDoubleValue("SCORE", "TIME_LIMIT", 0);

	m_settings->HIGHSCORE_NAME = ini.GetValue("HIGHSCORE", "NAME", "");
	m_settings->HIGHSCORE2_NAME = ini.GetValue("HIGHSCORE2", "NAME", "");
	m_settings->HIGHSCORE3_NAME = ini.GetValue("HIGHSCORE3", "NAME", "");
	m_settings->HIGHSCORE_SCORE = ini.GetLongValue("HIGHSCORE", "SCORE", 0);
	m_settings->HIGHSCORE2_SCORE = ini.GetLongValue("HIGHSCORE2", "SCORE", 0);
	m_settings->HIGHSCORE3_SCORE = ini.GetLongValue("HIGHSCORE3", "SCORE", 0);

	return true;
}
Пример #24
0
void Config::loadCountryValues(string configFile, string country)
{
    CSimpleIniA iniObj;
    iniObj.SetMultiKey(true);
    iniObj.LoadFile(configFile.c_str());
    CSimpleIniA* ini = &iniObj;

    minPlateSizeWidthPx = getInt(ini, "", "min_plate_size_width_px", 100);
    minPlateSizeHeightPx = getInt(ini, "", "min_plate_size_height_px", 100);

    multiline = 	getBoolean(ini, "", "multiline",		false);

    string invert_val = getString(ini, "", "invert", "auto");

    if (invert_val == "always")
    {
        auto_invert = false;
        always_invert = true;
    }
    else if (invert_val == "never")
    {
        auto_invert = false;
        always_invert = false;
    }
    else
    {
        auto_invert = true;
        always_invert = false;
    }

    plateWidthMM = getFloat(ini, "", "plate_width_mm", 100);
    plateHeightMM = getFloat(ini, "", "plate_height_mm", 100);

    charHeightMM = getAllFloats(ini, "", "char_height_mm");
    charWidthMM = getAllFloats(ini, "", "char_width_mm");

    // Compute the average char height/widths
    avgCharHeightMM = 0;
    avgCharWidthMM = 0;
    for (unsigned int i = 0; i < charHeightMM.size(); i++)
    {
        avgCharHeightMM += charHeightMM[i];
        avgCharWidthMM += charWidthMM[i];
    }
    avgCharHeightMM /= charHeightMM.size();
    avgCharWidthMM /= charHeightMM.size();

    charWhitespaceTopMM = getFloat(ini, "", "char_whitespace_top_mm", 100);
    charWhitespaceBotMM = getFloat(ini, "", "char_whitespace_bot_mm", 100);
    charWhitespaceBetweenLinesMM = getFloat(ini, "", "char_whitespace_between_lines_mm", 5);

    templateWidthPx = getInt(ini, "", "template_max_width_px", 100);
    templateHeightPx = getInt(ini, "", "template_max_height_px", 100);

    charAnalysisMinPercent = getFloat(ini, "", "char_analysis_min_pct", 0);
    charAnalysisHeightRange = getFloat(ini, "", "char_analysis_height_range", 0);
    charAnalysisHeightStepSize = getFloat(ini, "", "char_analysis_height_step_size", 0);
    charAnalysisNumSteps = getInt(ini, "", "char_analysis_height_num_steps", 0);

    segmentationMinSpeckleHeightPercent = getFloat(ini, "", "segmentation_min_speckle_height_percent", 0);
    segmentationMinBoxWidthPx = getInt(ini, "", "segmentation_min_box_width_px", 0);
    segmentationMinCharHeightPercent = getFloat(ini, "", "segmentation_min_charheight_percent", 0);
    segmentationMaxCharWidthvsAverage = getFloat(ini, "", "segmentation_max_segment_width_percent_vs_average", 0);

    plateLinesSensitivityVertical = getFloat(ini, "", "plateline_sensitivity_vertical", 0);
    plateLinesSensitivityHorizontal = getFloat(ini, "", "plateline_sensitivity_horizontal", 0);

    ocrLanguage = getString(ini, "", "ocr_language", "none");

    postProcessRegexLetters = getString(ini, "", "postprocess_regex_letters", "\\pL");
    postProcessRegexNumbers = getString(ini, "", "postprocess_regex_numbers", "\\pN");

    ocrImageWidthPx = round(((float) templateWidthPx) * ocrImagePercent);
    ocrImageHeightPx = round(((float)templateHeightPx) * ocrImagePercent);
    stateIdImageWidthPx = round(((float)templateWidthPx) * stateIdImagePercent);
    stateIdimageHeightPx = round(((float)templateHeightPx) * stateIdImagePercent);

    postProcessMinCharacters = getInt(ini, "", "postprocess_min_characters", 4);
    postProcessMaxCharacters = getInt(ini, "", "postprocess_max_characters", 8);
}
Пример #25
0
int main(int argc, const char * argv[]) {
	CSimpleIniA ini;
	
	ini.SetUnicode();
	if (ini.LoadFile("config.ini") == SI_FILE) {
		std::cout<< KWARN "Warning:" <<KREST << " Cannot load config.ini. Default setting is used.\n\n";
	}

	bool gui = true;
	
	uint16_t port = atoi(ini.GetValue("server", "port", stringize(SERVER_DEFAULT_PORT)));
	uint32_t numThreads = atoi(ini.GetValue("server", "threads", stringize(SERVER_DEFAULT_NUM_THREADS)));
	
	int width = atoi(ini.GetValue("camera", "width", stringize(CAM_DEFAULT_WIDTH)));
	int height = atoi(ini.GetValue("camera", "height", stringize(CAM_DEFAULT_HEIGHT)));
	uint32_t wait = atoi(ini.GetValue("camera", "wait", stringize(CAM_WAIT)));
	int dev = atoi(ini.GetValue("camera", "device", stringize(CAM_DEV)));
	
	const char* unlockPin = ini.GetValue("gpio", "unlock", GPIO_DEFAULT_UNLOCK);
	const char* errorPin = ini.GetValue("gpio", "error", GPIO_DEFAULT_ERROR);
	
	const char* rsapath = ini.GetValue("safety", "pem", SAFETY_DEFAULT_RSA_FILE);
	const char* passwd = ini.GetValue("safety", "password", SAFETY_DEFAULT_PASSWD);
	
	uint32_t qrexp = atoi(ini.GetValue("misc", "qrexpire", stringize(MISC_DEFAULT_QR_EXP)));
	
	for (int i = 1; i < argc; i++) {
		const char* arg = argv[i];
		
		if (strcmp(arg, "--help") == 0) {
			printf("%s", HELP_STRING);
			exit(0);
		} else if (strcmp(arg, "--nogui") == 0) {
			gui = false;
		} else {
			std::cerr<<KERR <<"Error:" << KREST << "unknown argument \""<<arg<<'"'<<std::endl;
			exit(2);
		}
	}
	
	ServerThreads::qrexp = qrexp;
	ServerThreads::port = port;
	ServerThreads::numThreads = numThreads;
	ServerThreads::gpioUnlock = unlockPin;
	ServerThreads::gpioError = errorPin;
	ServerThreads::rsaFile = rsapath;

	if (signal(SIGINT, sigHandler) == SIG_ERR)
		std::cerr<<"Can't catch SIGINT\n";
	
	pthread_t serverThreadId;
	pthread_create(&serverThreadId, nullptr, ServerThreads::startServer, nullptr);
	
	const char* apnRsaFile = ini.GetValue("apn", "pem", APN_DEFAULT_RSA_FILE);
	
	APNClient::DefaultClient.host = ini.GetValue("apn", "host", APN_DEFAULT_HOST);
	APNClient::DefaultClient.port = atoi(ini.GetValue("apn", "port", stringize(APN_DEFAULT_PORT)));
	APNClient::DefaultClient.rsa = rsaFromFile(apnRsaFile, true);
	
	REPL::cleanupFn = cleanup;
	REPL::password = passwd;
	pthread_t replThreadId;
	pthread_create(&replThreadId, nullptr, REPL::startLoop, nullptr);
    
    pthread_t btThreadId;
    pthread_create(&btThreadId, nullptr, BluetoothThread::startLoop, nullptr);
	
	CameraLoop::loop(dev, width, height, gui, wait);
	
    return 1;
}
Пример #26
0
int main(int ArgumentCount, char* Arguments[])
{
	M2Lib::CM2 M2;

	char iniFileName[1024];
	strcpy(iniFileName, Arguments[0]);
	char* lastSlash = strrchr(iniFileName, '\\');
	if (NULL == lastSlash)
	{
		lastSlash = strrchr(iniFileName, '/');
	}
	if (NULL != lastSlash)
	{
		lastSlash[1] = 0;
	}
	strcat(iniFileName, "M2Mod.ini");

	const char* szInputM2 = 0;
	const char* szOutputM2I = 0;
	const char* szInputM2I = 0;
	const char* szOutputM2 = 0;
	const char* szSubmeshPositionalTolerance = 0;
	const char* szSubmeshAngularTolerance = 0;
	const char* szBodyPositionalTolerance = 0;
	const char* szBodyAngularTolerance = 0;
	const char* szClothingPositionalTolerance = 0;
	const char* szClothingAngularTolerance = 0;
	const char* szIgnoreMaterials = 0;
	const char* szIgnoreBones = 0;
	const char* szIgnoreAttachments = 0;
	const char* szIgnoreCameras = 0;
	const char* szMirrorCamera = 0;
	const char* szScale = 0;
	const char* szShowVersion = 0;
	g_Verbose = 0;
	Float32 SubmeshPositionalTolerance = 0.0005f;
	Float32 SubmeshAngularTolerance = 60.0f;
	Float32 BodyPositionalTolerance = 0.0005f;
	Float32 BodyAngularTolerance = 90.0f;
	Float32 ClothingPositionalTolerance = 0.0005f;
	Float32 ClothingAngularTolerance = 45.0f;
	bool IgnoreMaterials = false;
	bool IgnoreBones = false;
	bool IgnoreAttachments = false;
	bool IgnoreCameras = false;
	bool MirrorCamera = false;
	Float32 Scale = 1.0f;
	bool ShowVersion = false;

	CSimpleIniA Ini;
	bool Pause = true;
	if ( ArgumentCount <= 1 )
	{
		// take inputs from INI
		//std::cout << "loading INI" << std::endl;
		if ( Ini.LoadFile( iniFileName ) != SI_OK )
		{
			std::cout << "Error: Could not load M2Mod.ini. Make sure M2Mod.ini is in same directory as M2Mod.exe." << std::endl;
			system("pause");
			return 0;
		}
		szInputM2 = Ini.GetValue( "input", "InputM2" );
		szOutputM2I = Ini.GetValue( "input", "OutputM2I" );
		szInputM2I = Ini.GetValue( "input", "InputM2I" );
		szOutputM2 = Ini.GetValue( "input", "OutputM2" );
		szSubmeshPositionalTolerance = Ini.GetValue( "options", "SubmeshPositionalTolerance" );
		szSubmeshAngularTolerance = Ini.GetValue( "options", "SubmeshAngularTolerance" );
		szBodyPositionalTolerance = Ini.GetValue( "options", "BodyPositionalTolerance" );
		szBodyAngularTolerance = Ini.GetValue( "options", "BodyAngularTolerance" );
		szClothingPositionalTolerance = Ini.GetValue( "options", "ClothingPositionalTolerance" );
		szClothingAngularTolerance = Ini.GetValue( "options", "ClothingAngularTolerance" );
		szIgnoreMaterials = Ini.GetValue( "options", "IgnoreMaterials" );
		szIgnoreBones = Ini.GetValue( "options", "IgnoreBones" );
		szIgnoreAttachments = Ini.GetValue( "options", "IgnoreAttachments" );
		szMirrorCamera = Ini.GetValue( "options", "MirrorCamera" );
		szScale = Ini.GetValue( "options", "Scale" );
		szShowVersion = Ini.GetValue( "debug", "ShowVersion" );
		g_Verbose = Ini.GetLongValue( "debug", "Verbose" );
	}
	else
	{
		// take inputs from command line
		//std::cout << "loading CMD" << std::endl;
		Pause = false;
		for ( SInt32 i = 1; i < ArgumentCount; i++ )
		{
			if ( strcmp( Arguments[i], "/InputM2" ) == 0 )
			{
				i++;
				szInputM2 = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/OutputM2I" ) == 0 )
			{
				i++;
				szOutputM2I = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/InputM2I" ) == 0 )
			{
				i++;
				szInputM2I = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/OutputM2" ) == 0 )
			{
				i++;
				szOutputM2 = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/SubmeshPositionalTolerance" ) == 0 )
			{
				i++;
				szSubmeshPositionalTolerance = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/SubmeshAngularTolerance" ) == 0 )
			{
				i++;
				szSubmeshAngularTolerance = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/BodyPositionalTolerance" ) == 0 )
			{
				i++;
				szBodyPositionalTolerance = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/BodyAngularTolerance" ) == 0 )
			{
				i++;
				szBodyAngularTolerance = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/ClothingPositionalTolerance" ) == 0 )
			{
				i++;
				szClothingPositionalTolerance = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/ClothingAngularTolerance" ) == 0 )
			{
				i++;
				szClothingAngularTolerance = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/IgnoreMaterials" ) == 0 )
			{
				szIgnoreMaterials = "1";
			}
			else if ( strcmp( Arguments[i], "/IgnoreBones" ) == 0 )
			{
				szIgnoreBones = "1";
			}
			else if ( strcmp( Arguments[i], "/IgnoreAttachments" ) == 0 )
			{
				szIgnoreBones = "1";
			}
			else if ( strcmp( Arguments[i], "/IgnoreCameras" ) == 0 )
			{
				szIgnoreBones = "1";
			}
			else if ( strcmp( Arguments[i], "/MirrorCamera" ) == 0 )
			{
				szMirrorCamera = "1";
			}
			else if ( strcmp( Arguments[i], "/Scale" ) == 0 )
			{
				i++;
				szScale = Arguments[i];
			}
			else if ( strcmp( Arguments[i], "/ShowVersion" ) == 0 )
			{
				szShowVersion = "1";
			}
			else if ( strcmp( Arguments[i], "/Verbose" ) == 0 )
			{
				i++;
				g_Verbose = atoi( Arguments[i] );
			}
		}
	}

	if ( szShowVersion )
	{
		if ( szShowVersion[0] == '0' )
		{
			ShowVersion = false;
		}
		else
		{
			ShowVersion = true;
		}
	}
	if ( ShowVersion )
	{
		std::cout << "M2Mod version: " << M2MOD_VERSION << std::endl;
	}

	if ( szIgnoreMaterials )
	{
		if ( szIgnoreMaterials[0] == '0' )
		{
			IgnoreMaterials = false;
		}
		else
		{
			IgnoreMaterials = true;
		}
	}

	if ( szIgnoreBones )
	{
		if ( szIgnoreBones[0] == '0' )
		{
			IgnoreBones = false;
		}
		else
		{
			IgnoreBones = true;
		}
	}

	if ( szIgnoreAttachments )
	{
		if ( szIgnoreAttachments[0] == '0' )
		{
			IgnoreAttachments = false;
		}
		else
		{
			IgnoreAttachments = true;
		}
	}

	if ( szIgnoreCameras )
	{
		if ( szIgnoreCameras[0] == '0' )
		{
			IgnoreCameras = false;
		}
		else
		{
			IgnoreCameras = true;
		}
	}

	if ( szMirrorCamera )
	{
		if ( szMirrorCamera[0] == '0' )
		{
			MirrorCamera = false;
		}
		else
		{
			MirrorCamera = true;
		}
	}

	if ( szSubmeshPositionalTolerance )
	{
		SubmeshPositionalTolerance = (Float32)atof( szSubmeshPositionalTolerance );
	}
	if ( szSubmeshAngularTolerance )
	{
		SubmeshAngularTolerance = (Float32)atof( szSubmeshAngularTolerance );
	}
	if ( szBodyPositionalTolerance )
	{
		BodyPositionalTolerance = (Float32)atof( szBodyPositionalTolerance );
	}
	if ( szBodyAngularTolerance )
	{
		BodyAngularTolerance = (Float32)atof( szBodyAngularTolerance );
	}
	if ( szClothingPositionalTolerance )
	{
		ClothingPositionalTolerance = (Float32)atof( szClothingPositionalTolerance );
	}
	if ( szClothingAngularTolerance )
	{
		ClothingAngularTolerance = (Float32)atof( szClothingAngularTolerance );
	}

	if ( SubmeshPositionalTolerance < 0.0f )
	{
		SubmeshPositionalTolerance = 0.0f;
	}
	else if ( SubmeshPositionalTolerance > MaxPositionalTolerance )
	{
		SubmeshPositionalTolerance = MaxPositionalTolerance;
	}

	if ( SubmeshAngularTolerance < 0.0f )
	{
		SubmeshAngularTolerance = 0.0f;
	}
	else if ( SubmeshAngularTolerance > MaxAngularTolerance )
	{
		SubmeshAngularTolerance = MaxAngularTolerance;
	}

	if ( BodyPositionalTolerance < 0.0f )
	{
		BodyPositionalTolerance = 0.0f;
	}
	else if ( BodyPositionalTolerance > MaxPositionalTolerance )
	{
		BodyPositionalTolerance = MaxPositionalTolerance;
	}

	if ( BodyAngularTolerance < 0.0f )
	{
		BodyAngularTolerance = 0.0f;
	}
	else if ( BodyAngularTolerance > MaxAngularTolerance )
	{
		BodyAngularTolerance = MaxAngularTolerance;
	}

	if ( ClothingPositionalTolerance < 0.0f )
	{
		ClothingPositionalTolerance = 0.0f;
	}
	else if ( ClothingPositionalTolerance > MaxPositionalTolerance )
	{
		ClothingPositionalTolerance = MaxPositionalTolerance;
	}

	if ( ClothingAngularTolerance < 0.0f )
	{
		ClothingAngularTolerance = 0.0f;
	}
	else if ( ClothingAngularTolerance > MaxAngularTolerance )
	{
		ClothingAngularTolerance = MaxAngularTolerance;
	}

	SubmeshAngularTolerance *= DegreesToRadians;
	BodyAngularTolerance *= DegreesToRadians;
	ClothingAngularTolerance *= DegreesToRadians;

	if ( szInputM2 )
	{
		std::cout << "Loading M2:    " << szInputM2 << std::endl;
		if ( M2Lib::EError Error = M2.Load( const_cast<Char8*>(szInputM2) ) )
		{
			std::cout << M2Lib::GetErrorText( Error ) << std::endl;
			system("pause");
			return -1;
		}
	}
	else
	{
		std::cout << "Error: No input M2 specified" << std::endl;
		system("pause");
		return -1;
	}

	if ( szOutputM2I )
	{
		std::cout << "Exporting M2I: " << szOutputM2I << std::endl;
		if ( M2Lib::EError Error = M2.ExportM2Intermediate( const_cast<Char8*>(szOutputM2I) ) )
		{
			std::cout << M2Lib::GetErrorText( Error ) << std::endl;
			system("pause");
			return -1;
		}
	}

	if ( szInputM2I )
	{
		std::cout << "Importing M2I: " << szInputM2I << std::endl;
		if ( M2Lib::EError Error = M2.ImportM2Intermediate( const_cast<Char8*>(szInputM2I), IgnoreMaterials, IgnoreBones, IgnoreAttachments, IgnoreCameras, SubmeshPositionalTolerance, SubmeshAngularTolerance, BodyPositionalTolerance, BodyAngularTolerance, ClothingPositionalTolerance, ClothingAngularTolerance ) )
		{
			std::cout << M2Lib::GetErrorText( Error ) << std::endl;
			system("pause");
			return -1;
		}
	}

	if ( szMirrorCamera )
	{
		M2.MirrorCamera();
	}

	if ( szScale )
	{
		Float32 Scale = (Float32)atof( szScale );
		if ( Scale != 1.0f )
		{
			if ( Scale < 0.8f )
			{
				Scale = 0.8f;
			}
			else if ( Scale > 1.2f )
			{
				Scale = 1.2f;
			}
			M2.Scale( Scale );
		}
	}

	if ( szOutputM2 )
	{
		std::cout << "Saving M2:     " << szOutputM2 << std::endl;
		if ( M2Lib::EError Error = M2.Save( const_cast<Char8*>(szOutputM2) ) )
		{
			std::cout << M2Lib::GetErrorText( Error ) << std::endl;
			system("pause");
			return -1;
		}
	}

	std::cout << "Operations Complete" << std::endl;

	if ( Pause )
	{
		system("pause");
	}

	return 0;
}
Пример #27
0
// The MAIN function for the server software, which starts up the XmlRpc (http server), 
// as well as Open Transactions.
//
int main(int argc, char* argv[])
{
	OTLog::vOutput(0, "\n\nWelcome to Open Transactions... Test Server -- version %s\n"
				   "(transport build: OTMessage -> OTEnvelope -> ZMQ )\n\n", OTLog::Version());
	// -----------------------------------------------------------------------

#ifdef _WIN32
	WSADATA wsaData;
	WORD wVersionRequested = MAKEWORD( 2, 2 );
	int nWSA = WSAStartup( wVersionRequested, &wsaData );
	OT_ASSERT_MSG(0 != nWSA, "Error calling WSAStartup.\n");	
#endif
	
	// -----------------------------------------------------------------------
	// I instantiate this here (instead of globally) so that I am assured all the globals
	// are ready to go before the server is created.  I still have it as a global pointer, though,
	// so I can get to it wherever I need to.
	g_pServer = new OTServer;
	// (This file you are reading is a wrapper for OTServer, which adds the transport layer.)

	OT_ASSERT_MSG(NULL != g_pServer, "Unable to instantiate OT server...\n");
	
	// -----------------------------------------------------------------------
	// The beginnings of an INI file!!
	
    OTString strIniFileDefault;
    OTLog::TransformFilePath(OT_INI_FILE_DEFAULT, strIniFileDefault);
	
	OTString strPath, strRawPath(SERVER_PATH_DEFAULT);
	
	{
		CSimpleIniA ini;
		
		SI_Error rc = ini.LoadFile(strIniFileDefault.Get());
		
		if (rc >=0)
		{
            {
                const char * pVal = ini.GetValue("paths", "server_path", SERVER_PATH_DEFAULT); // todo stop hardcoding.
                
                if (NULL != pVal)
                {
                    strRawPath.Set(pVal);
                    OTLog::vOutput(0, "Reading ini file (%s). \n Found Server data_folder path: %s \n", 
                                   strIniFileDefault.Get(), strRawPath.Get());
                }
                else
                {
                    strRawPath.Set(SERVER_PATH_DEFAULT);
                    OTLog::vOutput(0, "Reading ini file (%s): \n Failed reading Server data_folder path. Using: %s \n", 
                                   strIniFileDefault.Get(), strRawPath.Get());
                }
            }            
		}
		else 
		{
			strRawPath.Set(SERVER_PATH_DEFAULT);
			OTLog::vOutput(0, "Unable to load ini file (%s) to find data_folder path\n Will assume that server data_folder is at path: %s \n", 
						   strIniFileDefault.Get(), strRawPath.Get());
		}
	}
        
	// -----------------------------------------------------------------------

	OTString strCAFile, strDHFile, strKeyFile;  //, strSSLPassword;
	
    OTLog::TransformFilePath(strRawPath.Get(), strPath);
    
    OTLog::SetMainPath(strPath.Get());
    	
	OTLog::vOutput(0, "Using data_folder path:  %s\n", OTLog::Path());
	
	strCAFile. Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), CA_FILE);
	strDHFile. Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), DH_FILE);
	strKeyFile.Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), KEY_FILE);
	
	
	
	// -----------------------------------------------------------------------
	
	// Initialize SSL -- This MUST occur before any Private Keys are loaded!
	SSL_library_init();
	SSL_load_error_strings();
	
	// Init loads up server's nym so it can decrypt messages sent in envelopes.
	// It also does various other initialization work.
	//
	// (Envelopes prove that ONLY someone who actually had the server contract,
	// and had loaded it into his wallet, could ever connect to the server or 
	// communicate with it. And if that person is following the contract, there
	// is only one server he can connect to, and one key he can use to talk to it.)
	
	OTLog::vOutput(0, 
				   "\nNow loading the server nym, which will also ask you for a password, to unlock\n"
				   "its private key. (Default password is \"%s\".)\n", KEY_PASSWORD);
	
	g_pServer->Init(); // Keys, etc are loaded here.
	
	// -----------------------------------------------------------------------

	// We're going to listen on the same port that is listed in our server contract.
	//
	//
	OTString	strHostname;	// The hostname of this server, according to its own contract.
	int			nPort=0;		// The port of this server, according to its own contract.
	
	OT_ASSERT_MSG(g_pServer->GetConnectInfo(strHostname, nPort),
				  "Unable to find my own connect info (which is in my server contract BTW.)\n");
	
	const int	nServerPort = nPort;
	
	//	int nSFSocketInit = SFSocketInit(socket,
	//									 strCAFile.Get(), 
	//									 strDHFile.Get(), 
	//									 strKeyFile.Get(),
	//									 strSSLPassword.Get(), 
	//									 NULL);
	
	// -----------------------------------------------------------------------
	
	// For re-occuring actions (like markets and payment plans.)
	//
	g_pServer->ActivateCron();

	// -----------------------------------
	
	//  Prepare our context and socket
	zmq::context_t context(1);
	zmq::socket_t socket(context, ZMQ_REP);

	OTString strBindPath; strBindPath.Format("%s%d", "tcp://*:", nServerPort);

	socket.bind(strBindPath.Get());

	// -----------------------------------------------------------------------
	// Let's get the HTTP server up and running...
	// Switching out XmlRpc for 0MQ (ZeroMQ)
	//
//	XmlRpc::setVerbosity(1);
//
//	// Create the server socket on the specified port
//	theXmlRpcServer.bindAndListen(nServerPort);
//
//	// Enable introspection, so clients can see what services this server supports. (Open Transactions...)
//	theXmlRpcServer.enableIntrospection(true);

	// -----------------------------------------------------------------------

	//  Initialize poll set
	zmq::pollitem_t items [] =
	{
		{ socket, 0, ZMQ_POLLIN, 0 },
	};

	// ----------------------------------------------------------
	
	do  // THE HEARTBEAT LOOP FOR THE OPEN-TRANSACTIONS SERVER!
	{
		// The Server now processes certain things on a regular basis.
		// ProcessCron is what gives it the opportunity to do that.
		// All of the Cron Items (including market trades, and payment plans...) have their hooks here...
		//
		g_pServer->ProcessCron();
		
		// -----------------------------------------------------------------------
		
		// Wait for client http requests (and process replies out to them.)
		//
//		theXmlRpcServer.work(10.0); // supposedly milliseconds -- but it's actually seconds.

		// Loop: process up to 10 client requests, then sleep for 1/10th second.
		// 
		// Then: check for shutdown.
		//
		// Then: go back to the top and repeat.... process cron, loop 10 client requests, sleep, check for shutdown, etc.
		//
		//
        
        
		for (int i = 0; i < /*10*/OTServer::GetHeartbeatNoRequests(); i++) 
		{
			// Switching to ZeroMQ library.
			zmq::message_t message;

			zmq::poll(&items[0], 1, 0);  // non-blocking
//			zmq::poll(&items[0], 1, -1);

			if ((items[0].revents & ZMQ_POLLIN) && socket.recv(&message, ZMQ_NOBLOCK))
			{
//				socket.recv(&message);

				// Convert the ZMQ message to a std::string
				std::string str_Message;
				str_Message.reserve(message.size());
				str_Message.append(static_cast<const char *>(message.data()), message.size());

				//  Process task
				std::string str_Reply; // Output.
				ProcessMessage_ZMQ(str_Message, str_Reply);

				// -----------------------------------------------
				
				// Convert the std::string (reply) into a ZMQ message
				zmq::message_t reply (str_Reply.length());

				if (str_Reply.length() > 0)
					memcpy((void *) reply.data(), str_Reply.c_str(), str_Reply.length());

				// --------------------------------
				//  Send reply back to client

				int		nSendTries = 0;
				bool	bSuccessSending = false;
				
				// HALF-SECOND DELAY IF FAILURE SENDING REPLY...
				// (While it tries to re-send 5 times.)
				//
				while ((nSendTries++ < OTLog::GetLatencySendNoTries()/*5*/) && (false == (bSuccessSending = socket.send(reply, ZMQ_NOBLOCK))))
					OTLog::SleepMilliseconds(/*100*/OTLog::GetLatencySendMs());
				
				if (false == bSuccessSending)
					OTLog::vError("Socket error: failed while trying to send reply back to client! \n\n MESSAGE:\n%s\n\nREPLY:\n%s\n\n", 
								  str_Message.c_str(), str_Reply.c_str());
			}
		} //  for		
		// -----------------------------------------------------------------------
		
		// Now go to sleep for a tenth of a second.
		// (The main loop processes ten times per second, currently.)
		
		OTLog::SleepMilliseconds(/*100*/OTServer::GetHeartbeatMsBetweenBeats()); // 100 ms == (1 second / 10)
		
		// -----------------------------------------------------------------------
		// ARTIFICIAL LIMIT:
		// 10 requests per heartbeat, 10 rounds per second == 100 requests per second.
		//
		// *** ONE HUNDRED CLIENT MESSAGES PER SECOND is the same as:
		// 
		//     6000 PER MINUTE == 360,000 PER HOUR == 8,640,000 PER DAY***
		//
		// Speeding it up is just a matter of adjusting the above numbers, and TESTING to see if OT can handle it.
		// (Not counting optimization of course.)
		//
		// -----------------------------------------------------------------------

		if (g_pServer->IsFlaggedForShutdown())
		{
			OTLog::Output(0, "Server is shutting down gracefully....\n");
			break;
		}
    } while (1);
	
	
	// TODO: cleanup OpenSSL here.
	
#ifdef _WIN32
	WSACleanup();
#endif
	
	return 0;
}
Пример #28
0
int main (int argc, char **argv) 
{
	OTLog::vOutput(0, "\n\nWelcome to Open Transactions... Test Client -- version %s\n"
				   "(transport build: OTMessage -> TCP -> SSL)\n"
				   "IF YOU PREFER TO USE ZMQ (message based), then rebuild from main folder like this:\n"
				   "cd ..; make clean; make\n\n", 
				   OTLog::Version());

	OT_API::InitOTAPI();

	// -----------------------------------------------------------------------
	// The beginnings of an INI file!!

	OTString strPath;

	{
		CSimpleIniA ini; // We're assuming this file is on the path.
		SI_Error rc = ini.LoadFile("./.ot_ini"); // todo: stop hardcoding. 

		if (rc >=0)
		{
			const char * pVal = ini.GetValue("paths", "client_path", SERVER_PATH_DEFAULT); // todo stop hardcoding.

			if (NULL != pVal)
				strPath.Set(pVal);
			else
				strPath.Set(SERVER_PATH_DEFAULT);
		}
		else 
		{
			strPath.Set(SERVER_PATH_DEFAULT);
		}
	}
	// -----------------------------------------------------------------------

	OTString strCAFile, strKeyFile, strSSLPassword;

	if (argc < 2)
	{
		OTLog::vOutput(0, "\n==> USAGE:    %s   <SSL-password>  <absolute_path_to_data_folder>\n\n"
#if defined (FELLOW_TRAVELER)					   
				"(Password defaults to '%s' if left blank.)\n"
				"(Folder defaults to '%s' if left blank.)\n"
#else
				"(The test password is always 'test'.\n'cd data_folder' then 'pwd' to see the absolute path.)\n"
#endif
					   "\n\n", argv[0]
#if defined (FELLOW_TRAVELER)					   
					   , KEY_PASSWORD, 
					   strPath.Get()
#endif					   
					   );
	
#if defined (FELLOW_TRAVELER)
		strSSLPassword.Set(KEY_PASSWORD);

		OTString strClientPath(strPath.Get());
        g_OT_API.Init(strClientPath);  // SSL gets initialized in here, before any keys are loaded.
#else
		exit(1);
#endif
	}
	else if (argc < 3)
	{
		OTLog::vOutput(0, "\n==> USAGE:    %s   <SSL-password>  <absolute_path_to_data_folder>\n\n"
#if defined (FELLOW_TRAVELER)					      
				"(Folder defaults to '%s' if left blank.)\n"
#endif
					   "\n\n", argv[0]
#if defined (FELLOW_TRAVELER)
					   , strPath.Get()
#endif
					   );
		
#if defined (FELLOW_TRAVELER)					   
		strSSLPassword.Set(argv[1]);

		OTString strClientPath(strPath.Get());
        g_OT_API.Init(strClientPath);  // SSL gets initialized in here, before any keys are loaded.
#else
		exit(1);
#endif
	}
	else 
	{
		strSSLPassword.Set(argv[1]);

		OTString strClientPath(argv[2]);
        g_OT_API.Init(strClientPath);  // SSL gets initialized in here, before any keys are loaded.
	}	

	OTLog::vOutput::(0, "Using as path to data folder:  %s\n", OTLog::Path());

	strCAFile. Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), CA_FILE);
	strKeyFile.Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), KEY_FILE);


	// ------------------------------------------------------------------------------

	//
	// Basically, loop:
	//
	//	1) Present a prompt, and get a user string of input. Wait for that.
	//
	//	2) Process it out as an OTMessage to the server. It goes down the pipe.
	//
	//	3) Sleep for 1 second.
	//
	//	4) Awake and check for messages to be read in response from the server.
	//	   Loop. As long as there are any responses there, then process and handle
	//	   them all.
	//	   Then continue back up to the prompt at step (1).

    char buf[200] = "";
 	int retVal = 0;

	int nExpectResponse = 0;

	OTLog::Output(0, "You may wish to 'load' then 'connect' then 'stat'.\n");
	OTLog::vOutput(4, "Starting client loop. u_header size in C code is %d.\n", OT_CMD_HEADER_SIZE);


	for(;;)
	{
		buf[0] = 0; // Making it fresh again.

		nExpectResponse = 0;

		// 1) Present a prompt, and get a user string of input. Wait for that.
		OTLog::Output(0, "\nWallet> ");

		if (NULL == fgets(buf, sizeof(buf)-10, stdin)) // Leaving myself 10 extra bytes at the end for safety's sake.
            break;

		OTLog::Output(0, ".\n..\n...\n....\n.....\n......\n.......\n........\n.........\n..........\n"
				"...........\n............\n.............\n");

		// so we can process the user input
		std::string strLine = buf;

		// 1.5 The one command that doesn't involve a message to the server (so far)
		//     is the command to load the wallet from disk (which we do before we can
		//     do anything else.)  That and maybe the message to CONNECT to the server.
		// Load wallet.xml
		if (strLine.compare(0,4,"load") == 0)
		{
			OTLog::Output(0, "User has instructed to load wallet.xml...\n");
			g_OT_API.GetWallet()->LoadWallet("wallet.xml");
 
//			g_OT_API.GetWallet()->SaveWallet("NEWwallet.xml"); // todo remove this test code.

			continue;
		}

		else if (strLine.compare(0,5,"clear") == 0)
		{
			if (NULL == g_pTemporaryNym)
			{
				OTLog::Output(0, "No Nym yet available. Try 'load'.\n");
				continue;
			}

			g_pTemporaryNym->RemoveAllNumbers();

			g_pTemporaryNym->SaveSignedNymfile(*g_pTemporaryNym);

			OTLog::Output(0, "Successfully removed all issued and transaction numbers. Saving nym...\n");

			continue;
		}			

		else if (strLine.compare(0,7,"payment") == 0)
		{
			if (NULL == g_pTemporaryNym)
			{
				OTLog::Output(0, "No Nym yet available to sign the payment plan with. Try 'load'.\n");
				continue;
			}

			OTLog::Output(0, "Enter your Asset Account ID that the payments will come from: ");
			OTString strTemp;
			strTemp.OTfgets(std::cin);

			const OTIdentifier ACCOUNT_ID(strTemp), USER_ID(*g_pTemporaryNym);
			OTAccount * pAccount = g_OT_API.GetWallet()->GetAccount(ACCOUNT_ID);

			if (NULL == pAccount)
			{
				OTLog::Output(0, "That account isn't loaded right now. Try 'load'.\n");
				continue;
			}

			// To write a payment plan, like a cheque, we need to burn one of our transaction numbers. (Presumably
			// the wallet is also storing a couple of these, since they are needed to perform any transaction.)
			//
			// I don't have to contact the server to write a payment plan -- as long as I already have a transaction
			// number I can use to write it. Otherwise I'd have to ask the server to send me one first.
			OTString strServerID(pAccount->GetRealServerID());
			long lTransactionNumber=0;

			if (false == g_pTemporaryNym->GetNextTransactionNum(*g_pTemporaryNym, strServerID, lTransactionNumber))
			{
				OTLog::Output(0, "Payment Plans are written offline, but you still need a transaction number\n"
							  "(and you have none, currently.) Try using 'n' to request another transaction number.\n");
				continue;
			}

			// -----------------------------------------------------------------------

			OTString str_RECIPIENT_USER_ID, str_RECIPIENT_ACCT_ID, strConsideration;

			// Get the Recipient Nym ID
			OTLog::Output(0, "Enter the Recipient's User ID (NymID): ");
			str_RECIPIENT_USER_ID.OTfgets(std::cin);		


			// THEN GET AN ACCOUNT ID in that same asset type
			OTLog::Output(0, "Enter the Recipient's ACCOUNT ID (of the same asset type as your account): ");
			str_RECIPIENT_ACCT_ID.OTfgets(std::cin);		

			OTLog::Output(0, "Enter a memo describing consideration for the payment plan: ");
			strConsideration.OTfgets(std::cin);		

			const OTIdentifier	RECIPIENT_USER_ID(str_RECIPIENT_USER_ID), 
								RECIPIENT_ACCT_ID(str_RECIPIENT_ACCT_ID);


			OTPaymentPlan thePlan(pAccount->GetRealServerID(), pAccount->GetAssetTypeID(),
								  pAccount->GetRealAccountID(),	pAccount->GetUserID(),
								  RECIPIENT_ACCT_ID, RECIPIENT_USER_ID);

			// -----------------------------------------------------------------------

			// Valid date range (in seconds)
			OTLog::Output(0, 
						  " 6 minutes	==      360 Seconds\n"
						  "10 minutes	==      600 Seconds\n"
						  "1 hour		==     3600 Seconds\n"
						  "1 day		==    86400 Seconds\n"
						  "30 days			==  2592000 Seconds\n"
						  "3 months		==  7776000 Seconds\n"
						  "6 months		== 15552000 Seconds\n\n"
						  );

			long lExpirationInSeconds = 86400;
			OTLog::vOutput(0, "How many seconds before payment plan expires? (defaults to 1 day: %ld): ", lExpirationInSeconds);
			strTemp.Release();
			strTemp.OTfgets(std::cin);

			if (strTemp.GetLength() > 1)
				lExpirationInSeconds = atol(strTemp.Get());


			// -----------------------------------------------------------------------

			time_t	VALID_FROM	= time(NULL); // This time is set to TODAY NOW

			OTLog::vOutput(0, "Payment plan becomes valid for processing STARTING date\n"
						   "(defaults to now, in seconds) [%ld]: ", VALID_FROM);
			strTemp.Release();
			strTemp.OTfgets(std::cin);

			if (strTemp.GetLength() > 2)
				VALID_FROM = atol(strTemp.Get());

			const time_t VALID_TO = VALID_FROM + lExpirationInSeconds; // now + 86400

			// -----------------------------------------------------------------------

			bool bSuccessSetAgreement = thePlan.SetAgreement(lTransactionNumber, strConsideration, VALID_FROM,	VALID_TO);

			if (!bSuccessSetAgreement)
			{
				OTLog::Output(0, "Failed trying to set the agreement!\n");

				// IF FAILED, ADD TRANSACTION NUMBER BACK TO LIST OF AVAILABLE NUMBERS.
				g_pTemporaryNym->AddTransactionNum(*g_pTemporaryNym, strServerID, lTransactionNumber, true); // bSave=true								

				continue;
			}

			bool bSuccessSetInitialPayment	= true; // the default, in case user chooses not to even have this payment.
			bool bSuccessSetPaymentPlan		= true; // the default, in case user chooses not to have a payment plan
			// -----------------------------------------------------------------------

			OTLog::Output(0, "What is the Initial Payment Amount, if any? [0]: ");
			strTemp.Release(); strTemp.OTfgets(std::cin);
			long lInitialPayment = atol(strTemp.Get());

			if (lInitialPayment > 0)
			{
				time_t	PAYMENT_DELAY = 60; // 60 seconds.

				OTLog::vOutput(0, "From the Start Date forward, how long until the Initial Payment should charge?\n"
							   "(defaults to one minute, in seconds) [%d]: ", PAYMENT_DELAY);
				strTemp.Release();
				strTemp.OTfgets(std::cin);

				if ((strTemp.GetLength() > 1) && atol(strTemp.Get())>0)
					PAYMENT_DELAY = atol(strTemp.Get());

				// -----------------------------------------------------------------------

				 bSuccessSetInitialPayment = thePlan.SetInitialPayment(lInitialPayment, PAYMENT_DELAY);
			}

			if (!bSuccessSetInitialPayment)
			{
				OTLog::Output(0, "Failed trying to set the initial payment!\n");

				// IF FAILED, ADD TRANSACTION NUMBER BACK TO LIST OF AVAILABLE NUMBERS.
				g_pTemporaryNym->AddTransactionNum(*g_pTemporaryNym, strServerID, lTransactionNumber, true); // bSave=true								

				continue;
			}

			// -----------------------------------------------------------------------

			OTLog::Output(0, "What is the regular payment amount, if any? [0]: ");
			strTemp.Release(); strTemp.OTfgets(std::cin);
			long lRegularPayment = atol(strTemp.Get());

			if (lRegularPayment > 0) // If there are regular payments.
			{
				// -----------------------------------------------------------------------

				time_t	PAYMENT_DELAY = 120; // 120 seconds.

				OTLog::vOutput(0, "From the Start Date forward, how long until the Regular Payments start?\n"
							   "(defaults to two minutes, in seconds) [%d]: ", PAYMENT_DELAY);
				strTemp.Release();
				strTemp.OTfgets(std::cin);

				if ((strTemp.GetLength() > 1) && atol(strTemp.Get())>0)
					PAYMENT_DELAY = atol(strTemp.Get());

				// -----------------------------------------------------------------------

				time_t	PAYMENT_PERIOD = 30; // 30 seconds.

				OTLog::vOutput(0, "Once payments begin, how much time should elapse between each payment?\n"
							   "(defaults to thirty seconds) [%d]: ", PAYMENT_PERIOD);
				strTemp.Release();
				strTemp.OTfgets(std::cin);

				if ((strTemp.GetLength() > 1) && atol(strTemp.Get())>0)
					PAYMENT_PERIOD = atol(strTemp.Get());

				// -----------------------------------------------------------------------

				time_t	PLAN_LENGTH = 0; // 0 seconds (for no max length).

				OTLog::vOutput(0, "From start date, do you want the plan to expire after a certain maximum time?\n"
							   "(defaults to 0 for no) [%d]: ", PLAN_LENGTH);
				strTemp.Release();
				strTemp.OTfgets(std::cin);

				if (strTemp.GetLength() > 1)
					PLAN_LENGTH = atol(strTemp.Get());

				// -----------------------------------------------------------------------

				OTLog::Output(0, "Should there be some maximum number of payments? (Zero for no maximum.) [0]: ");
				strTemp.Release(); strTemp.OTfgets(std::cin);
				int nMaxPayments = atoi(strTemp.Get());

				bSuccessSetPaymentPlan = thePlan.SetPaymentPlan(lRegularPayment, PAYMENT_DELAY, PAYMENT_PERIOD, PLAN_LENGTH, nMaxPayments);
			}

			if (!bSuccessSetPaymentPlan)
			{
				OTLog::Output(0, "Failed trying to set the payment plan!\n");

				// IF FAILED, ADD TRANSACTION NUMBER BACK TO LIST OF AVAILABLE NUMBERS.
				g_pTemporaryNym->AddTransactionNum(*g_pTemporaryNym, strServerID, lTransactionNumber, true); // bSave=true								

				continue;
			}

			thePlan.SignContract(*g_pTemporaryNym);
			thePlan.SaveContract();

			OTString strPlan(thePlan);

			OTLog::vOutput(0, "\n\n(Make sure Both Parties sign the payment plan before submitting to server):\n\n\n%s\n", 
						   strPlan.Get());

			continue;			
		}


		else if (strLine.compare(0,6,"cheque") == 0)
		{
			if (NULL == g_pTemporaryNym)
			{
				OTLog::Output(0, "No Nym yet available to sign the cheque with. Try 'load'.\n");
				continue;
			}


			OTLog::Output(0, "Enter the ID for your Asset Account that the cheque will be drawn on: ");
			OTString strTemp;
			strTemp.OTfgets(std::cin);

			const OTIdentifier ACCOUNT_ID(strTemp), USER_ID(*g_pTemporaryNym);
			OTAccount * pAccount = g_OT_API.GetWallet()->GetAccount(ACCOUNT_ID);

			if (NULL == pAccount)
			{
				OTLog::Output(0, "That account isn't loaded right now. Try 'load'.\n");
				continue;
			}

			// To write a cheque, we need to burn one of our transaction numbers. (Presumably the wallet
			// is also storing a couple of these, since they are needed to perform any transaction.)
			//
			// I don't have to contact the server to write a cheque -- as long as I already have a transaction
			// number I can use to write it. Otherwise I'd have to ask the server to send me one first.
			OTString strServerID(pAccount->GetRealServerID());
			long lTransactionNumber=0;

			if (false == g_pTemporaryNym->GetNextTransactionNum(*g_pTemporaryNym, strServerID, lTransactionNumber))
			{
				OTLog::Output(0, "Cheques are written offline, but you still need a transaction number\n"
						"(and you have none, currently.) Try using 'n' to request another transaction number.\n");
				continue;
			}


			OTCheque theCheque(pAccount->GetRealServerID(), pAccount->GetAssetTypeID());

			// Recipient
			OTLog::Output(0, "Enter a User ID for the recipient of this cheque (defaults to blank): ");
			OTString strRecipientUserID;
			strRecipientUserID.OTfgets(std::cin);
			const OTIdentifier RECIPIENT_USER_ID(strRecipientUserID.Get());

			// Amount
			OTLog::Output(0, "Enter an amount: ");
			strTemp.Release();
			strTemp.OTfgets(std::cin);
			const long lAmount = atol(strTemp.Get());

			// -----------------------------------------------------------------------

			// Memo
			OTLog::Output(0, "Enter a memo for your check: ");
			OTString strChequeMemo;
			strChequeMemo.OTfgets(std::cin);

			// -----------------------------------------------------------------------

			// Valid date range (in seconds)
			OTLog::Output(0, 
					" 6 minutes	==      360 Seconds\n"
					"10 minutes	==      600 Seconds\n"
					"1 hour		==     3600 Seconds\n"
					"1 day		==    86400 Seconds\n"
					"30 days	==  2592000 Seconds\n"
					"3 months	==  7776000 Seconds\n"
					"6 months	== 15552000 Seconds\n\n"
					);

			long lExpirationInSeconds = 3600;
			OTLog::vOutput(0, "How many seconds before cheque expires? (defaults to 1 hour: %ld): ", lExpirationInSeconds);
			strTemp.Release();
			strTemp.OTfgets(std::cin);

			if (strTemp.GetLength() > 1)
				lExpirationInSeconds = atol(strTemp.Get());


			// -----------------------------------------------------------------------

			time_t	VALID_FROM	= time(NULL); // This time is set to TODAY NOW

			OTLog::vOutput(0, "Cheque may be cashed STARTING date (defaults to now, in seconds) [%ld]: ", VALID_FROM);
			strTemp.Release();
			strTemp.OTfgets(std::cin);

			if (strTemp.GetLength() > 2)
				VALID_FROM = atol(strTemp.Get());


			const time_t VALID_TO = VALID_FROM + lExpirationInSeconds; // now + 3600

			// -----------------------------------------------------------------------

			bool bIssueCheque = theCheque.IssueCheque(lAmount, lTransactionNumber, VALID_FROM, VALID_TO, 
													  ACCOUNT_ID, USER_ID, strChequeMemo,
													  (strRecipientUserID.GetLength() > 2) ? &(RECIPIENT_USER_ID) : NULL);

			if (bIssueCheque)
			{
				theCheque.SignContract(*g_pTemporaryNym);
				theCheque.SaveContract();

				OTString strCheque(theCheque);

				OTLog::vOutput(0, "\n\nOUTPUT:\n\n\n%s\n", strCheque.Get());
			}
			else 
			{
				OTLog::Output(0, "Failed trying to issue the cheque!\n");

				// IF FAILED, ADD TRANSACTION NUMBER BACK TO LIST OF AVAILABLE NUMBERS.
				g_pTemporaryNym->AddTransactionNum(*g_pTemporaryNym, strServerID, lTransactionNumber, true); // bSave=true								
			}

			continue;
		}

		else if (strLine.compare(0,7,"decrypt") == 0)
		{
			if (NULL == g_pTemporaryNym)
			{
				OTLog::Output(0, "No Nym yet available to decrypt with.\n");
				continue;
			}

			OTLog::Output(0, "Enter text to be decrypted:\n> ");

			OTASCIIArmor theArmoredText;
			char decode_buffer[200]; // Safe since we only read sizeof - 1

			do {
				decode_buffer[0] = 0;
				if (NULL != fgets(decode_buffer, sizeof(decode_buffer)-1, stdin))
				{
					theArmoredText.Concatenate("%s\n", decode_buffer);
					OTLog::Output(0, "> ");
				}
				else 
				{
					break;
				}
			} while (strlen(decode_buffer)>1);


			OTEnvelope	theEnvelope(theArmoredText);
			OTString	strDecodedText;

			theEnvelope.Open(*g_pTemporaryNym, strDecodedText);

			OTLog::vOutput(0, "\n\nDECRYPTED TEXT:\n\n%s\n\n", strDecodedText.Get());

			continue;
		}

		else if (strLine.compare(0,6,"decode") == 0)
		{
			OTLog::Output(0, "Enter text to be decoded:\n> ");

			OTASCIIArmor theArmoredText;
			char decode_buffer[200]; // Safe since we only read sizeof - 1.

			do {
				decode_buffer[0] = 0;
				if (NULL != fgets(decode_buffer, sizeof(decode_buffer)-1, stdin))
				{
					theArmoredText.Concatenate("%s\n", decode_buffer);
					OTLog::Output(0, "> ");
				}
				else 
				{
					break;
				}

			} while (strlen(decode_buffer)>1);

			OTString strDecodedText(theArmoredText);

			OTLog::vOutput(0, "\n\nDECODED TEXT:\n\n%s\n\n", strDecodedText.Get());

			continue;
		}

		else if (strLine.compare(0,6,"encode") == 0)
		{
			OTLog::Output(0, "Enter text to be ascii-encoded (terminate with ~ on a new line):\n> ");

			OTString strDecodedText;
			char decode_buffer[200]; // Safe since we only read sizeof - 1.

			do {
				decode_buffer[0] = 0;

				if ((NULL != fgets(decode_buffer, sizeof(decode_buffer)-1, stdin)) &&
					(decode_buffer[0] != '~'))
				{
					strDecodedText.Concatenate("%s", decode_buffer);
					OTLog::Output(0, "> ");
				}
				else 
				{
					break;
				}

			} while (decode_buffer[0] != '~');

			OTASCIIArmor theArmoredText(strDecodedText);

			OTLog::vOutput(0, "\n\nENCODED TEXT:\n\n%s\n\n", theArmoredText.Get());

			continue;
		}

		else if (strLine.compare(0,4,"hash") == 0)
		{
			OTLog::Output(0, "Enter text to be hashed (terminate with ~ on a new line):\n> ");

			OTString strDecodedText;
			char decode_buffer[200]; // Safe since we only read sizeof - 1.

			do {
				decode_buffer[0] = 0;

				if ((NULL != fgets(decode_buffer, sizeof(decode_buffer)-1, stdin)) &&
					(decode_buffer[0] != '~'))
				{
					strDecodedText.Concatenate("%s\n", decode_buffer);
					OTLog::Output(0, "> ");
				}
				else 
				{
					break;
				}

			} while (decode_buffer[0] != '~');

			OTIdentifier theIdentifier;
			theIdentifier.CalculateDigest(strDecodedText);

			OTString strHash(theIdentifier);

			OTLog::vOutput(0, "\n\nMESSAGE DIGEST:\n\n%s\n\n", strHash.Get());

			continue;
		}

		else if (strLine.compare(0,4,"stat") == 0)
		{
			OTLog::Output(0, "User has instructed to display wallet contents...\n");

			OTString strStat;
			g_OT_API.GetWallet()->DisplayStatistics(strStat);
			OTLog::vOutput(0, "%s\n", strStat.Get());

			continue;
		}

		else if (strLine.compare(0,4,"help") == 0)
		{
			OTLog::Output(0, "User has instructed to display the help file...\n");

			system("more ../docs/CLIENT-COMMANDS.txt");

			continue;
		}

		else if (strLine.compare(0,4,"quit") == 0)
		{
			OTLog::Output(0, "User has instructed to exit the wallet...\n");

			break;
		}

		// 1.6 Connect to the first server in the wallet. (assuming it loaded a server contract.)
		else if (strLine.compare(0,7,"connect") == 0)
		{
			OTLog::Output(0, "User has instructed to connect to the first server available in the wallet.\n");

			if (NULL == g_pTemporaryNym)
			{
				OTLog::Output(0, "No Nym yet available to connect with. Try 'load'.\n");
				continue;
			}

			// Wallet, after loading, should contain a list of server
			// contracts. Let's pull the hostname and port out of
			// the first contract, and connect to that server.
			bool bConnected = g_OT_API.GetClient()->ConnectToTheFirstServerOnList(*g_pTemporaryNym, strCAFile, strKeyFile, strSSLPassword); 

			if (bConnected)
				OTLog::Output(0, "Success. (Connected to the first notary server on your wallet's list.)\n");
			else {
				OTLog::Output(0, "Either the wallet is not loaded, or there was an error connecting to server.\n");
			}

			continue;
		}

		if (!g_OT_API.GetClient()->IsConnected())
		{
			OTLog::Output(0, "(You are not connected to a notary server--you cannot send commands.)\n");
			continue;
		}

		// 2) Process it out as an OTMessage to the server. It goes down the pipe.
		g_OT_API.GetClient()->ProcessMessageOut(buf, &nExpectResponse);
		
		// 3) Sleep for 1 second.
#ifdef _WIN32
		OT_Sleep(1000);
#else
		sleep (1);
#endif

		bool bFoundMessage = false;

		// 4) While there are messages to be read in response from the server,
		//	  then process and handle them all.
		do 
		{
			OTMessage * pMsg = new OTMessage;

			OT_ASSERT(NULL != pMsg);

			// If this returns true, that means a Message was
			// received and processed into an OTMessage object (theMsg)
			bFoundMessage = g_OT_API.GetClient()->ProcessInBuffer(*pMsg);

			if (true == bFoundMessage)
			{
//				OTString strReply;
//				theMsg.SaveContract(strReply);
//				OTLog::vOutput(0, "\n\n**********************************************\n"
//						"Successfully in-processed server response.\n\n%s\n", strReply.Get());
				g_OT_API.GetClient()->ProcessServerReply(*pMsg); // the Client takes ownership and will handle cleanup.
			}
			else 
			{
				delete pMsg;
				pMsg = NULL;
			}


		} while (true == bFoundMessage);
	} // for

	OTLog::Output(0, "Finished running client.\n");

#ifdef _WIN32
	WSACleanup();
#endif

	return retVal;
}
Пример #29
0
  void Config::loadCommonValues(string configFile)
  {

    CSimpleIniA iniObj;
    iniObj.LoadFile(configFile.c_str());
    CSimpleIniA* ini = &iniObj;
    
    runtimeBaseDir = getString(ini, "", "runtime_dir", "/usr/share/openalpr/runtime_data");

    std::string detectorString = getString(ini, "", "detector", "lbpcpu");
    std::transform(detectorString.begin(), detectorString.end(), detectorString.begin(), ::tolower);

    if (detectorString.compare("lbpcpu") == 0)
      detector = DETECTOR_LBP_CPU;
    else if (detectorString.compare("lbpgpu") == 0)
      detector = DETECTOR_LBP_GPU;
    else if (detectorString.compare("morphcpu") == 0)
      detector = DETECTOR_MORPH_CPU;
    else
    {
      std::cerr << "Invalid detector specified: " << detectorString << ".  Using default" << std::endl;
      detector = DETECTOR_LBP_CPU;
    }
    
    detection_iteration_increase = getFloat(ini, "", "detection_iteration_increase", 1.1);
    detectionStrictness = getInt(ini, "", "detection_strictness", 3);
    maxPlateWidthPercent = getFloat(ini, "", "max_plate_width_percent", 100);
    maxPlateHeightPercent = getFloat(ini, "", "max_plate_height_percent", 100);
    maxDetectionInputWidth = getInt(ini, "", "max_detection_input_width", 1280);
    maxDetectionInputHeight = getInt(ini, "", "max_detection_input_height", 768);

    skipDetection = getBoolean(ini, "", "skip_detection", false);
    
    prewarp = getString(ini, "", "prewarp", "");
            
    maxPlateAngleDegrees = getInt(ini, "", "max_plate_angle_degrees", 15);


    ocrImagePercent = getFloat(ini, "", "ocr_img_size_percent", 100);
    stateIdImagePercent = getFloat(ini, "", "state_id_img_size_percent", 100);

    ocrMinFontSize = getInt(ini, "", "ocr_min_font_point", 100);

    postProcessMinConfidence = getFloat(ini, "", "postprocess_min_confidence", 100);
    postProcessConfidenceSkipLevel = getFloat(ini, "", "postprocess_confidence_skip_level", 100);
    postProcessMinCharacters = getInt(ini, "", "postprocess_min_characters", 100);
    postProcessMaxCharacters = getInt(ini, "", "postprocess_max_characters", 100);

    debugGeneral = 	getBoolean(ini, "", "debug_general",		false);
    debugTiming = 	getBoolean(ini, "", "debug_timing",		false);
    debugPrewarp = 	getBoolean(ini, "", "debug_prewarp",		false);
    debugDetector = 	getBoolean(ini, "", "debug_detector",		false);
    debugStateId = 	getBoolean(ini, "", "debug_state_id",		false);
    debugPlateLines = 	getBoolean(ini, "", "debug_plate_lines", 	false);
    debugPlateCorners = 	getBoolean(ini, "", "debug_plate_corners", 	false);
    debugCharSegmenter = 	getBoolean(ini, "", "debug_char_segment", 	false);
    debugCharAnalysis =	getBoolean(ini, "", "debug_char_analysis",	false);
    debugColorFiler = 	getBoolean(ini, "", "debug_color_filter", 	false);
    debugOcr = 		getBoolean(ini, "", "debug_ocr", 		false);
    debugPostProcess = 	getBoolean(ini, "", "debug_postprocess", 	false);
    debugShowImages = 	getBoolean(ini, "", "debug_show_images",	false);
    debugPauseOnFrame = 	getBoolean(ini, "", "debug_pause_on_frame",	false);

  }
Пример #30
0
void ConfigOptions::init()
{
	//Opening ini file
	CSimpleIniA ini;
	ini.SetUnicode();
	ini.SetMultiKey();
	if (ini.LoadFile("Config.ini") == SI_OK)
	{
		/////////////////////GAMEPLAY///////////////////////////////
		//Difficulty
		m_aiThinkingTime = atoi(ini.GetValue("Gameplay", "Difficulty", "1"));
		m_p1AI = ini.GetBoolValue("Gameplay", "Player1AI", 0);
		m_p2AI = ini.GetBoolValue("Gameplay", "Player2AI", 0);
		m_dialogOn = ini.GetBoolValue("Gameplay", "ShowDialog", 0);
		m_autoReset = ini.GetBoolValue("Gameplay", "AutoReset", 0);

		/////////////////////GRAPHICS///////////////////////////////
		//Resoltion
		m_resolution = sf::Vector2i(atoi(ini.GetValue("Graphics", "ScreenWidth", "1920")), atoi(ini.GetValue("Graphics", "ScreenHeight", "1080")));
		m_inFullscreen = ini.GetBoolValue("Graphics", "FullScreen", 0);
		m_view.SetFromRect(sf::FloatRect(0, 0, (float) nativeWidth(), (float) nativeHeight()));

		//////////////////////CONTROLS/////////////////////////////
		std::string item;
		std::string val;

		//Keys
		std::map<std::string, sf::Key::Code> allKeys = getNamedKeys();

		// if there are keys and values...
		const CSimpleIniA::TKeyVal* keys = ini.GetSection("KeyboardControls");
		if (keys)
		{
			// iterate over all keys and dump the key name and value
			for (CSimpleIniA::TKeyVal::const_iterator it = keys->begin() ; it != keys->end() ; ++it)
			{
				item = it->first.pItem;
				val = it->second;
				m_iHandler.map(item, allKeys[val]);
			}
		}

		//Mouse buttons
		std::map<std::string, sf::Mouse::Button> allButtons = getNamedButtons();

		// if there are keys and values...
		const CSimpleIniA::TKeyVal* buttons = ini.GetSection("MouseControls");
		if (keys)
		{
			// iterate over all keys and dump the key name and value
			for (CSimpleIniA::TKeyVal::const_iterator it = buttons->begin() ; it != buttons->end() ; ++it)
			{
				item = it->first.pItem;
				val = it->second;
				m_iHandler.map(item, allButtons[val]);
			}
		}

		//////////////////////OTHER/////////////////////////////

		m_theme = ini.GetValue("Graphics", "Theme", "");
		if (m_theme == "Default") //default theme
			m_theme = "";
	}
	else
	{
		std::cerr << "Unable to load file : Config.ini" << std::endl;
	}
}