Example #1
0
/** 将 configures 中的配置信息写入 fp */
static int write_configures(FILE *fp, Configure *configures)
{
    Configure *tc;

    for(tc = configures; tc->name; tc++){
        if(tc->comment)
            fprintf(fp, "# %s\n", tc->comment);
        if(tc->config_rw)
            tc->config_rw(tc, fp, 0);
        else{
            switch(tc->value_type){
                case CONFIG_INTEGER:
                    generic_config_integer(tc, fp, 0);
                    break;
                case CONFIG_STRING:
                    generic_config_string(tc, fp, 0);
                    break;
                case CONFIG_COLOR:
                    generic_config_color(tc, fp, 0);
                    break;
                default:
                    fprintf(stderr, "error: shouldn't be here\n");
                    exit(1);
            }
        }
    }
    return 0;
}
Example #2
0
    CacheMonitorServer::CacheMonitorServer()
    : folderCache_(Factory::GetCacheFolder()),
      folderMeta_(Factory::GetMetaFolder()),
      run_(true),
      minFreeSize_(0), maxFreeSize_(0),
      thread_(boost::thread(&CacheMonitorServer::ServerThread,this))
    {
        struct statfs stat;
        if ( 0 != statfs(folderCache_.string().c_str(),&stat) ) {
            LogWarn(folderCache_);
            return;
        }
        off_t sizeFileSystemOnePercent =
                (off_t)stat.f_bsize * stat.f_blocks / 100;

        Configure * config = Factory::GetConfigure();

        minFreeSize_ = config->GetValueSize(Configure::CacheFreeMinSize);
        off_t sizeMinFreePercent = sizeFileSystemOnePercent
                * config->GetValueSize(Configure::CacheFreeMinPercent);
        minFreeSize_ = max(minFreeSize_,sizeMinFreePercent);
        LogDebug(minFreeSize_);

        maxFreeSize_ = config->GetValueSize(Configure::CacheFreeMaxSize);
        off_t sizeMaxFreePercent = sizeFileSystemOnePercent
                * config->GetValueSize(Configure::CacheFreeMaxPercent);
        maxFreeSize_ = max(maxFreeSize_,sizeMaxFreePercent);
        LogDebug(maxFreeSize_);
    }
Example #3
0
void
ConfigureTest::testConfigure()
{
    ofstream config(configFile.c_str());
    config << Configure::CacheFreeMinPercent << " : 5" << endl;
    config << Configure::CacheFreeMaxPercent << " : 10" << endl;
    config << Configure::CacheFileSizeRead << " : 1000000000" << endl;
    config << Configure::FileMaxSize << " : 8000000000" << endl;

    Configure configure;
    configure.Refresh(fileConfig);
    CPPUNIT_ASSERT(
            configure.GetValue(Configure::CacheFreeMinPercent) == "5");
    CPPUNIT_ASSERT(
            configure.GetValueSize(Configure::CacheFreeMinPercent) == 5);
    CPPUNIT_ASSERT(
            configure.GetValue(Configure::CacheFreeMaxPercent) == "10");
    CPPUNIT_ASSERT(
            configure.GetValueSize(Configure::CacheFreeMaxPercent) == 10);
    CPPUNIT_ASSERT(
            configure.GetValue(Configure::CacheFileSizeRead) == "1000000000");
    CPPUNIT_ASSERT(
            configure.GetValueSize(Configure::CacheFileSizeRead)
                == 1000000000LL );
    CPPUNIT_ASSERT(
            configure.GetValue(Configure::FileMaxSize) == "8000000000");
    CPPUNIT_ASSERT(
            configure.GetValueSize(Configure::FileMaxSize) == 8000000000LL );
}
Example #4
0
void Main::obrir_configuracio_worker(bool first) {
        Configure *c = new Configure;
	c->carregar_config();
	c->setFirst(first);
	c->exec();

	delete c;
	
        carrega_config(0);
}
/*
    after some specific time ,
    merge cache data with disk file and update every thread's cache
    then every thread has the same cache
*/
void CacheManagerThread::synchronizeGlobalCacheWithDisk()
{
#ifndef NDEBUG
    WRITE_STR(string(" start synchronize Global Cache With Disk ......."));
#endif
    Configure *pconf = Configure::getInstance();
    string cache_path = pconf->getConfigByName("cache_file_path");
    string home_path = pconf->getConfigByName("home_path");
#ifndef NDEBUG
    WRITE_STR(string(" 1st. merge the disk cache data to memory ......."));
#endif
    // 1st. merge the disk cache data to memory;
    ifstream ifs((home_path + cache_path).c_str());
    if (!(ifs.is_open()))
    {
        throw runtime_error("open cache_path file");
    }
    string line, keyword, pairword;
    int frequency;
    while (getline(ifs, line))
    {
        istringstream istr(line);
        istr >> keyword;
        vector<pair<string, int> > vec;
        while (istr >> pairword)
        {
            istr >> frequency;
            vec.push_back(make_pair(pairword, frequency));
        }
        CacheData data(vec);
        global_cache_map_.insert(make_pair(keyword, data));
    }
    ifs.close();
#ifndef NDEBUG
    WRITE_STR(string(" 2nd. write the cache data back to disk...... "));
#endif
    // 2nd. write the global cache data back to disk;
    ofstream ofs((home_path + cache_path).c_str());
    // file lock;
    if (!(ofs.is_open()))
    {
        throw runtime_error("open cache_path file");
    }
    for (Cache::cache_map_type::iterator iter = global_cache_map_.begin() ; iter != global_cache_map_.end(); ++iter)
    {
        ofs << (*iter).first << "\t";
        vector<pair<string, int> > vec = (*iter).second.getDataVec();
        for (vector<pair<string, int> >::iterator it = vec.begin(); it != vec.end(); ++it)
        {
            ofs << (*it).first << " " << (*it).second<<" ";
        }
        ofs << "\n";
    }
    ofs.close();
}
Example #6
0
int main(int argc, char** argv) {
	cfg.path("../../setup");
	cfg.args("detector.webcam.provider.", argv);
	if (argc == 1) cfg.load("config.csv");
	bool verbose = cfg.flag("detector.webcam.provider.verbose", true);
	if (verbose) cfg.show();
		
	int indexR = (int)cfg.num("detector.webcam.provider.indexR");
	int indexL = (int)cfg.num("detector.webcam.provider.indexL");
	int sleep_time = (int)cfg.num("detector.webcam.provider.sleep_time");
	std::string addressf = cfg.str("detector.webcam.provider.f_ip").c_str();
	std::string addressc = cfg.str("detector.webcam.provider.c_ip").c_str();
	std::string port = cfg.str("detector.webcam.provider.port").c_str();

	signal(SIGINT, quitproc);
	signal(SIGTERM, quitproc);
	signal(SIGQUIT, quitproc);

	webcamProvider p(indexR, indexL, sleep_time, verbose, argv[0], addressf.c_str(), addressc.c_str(), port);
	ghost = &p;	
	if(p.init()) {
		//p.rotate();
		p.provide();
		
	}

	return 0;
}
void CacheManagerThread::run()
{
    while (true)
    {
#ifndef NDEBUG
        WRITE_STR("start updateCache .......");
#endif
        updateCache();
        // 每隔一段时间就更新所有cache
        Configure *pconf = Configure::getInstance();
        string s_time = pconf->getConfigByName("cache_manager_sleep_seconds");
        int sleep_time = atoi(s_time.c_str());
        sleep(sleep_time);
    }
}
Example #8
0
/// 读取配置数据
void loadConfig() {
    config.load();
    printf("FrontAddress=%s\n",config.FrontAddress);
    printf("BrokerID=%s\n",config.BrokerID);
    printf("UserID=%s\n",config.UserID);
    printf("Password=%s\n",config.Password);
    printf("RequestPipe=%s\n",config.RequestPipe);
    printf("PushbackPipe=%s\n",config.PushbackPipe);
    printf("PublishPipe=%s\n",config.PublishPipe);
}
Example #9
0
void DictManager::initialization()
{
    Configure *config = g_application.m_configure;

    // Check new dictionary
    vector<struct DictNode>& nodeVec = config->m_dictNodes;
    for (int i=0; i<nodeVec.size(); i++) {
        if (nodeVec[i].open == "") {
            nodeVec[i].open = "none";
            iDict *dict;
            if ((dict = createHandleByDict(nodeVec[i].path)) != NULL) {
                nodeVec[i].open = dict->identifier();
                dict->getLanguage(nodeVec[i].srclan, nodeVec[i].detlan);
				dict->summary(nodeVec[i].summary);
            }
            config->writeDictItem(i);
        }
    }
    TaskManager::getInstance()->addTask(new LoadDictTask(), 0);
}
Example #10
0
int Access::listen()
{
    int iRet = 0;

    if(listenSock_.getFd() < 0)
        return -1;

    if(status == START)
        return 0;

    listenSock_.setReUse();
    listenSock_.setBlock(0);

    Configure* conf = Server::getInstance()->getConf();

    iRet = listenSock_.bind(conf->getValue("address"),
                            toint<string>(conf->getValue("port")));
    assert(iRet == 0);
    
    listenSock_.listen(10240);
    return 0;
}
Example #11
0
void test03() {
    config.load();
    CThostFtdcInstrumentField pInstrument;
    CThostFtdcRspInfoField pRspInfo;
    int nRequestID;
    bool bIsLast;
    CTraderHandler traderHandler = CTraderHandler(&config);
    while(1) {
        traderHandler.OnRspQryInstrument(&pInstrument,&pRspInfo,nRequestID,bIsLast);
        //traderHandler.OnRspQryInstrument(0,&pRspInfo,nRequestID,bIsLast);
        std::cout << "message send ..." << std::endl;
        getchar();
    }
}
Example #12
0
  ProxyServoListener()
  {
    subscribers.push_back(cfg.str("servos.subscribe"));
    publish=cfg.str("proxyservos.publish");

    std::set < std::string > names = cfg.servoNames();
    for (std::set < std::string > :: iterator i = names.begin(); i != names.end(); ++i) {
      int id = atoi(cfg.servo(*i,"id").c_str());
      ZMQProxyServo &servo=servos[id];
      servo.id(id);
      servo.tempRate(cfg.num("proxyservos.temprate"));
      servo.angleRate(cfg.num("proxyservos.anglerate"));
    }
    start();
  }
Example #13
0
TEST(ConfigureTest, addItem)
{
	// do some initialization
	Configure* pc = new Configure();
	
	// validate the pointer is not null
	ASSERT_TRUE(pc != NULL);

	// call the method we want to test
	pc->addItem("A");
	pc->addItem("B");
	pc->addItem("A");

	// validate the result after operation
	EXPECT_EQ(pc->getSize(), 2);
	EXPECT_STREQ(pc->getItem(0).c_str(), "A");
	EXPECT_STREQ(pc->getItem(1).c_str(), "B");
	EXPECT_STREQ(pc->getItem(10).c_str(), "");

	delete pc;
}
Example #14
0
int main(int argc, char *argv[])
{
  cfg.path("../../setup");
  cfg.args("proxyservos.",argv);
  if (argc == 1) cfg.load("config.csv");
  cfg.servos();
  verbose = cfg.flag("proxyservos.verbose",false);
  if (verbose) cfg.show();


  server = ProxyServoListenerSP(new ProxyServoListener());

  signal(SIGINT, quit);
  signal(SIGTERM, quit);
  signal(SIGQUIT, quit);

  while (server) {
    usleep(int(0.25*1e6));
  }

  std::cout << "done" << std::endl;
  return 0;
}
Example #15
0
//
// main loop
//
int main(void) {

#ifdef DEBUG
	#if __USE_USB
		usbCDC ser;
		ser.connect();
	#else
		CSerial ser;
		ser.settings(115200);
	#endif
	CDebug dbg(ser);
	dbg.start();
#endif

	/*************************************************************************
	 *
	 *                         your setup code here
	 *
	 **************************************************************************/
#ifndef DEBUG
	//
	// Configure
	//
	Configure cfg;	// load configure data from EEPROM

	//
	// BLE Engine (Serial Stream)
	//
	myBLE ble(cfg.m_ble.name);
	ble.advertising(cfg.m_ble.advInterval,
					cfg.m_ble.txPowerLevel,
					cfg.m_ble.conInterval,
					cfg.m_ble.mfgCode);

	ble.enable();		// start the ble engine first!!
	ble.setRadioTxPower(cfg.m_ble.power);
	ble.watchdog(10000);	// set watchdog timeout 10 seconds

#else
	//
	// BLE Engine (Serial Stream)
	//
	myBLE ble;
	ble.advertising(100, -59);	// set adv. interval = 100ms, calibrater tx power = -59dBm
	ble.enable();
#endif

	//
	// Device Information Service
	//
	bleDeviceInfo info(ble);
	info.setManufactureName(u8"英倍達國際");	// u8 mean to use the UTF-8 string
	info.setModelNumber("nano11U37");
	info.setSerialNumber("140226000");
	info.setFirmwareRevision(uCXpresso_VER_STR);
	info.setHardwareRevision("R1");
	info.setPnP(VS_USB, 1, 2, 0x3456);		// vendor Id=1, product Id = 2,  product ver. = 0x3456

	SYS_ID_T sysId = {
		{0x00, 0x01, 0x02, 0x03, 0x04}, 	// Manufacturer Identifier
		{0x05, 0x06, 0x07}					// Organizationally Unique Identifier
	};
	info.setSystemId(sysId);

	//
	// Proximity Service
	//
//	myProximity alert(ble);	// declare Proximity Service (Immediate alert + Lose Link)

	//
	// Battery Level Service
	//
	bleBatteryLevel bl(ble);	// declare Battery Level Service object

	//
	// Health Thermometer Service
	//
	bleHealthThermometer ht(ble);	// declare Health Thermometer Service object
	ht.measurementInterval(1);			// set measurement interval = 1 second

	//
	// Arduino Firmata
	//
	myFirmata.begin(ble);				// begin the Firmata Object with the ble serial stream.
	callback_init();					// initialize the callback functions for myFirmata Object.

	//
	// A key input for Alert (for Proximity)
	//
	CPin keyAlert(P8);					// define P8 as a push button
	keyAlert.input();
//	PIN_LEVEL_T	pinVal = keyAlert;

	//
	// Timeout for time interval
	//
	CTimeout t1, t2, t3;				// t1=analog input check, t2=temperature check, t3=battery check

#ifndef DEBUG
	//
	// Power Save Feature
	//
	myPowerSave ps;						// use power Save feature

	cfg.start();						// start configure task (via usbCDC)
#endif

	float 	value;
	uint8_t level;

	while(1) {
		/**********************************************************************
		 *
		 *                         your loop code here
		 *
		 **********************************************************************/
		if ( ble.isConnected() ) {
#ifndef DEBUG
			ps.disable();		// disable power save features  when ble connected
#endif
			//
			// UART Service
			//
			if ( ble.isAvailable() ) {

				//
				// BLE Firmata Demo
				//
				if ( myFirmata.available() ) {
					do {
						myFirmata.processInput();
					} while(myFirmata.available());
				} else {
					//
					// check the Digital Input
					//
					checkDigitalInputs();

					//
					// check the Analog Input with a sampling Interval
					//
					if (t1.isExpired(samplingInterval) ) {
						t1.reset();
						checkAnalogInputs();
					}
				}
			}

			//
			// Proximity Service
			//
#if 0
			if ( alert.isAvailable() ) {
					//
					// push button check (Proximity Service)
					//
					if ( keyAlert != pinVal ) {
						pinVal = keyAlert;	// keep last status of key
						alert.sendEvent(keyAlert.read()==LOW ? 1 : 0);
					}
			}
#endif
			//
			// Health Thermometer Service
			//
			if ( ht.isAvailable() ) {
				//
				// check temperature
				//
				if ( t2.isExpired(1000) ) {
					t2.reset();
					if ( ht.readTemperature(value) ) {
						ht.sendMeasure(value);
						DBG("temp=%0.2f\n", value);
					} // */
				}
			}

			//
			// Battery Service
			//
			if ( bl.isAvailable() ) {
				//
				// update Battery Level
				//
				if ( t3.isExpired(3000) ) {
					t3.reset();
					if ( bl.readSystemVoltage(value) ) {
						if ( value>=2.4 && value<=3.6 ) {
							level =  map(value, 2.0, 3.3, 0, 100);
							bl.sendBatteryLevel(level);
							DBG("battery:%0.2fv %d%c\n", value, level, '%');
						}
					}
				}
			}

		}	// isConnected
		else {
#ifndef DEBUG
			if ( usbCDC::isVBUS() ) {
				ledACT = LED_ON;
				ps.disable();			// disable power save features when USB connected
			} else {
				ps.enable(POWER_DOWN);	// enable power save features when 3.3V only
			}
			ble.wait();				// block and wait a BLE event
#else
			ledACT = LED_ON;
#endif
		}
	}
    return 0 ;
}
Example #16
0
 void configure(Configure& c) {
   c("random-seed", &seed)("if set, use as initial seed for RNG");
   c.is("random_seed");
 }
Example #17
0
void calibrateProcess(Configure& conf, cv::Mat& cameraMatrix, cv::Mat& distCoeffs)
{
    const cv::Size frameSize(conf.getConfInt("universal.frameWidth"),
                             conf.getConfInt("universal.frameHeight"));
    const cv::string dataPath(conf.getConfString("universal.dataPath"));
    
    const std::string checkerPrefix
        (conf.getConfString("calibration.checkerPrefix"));
    const std::string checkerSuffix
        (conf.getConfString("calibration.checkerSuffix"));
    const int checkerNum = conf.getConfInt("calibration.checkerNum");
    const cv::Size checkerSize(conf.getConfInt("calibration.checkerWidth"),
                               conf.getConfInt("calibration.checkerHeight"));
    
    cv::vector<cv::Mat> checkerImgs;
    cv::vector<cv::vector<cv::Point3f>> worldPoints(checkerNum);
    cv::vector<cv::vector<cv::Point2f>> imagePoints(checkerNum);
    
    cv::TermCriteria criteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 20, 0.001);
    
    cv::vector<cv::Mat> rotationVectors;
    cv::vector<cv::Mat> translationVectors;
    
    for(int i=0; i<checkerNum; i++){
        std::stringstream stream;
        stream << checkerPrefix << i+1 << checkerSuffix;
        std::string fileName = stream.str();
        cv::Mat tmp = cv::imread(dataPath + fileName, 0);
        cv::resize(tmp, tmp, frameSize);
        checkerImgs.push_back(tmp);
        std::cout << "load checker image: " << fileName << std::endl;
    }
    
    cv::namedWindow("Source", CV_WINDOW_AUTOSIZE|CV_WINDOW_FREERATIO);
    for(int i=0; i<checkerNum; i++){
        std::cout << "find corners from image " << i+1;
        if(cv::findChessboardCorners(checkerImgs[i], checkerSize,
                                     imagePoints[i])){
            std::cout << " ... all corners found." << std::endl;
            cv::cornerSubPix(checkerImgs[i], imagePoints[i], cv::Size(5, 5),
                             cv::Size(-1, -1), criteria);
            cv::drawChessboardCorners(checkerImgs[i], checkerSize,
                                      (cv::Mat)(imagePoints[i]), true);
            cv::imshow("Source", checkerImgs[i]);
            cv::waitKey(200);
        }else{
            std::cout << " ... at least 1 corner not found." << std::endl;
            cv::waitKey(0);
            exit(-1);
        }
    }
    cv::destroyWindow("Source");
    
    for(int i=0; i<checkerNum; i++){
        for(int j=0; j<checkerSize.area(); j++){
            worldPoints[i].
                push_back(cv::Point3f(static_cast<float>(j%checkerSize.width*10),
                                      static_cast<float>(j/checkerSize.width*10),
                                      0.0));
        }
    }
    
    cv::calibrateCamera(worldPoints, imagePoints, frameSize, cameraMatrix,
                        distCoeffs, rotationVectors, translationVectors);
    
    std::cout << "camera matrix" << std::endl;
    std::cout << cameraMatrix << std::endl;
    std::cout << "dist coeffs" << std::endl;
    std::cout << distCoeffs << std::endl;
    
}
Example #18
0
int main(int argc, char** argv)
{
  pid_t leapd_pid;

  if ((leapd_pid=fork()) == 0) {
    execl("/usr/bin/leapd","leapd",0);
  }

  cfg.path("../../setup");
  cfg.args("leap.provider.", argv);
  if (argc == 1) cfg.load("config.csv");
  verbose = cfg.flag("leap.provider.verbose", false);
  if (verbose) cfg.show();
  
  decay_time = cfg.num("leap.provider.decay_time");
  
  int hwm = 1;
  int retries = 5;
  int linger = 25;
  int rc = 0;
  bool connected = false;
  
  MyListener listener;
  Controller controller(listener);	
  
  zmq_context = zmq_ctx_new ();
  zmq_pub = zmq_socket(zmq_context,ZMQ_PUB);

  while(!connected && retries--) {
	  if(zmq_setsockopt(zmq_pub, ZMQ_SNDHWM, &hwm, sizeof(hwm)) == 0) {
	  	if(zmq_setsockopt(zmq_pub, ZMQ_LINGER, &linger, sizeof(linger)) == 0) {
	  		if(zmq_bind(zmq_pub, cfg.str("leap.provider.publish").c_str()) == 0) {
				connected = true;
			}

		}		
	  }
	  if (retries <= 0) {
	    int en=zmq_errno();
	    std::cout << "TCP Error Number " << en << " " << zmq_strerror(en) << std::endl;
	    die = true;
	  }
	  std::this_thread::sleep_for(std::chrono::milliseconds(200));
  }
  signal(SIGINT, quitproc);
  signal(SIGTERM, quitproc);
  signal(SIGQUIT, quitproc);

  while(!die) {
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
  }

  controller.removeListener(listener);
  zmq_close(zmq_pub);
  zmq_ctx_destroy(zmq_context);

  kill(leapd_pid,SIGINT);
  waitpid(leapd_pid,0,0);

  std::cout << "--done!" << std::endl;

  return 0;
}