void AVRProgrammer::startupTargetMcuProgramming(byte& statusRes) {
  initStatus();
  if (targetMcuProgMode) {
    logError("MCU In PMODE!");
    returnStatus(ERR(0x17));
  }
  
  digitalWrite(pinVccEnable, HIGH);
  digitalWrite(pinAVccEnable, HIGH);
  
  // special case (when we cannot operate with Vcc and Avcc pins of target mcu)
  digitalWrite(pinReset, HIGH);
  delay(3);
  digitalWrite(pinReset, LOW);
  
  delay(30); // minimum 20ms is required by spec
  
  byte byte1 = sendReadByte(0xAC);
  byte byte2 = sendReadByte(0x53);
  byte byte3 = sendReadByte(0x00);
  byte byte4 = sendReadByte(0x00);

  targetMcuProgMode = true;
  targetMcuOutOfSync = (byte3 != 0x53 || byte4 != 0x00);
  if (targetMcuOutOfSync) {
    returnStatus(ERR(0x11));
  }
}
Exemple #2
0
bool HomeScene::init()
{
    if ( !MainScene::init("home/HomeScene.csb") )
    {
        return false;
    }
    
    _home_bg = _scene->getChildByName<Sprite*>("home_bg");
    
    if(!initUI() || !initStatus()){
        return false;
    }
    
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = CC_CALLBACK_2(HomeScene::onTouchBegin,this);
    listener->onTouchMoved = CC_CALLBACK_2(HomeScene::onTouchMoved,this);
    listener->onTouchEnded = CC_CALLBACK_2(HomeScene::onTouchEnded,this);
    listener->onTouchCancelled = CC_CALLBACK_2(HomeScene::onTouchCancelled,this);
    
    listener->setSwallowTouches(true);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
    
    schedule(schedule_selector(HomeScene::update),1.0f);
    
    _db = dbIO::getInstance();
    return true;
}
Exemple #3
0
/* Inicio de rutina para inicializar el entorno de accion */
void main(void){
	struct get_process_status_type g_p_s;
	RETURN_CODE_TYPE retCode;
	PROCESS_ID_TYPE procMainIdMT;
	PROCESS_ID_TYPE procMainId1;
	char sal_code[MAX_CAD];
	PROCESS_STATUS_TYPE status;

	CREATE_PROCESS (&processTable[0],  /* process attribute */
                    &procMainIdMT,    /* process Id */
                    &retCode);

	CHECK_CODE(": CREATE_PROCESS Process Master Test", retCode, sal_code);
    printf("%s\n", sal_code);

    CREATE_PROCESS (&processTable[1],  /* process attribute */
                    &procMainId1,    /* process Id */
                    &retCode);
    CHECK_CODE(": CREATE_PROCESS Process 1", retCode, sal_code);
    printf("%s\n", sal_code);

    /* To get the init values of Process 1*/
    status = initStatus();

	/* check process 1 status */
	g_p_s = checkget_process_status(status, procMainId1, NO_ERROR);

	show_resultget_p(g_p_s);

	SET_PARTITION_MODE(NORMAL, &retCode);
	CHECK_CODE(": SET_PARTITION_MODE", retCode, sal_code);
	printf("%s\n", sal_code);
}
byte AVRProgrammer::issueByteReadCmd4(byte b1, byte b2, byte b3, byte b4, byte& statusRes) {
  initStatus();
  if (!targetMcuProgMode) {
    logError("MCU !ProgMode");
    returnStatusV(ERR(0x13), 0);
  }
  if (targetMcuOutOfSync) {
    logError("MCU OutOfSync!");
    returnStatusV(ERR(0x14), 0);
  }
  
  // Send Byte #1
  sendReadByte(b1);
  
  // Send Byte #2 and check result with Byte #1
  if (sendReadByte(b2) != b1) {
    targetMcuOutOfSync = true;
    logErrorB(("OutOfSync b2:"),b1);// Out of sync on 2nd byte
    returnStatusV(ERR(0x15), 0);
  }

  // Send Byte #3 and check result with Byte #2
  if (sendReadByte(b3) != b2) {
    targetMcuOutOfSync = true;
    logErrorB(("OutOfSync b3:"),b2);// Out of sync on 3rd byte
    returnStatusV(ERR(0x16), 0);
  }

  // Send Byte #4 and return result
  return sendReadByte(b4);
}
void ProgramFile::findAndOpenNextFileBackupFile(String filePref, byte& statusRes) {
  initStatus();
  // Create file
  if (filePref.length() > 4) {
    logDebug("Wrong file pref used");
    returnStatus(ERR(0x50)); // system error, wrong filePref used
  }
  //char buf[13];
  String fileName;
  boolean isF = false;
  int minAvNo = 10000;
  for (int n = 300; n > 0; n--) {//maximum 300 files allowed, for faster search (possible up to 9999)
    fileName = String(filePref + String(n / 1000) + String(n / 100 % 10) + String(n / 10 % 10) + String(n % 10) + ".BKP");
    logDebugS("checking:", fileName);
    backupFile = SD.open(fileName, FILE_READ);
    if (backupFile) {
      logDebugD("found",n);
      break;
    }
    minAvNo = n;
  }
  if (minAvNo == 10000) {
    returnStatus(ERR(0x53)); // not enough space for backup files
  }
  
  fileName = String(filePref + String(minAvNo / 1000) + String(minAvNo / 100 % 10) + String(minAvNo / 10 % 10) + String(minAvNo % 10) + ".BKP");
  logDebugS("Next free file:", fileName);
  backupFile = SD.open(fileName, FILE_WRITE);
  if (!backupFile) {
    logDebug("!writeFile");
    returnStatus(ERR(0x52)); // cannot open backup file for write
  }
}
Exemple #6
0
void DatabaseManager::updateLastAppStartTimestamp(const Pet& pet) {
    initStatus(pet.getId());
    qDebug() << "DatabaseManager: update LAST_APP_START timestamp";
    QSqlQuery query;
    query.prepare("UPDATE Status SET LAST_APP_START=CURRENT_TIMESTAMP WHERE PET_ID=?");
    query.addBindValue(pet.getId());
    query.exec();
}
Exemple #7
0
Game::Game(PlayerData *_playerData, Game **_allGame):
    playerData(_playerData),
    allGame(_allGame),
    show(new Show(_playerData))
{
    initTimer();
    initCounter();
    initStatus();
    gameStatus = PREPARE;
}
Exemple #8
0
// Update Protocol reply recieved
void updateReplyRecieved()
{
  // Check if INIT Success
  // Release the RX buffer inside
  if (txState == INIT){
    initStatus();
  }
  else if (txState == START){
    startStatus();
  }
  else
    bmac_rx_pkt_release ();
}
SpyFrame::SpyFrame(dwt::TabView* mdiParent) :
	BaseType(mdiParent, T_("Search Spy"), IDH_SEARCH_SPY, IDR_SPY),
	searches(0),
	ignoreTTH(0),
	bIgnoreTTH(BOOLSETTING(SPY_FRAME_IGNORE_TTH_SEARCHES)),
	total(0),
	cur(0)
{
	memset(perSecond, 0, sizeof(perSecond));

	{
		Table::Seed cs = WinUtil::Seeds::Table;
		cs.style |= LVS_SINGLESEL;
		searches = addChild(cs);
		addWidget(searches);

		searches->createColumns(WinUtil::getStrings(columnNames));
		searches->setColumnOrder(WinUtil::splitTokens(SETTING(SPYFRAME_ORDER), columnIndexes));
		searches->setColumnWidths(WinUtil::splitTokens(SETTING(SPYFRAME_WIDTHS), columnSizes));
		searches->setSort(COLUMN_COUNT, dwt::Table::SORT_INT, false);
		searches->onColumnClick(std::tr1::bind(&SpyFrame::handleColumnClick, this, _1));
		searches->onContextMenu(std::tr1::bind(&SpyFrame::handleContextMenu, this, _1));
	}

	{
		CheckBox::Seed cs(T_("Ignore TTH searches"));
		ignoreTTH = addChild(cs);
		ignoreTTH->setHelpId(IDH_SPY_IGNORE_TTH);
		ignoreTTH->setChecked(bIgnoreTTH);
		ignoreTTH->onClicked(std::tr1::bind(&SpyFrame::handleIgnoreTTHClicked, this));
	}

	initStatus();
	statusSizes[STATUS_IGNORE_TTH] = 150; ///@todo get real checkbox + text width

	setStatusHelpId(STATUS_TOTAL, IDH_SPY_TOTAL);
	setStatusHelpId(STATUS_AVG_PER_SECOND, IDH_SPY_AVG_PER_SECOND);
	setStatusHelpId(STATUS_HITS, IDH_SPY_HITS);
	setStatusHelpId(STATUS_HIT_RATIO, IDH_SPY_HIT_RATIO);

	layout();

	onSpeaker(std::tr1::bind(&SpyFrame::handleSpeaker, this, _1, _2)) ;

	ShareManager::getInstance()->setHits(0);

	ClientManager::getInstance()->addListener(this);

	initSecond();
}
// returns false if there are no more characters to read, true otherwise
// This method: skips all white spaces and comments, positions on the first valid character to read
// NOTE: this method expects to be on the beginning of file, or on the beginning of new line
boolean ConfFile::skipToValidData(byte& statusRes) {
  initStatus();
  boolean av = true;
  while (_confFile.available()) {
    av = skipWhiteCharacters(statusRes); checkStatusV(false);
    if (!av) return false;
    
    char c = _confFile.peek();
    if (c != '#') {
      return true;
    } else {
      skipLine(statusRes); checkStatusV(false);
    }
  }
  return false;
}
void HEXFile::openFile(File& f, String fileName, int mode, byte& statusRes) {
  initStatus();
  f = SD.open(fileName, FILE_READ);
  if (mode == FILE_WRITE) {
    if (!f) {
      logDebugS("File exists! override protection!:", fileName);
      returnStatus(ERR(0x90));//system error, calling program must check if file exists
    }
    f = SD.open(fileName, FILE_WRITE);
  }
  if (!f) {
    logDebugS("!open:",fileName);
    returnStatus(ERR(0x91)); //Cannot open ProgramFile
  } else {
    logInfoS("Opened file:", fileName);
  }
}
// soundsource overrides
Result SoundSourceFLAC::open() {
    if (!m_file.open(QIODevice::ReadOnly)) {
        qWarning() << "SSFLAC: Could not read file!";
        return ERR;
    }

    m_decoder = FLAC__stream_decoder_new();
    if (m_decoder == NULL) {
        qWarning() << "SSFLAC: decoder allocation failed!";
        return ERR;
    }
    FLAC__StreamDecoderInitStatus initStatus(
        FLAC__stream_decoder_init_stream(
            m_decoder, FLAC_read_cb, FLAC_seek_cb, FLAC_tell_cb, FLAC_length_cb,
            FLAC_eof_cb, FLAC_write_cb, FLAC_metadata_cb, FLAC_error_cb,
            (void*) this)
    );
    if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
        qWarning() << "SSFLAC: decoder init failed!";
        goto decoderError;
    }
    if (!FLAC__stream_decoder_process_until_end_of_metadata(m_decoder)) {
        qWarning() << "SSFLAC: process to end of meta failed!";
        qWarning() << "SSFLAC: decoder state: " << FLAC__stream_decoder_get_state(m_decoder);
        goto decoderError;
    } // now number of samples etc. should be populated
    if (m_flacBuffer == NULL) {
        // we want 2 samples per frame, see ::flacWrite code -- bkgood
        m_flacBuffer = new FLAC__int16[m_maxBlocksize * 2 /*m_iChannels*/];
    }
    if (m_leftoverBuffer == NULL) {
        m_leftoverBuffer = new FLAC__int16[m_maxBlocksize * 2 /*m_iChannels*/];
    }
//    qDebug() << "SSFLAC: Total samples: " << m_samples;
//    qDebug() << "SSFLAC: Sampling rate: " << m_iSampleRate << " Hz";
//    qDebug() << "SSFLAC: Channels: " << m_iChannels;
//    qDebug() << "SSFLAC: BPS: " << m_bps;
    return OK;
decoderError:
    FLAC__stream_decoder_finish(m_decoder);
    FLAC__stream_decoder_delete(m_decoder);
    m_decoder = NULL;

    qWarning() << "SSFLAC: Decoder error at file" << m_qFilename;
    return ERR;
}
// returns false if there are no more characters to read, true otherwise
void ConfFile::skipLine(byte& statusRes) {// skips to the next line, positions on first character of next line
  initStatus();
  while (_confFile.available()) {
    byte c = _confFile.read();
    if (c == 0x0A) {
      return;
    }
    if (c == 0x0D) {
      if (_confFile.available()) c = _confFile.read();
      if (c != 0x0A) {
        logDebug("skipLine,eol wrong");
        returnStatus(ERR(0x21)); // corrupted file, eol is wrong
      }
      return;
    }
  }
}
// returns false if there are no more characters to read, true otherwise
void ConfFile::skipWhiteCharactersExpectNoEolNoEof(byte& statusRes) {// skip all white characters (except EOL), positions on the first non-white character. Expect no EOL or EOF!
  initStatus();
  int skippedChars = 0;
  while (_confFile.available()) {
    char c = _confFile.peek();
    if (c == 0x0A || c == 0x0D) {
      logDebug("unexpected EOL");
      returnStatus(ERR(0x22)); // unexpected EOL
    } else {
      if (!isWhiteChar(c)) {
        return;
      }
    }
    _confFile.read(); skippedChars++;
  }
  logDebug("unexpected EOF");
  returnStatus(ERR(0x22));//unexpected EOF
}
Exemple #15
0
void Game::prepareHandleEvent(const SDL_Event &event)
{
    if (event.type == SDL_KEYDOWN){
	SDLKey sym = event.key.keysym.sym;
	if (sym == playerData->moveLeft ||
	    sym == playerData->moveRight ||
	    sym == playerData->rotateLeft ||
	    sym == playerData->rotateRight ||
	    sym == playerData->hardDrop ||
	    sym == playerData->hold){
	    
	    initStatus();
	    show->mapShow(mapData);
	    show->messageShow("Ready !!!");
	    gameStatus = READY;
	}
    }    
}
Exemple #16
0
Static void doMusic(void)
{
  Char STR1[256], STR2[256];
  Char STR4[256];

  first_paragraph = true;
  pmx_preamble_done = false;
  bar_no = 1;
  *repeat_sign = '\0';
  must_respace = false;
  must_restyle = false;
  do {
    final_paragraph = endOfInfile();
    memcpy(orig_P, P, sizeof(paragraph));
    if (para_len > 0 && !ignore_input && thisCase()) {
      if (no_commands_yet) {
	interpretCommands();
	printFeatures(false);
	one_beat = 64 / meterdenom;
	full_bar = meternum * one_beat;
	if (nvoices > standardPMXvoices) {
	  sprintf(STR4, "You have %s voices; standard PMX can only handle %s",
		  toString(STR1, nvoices), toString(STR2, standardPMXvoices));
	  warning(STR4, !print);
	}
	initMTX();
	initUptext();
	initStatus();
	initLyrics();
	no_commands_yet = false;
      }
      if (startsWithBracedWord(P[0]))
	lyricsParagraph();
      else {
	musicParagraph();
	first_paragraph = false;
	writeRepeat(repeat_sign);
      }
    }
    readParagraph(P, orig_line_no, &para_len);
  } while (para_len != 0);
}
TextFrame::TextFrame(dwt::TabView* mdiParent, const string& fileName) : 
	BaseType(mdiParent, Text::toT(Util::getFileName(fileName))),
	pad(0) 
{
	TextBox::Seed cs = WinUtil::Seeds::textBox;
	cs.style |= WS_VSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_NOHIDESEL | ES_READONLY;
	cs.font = WinUtil::monoFont;
	pad = addChild(cs);
	addWidget(pad);

	pad->setTextLimit(0);
	
	try {
		pad->setText(Text::toT(Text::toDOS(File(fileName, File::READ, File::OPEN).read(MAX_TEXT_LEN))));
	} catch(const FileException& e) {
		pad->setText(Text::toT(e.getError()));
	}
	initStatus();
	layout();
}
// returns false if there are no more characters to read, true otherwise
boolean ConfFile::skipWhiteCharacters(byte& statusRes) {// skip all white characters (including EOL), positions on the first non-white character
  initStatus();
  int skippedChars = 0;
  while (_confFile.available()) {
    char c = _confFile.peek();
    if (c == 0x0A) {
      // Linux EOL, also a white char, so skip it
    } else if (c == 0x0D) {
      // Windows EOL, two chars
      _confFile.read(); skippedChars++;
      if (!_confFile.available() || _confFile.peek() != 0x0A) {
        logDebug("skipWhiteChars:no 0A after 0D");
        returnStatusV(ERR(0x21),false);// no 0A after 0D
      }
    } else {
      if (!isWhiteChar(c)) {
        return true;
      }
    }
    _confFile.read(); skippedChars++;
  }
  return false;
}
UsersFrame::UsersFrame(dwt::TabView* mdiParent) : 
	BaseType(mdiParent, T_("Favorite Users"), IDH_FAVUSERS, IDR_USERS),
	users(0),
	startup(true)
{
	{
		WidgetUsers::Seed cs;
		cs.lvStyle |= LVS_EX_CHECKBOXES;
		users = addChild(cs);
		addWidget(users);

		users->createColumns(WinUtil::getStrings(columnNames));
		users->setColumnOrder(WinUtil::splitTokens(SETTING(HUBFRAME_ORDER), columnIndexes));
		users->setColumnWidths(WinUtil::splitTokens(SETTING(HUBFRAME_WIDTHS), columnSizes));
		users->setSort(COLUMN_NICK);

		users->onDblClicked(std::tr1::bind(&UsersFrame::handleGetList, this));
		users->onKeyDown(std::tr1::bind(&UsersFrame::handleKeyDown, this, _1));
		users->onRaw(std::tr1::bind(&UsersFrame::handleItemChanged, this, _2), dwt::Message(WM_NOTIFY, LVN_ITEMCHANGED));
		users->onContextMenu(std::tr1::bind(&UsersFrame::handleContextMenu, this, _1));
	}

	FavoriteManager::FavoriteMap ul = FavoriteManager::getInstance()->getFavoriteUsers();
	HoldRedraw hold(users);
	for(FavoriteManager::FavoriteMap::iterator i = ul.begin(); i != ul.end(); ++i) {
		addUser(i->second);
	}
	FavoriteManager::getInstance()->addListener(this);

	initStatus();

	layout();

	startup = false;

	onSpeaker(std::tr1::bind(&UsersFrame::handleSpeaker, this, _1, _2));
}
void RecordWorkThread::run()
{
    recorderFlag = false;
    anares.clear();
    CurrentStaus cstatus;


    workbook *wb = new workbook();
    xf_t* xf = wb->xformat();
    worksheet* ws;
    ws = wb->sheet("sheet1");
    setTitle(ws,xf);
    int cnt = 1;
    int sheetNUM = 1;
    overflow = false;
    bool first = true;

    Util::SysLogD("charge type : %d %f %f %f\n ",charge_type,power_charge_normal,power_charge_peak,power_charge_valley);
    Util::SysLogD("normal : %d %d %d %d %d %d\n ",normal_period[0],normal_period[1],normal_period[2],normal_period[3],normal_period[4],normal_period[5]);
    Util::SysLogD("peak : %d %d %d %d %d %d\n ",peak_period[0],peak_period[1],peak_period[2],peak_period[3],peak_period[4],peak_period[5]);
    Util::SysLogD("valley : %d %d %d %d %d %d\n ",valley_period[0],valley_period[1],valley_period[2],valley_period[3],valley_period[4],valley_period[5]);
    while(!recorderFlag)
    {
        if(overflow)
        {
            usleep(300000);
        }
        usleep(300000);
        EnergyParam param = dataWoker->getEnergyParam();
        if(first)
        {
            anares.start_measure_time = param.time;
            first = false;
            mutex.lock();
            initStatus(&cstatus,&param);
            anares.vsp_cnt = cstatus.acc_vsp_cnt;
            mutex.unlock();
            writeParam(ws,xf,param,cnt);

        }
        if(cstatus.lastTime < param.time)
        {
            cnt++;
            mutex.lock();
            updateResult(&cstatus,&param);
            anares.vsp_cnt = cstatus.acc_vsp_cnt;
            mutex.unlock();
            writeParam(ws,xf,param,cnt);
        }

        acc_flow = anares.acc_flow;
        acc_power = anares.acc_power;
        load_radio = ((float)anares.load_time/(float)(anares.load_time + anares.unload_time))*100.0;
        if(cnt>SHEET_MAX_LINE)
        {
            if(sheetNUM < SHEET_MAX_INDEX)
            {
                char temp[10];
                sprintf(temp,"sheet%d",sheetNUM+1);
                ws = wb->sheet(temp);
                setTitle(ws,xf);
                sheetNUM++;
            }else {
                emit recordoverflow(1);
                overflow = true;
            }
            cnt = 0;
        }

    }

    if(cstatus.state == STAGE_LOAD )
    {
//        anares.load_cnt++;
//        anares.load_time += cstatus.duration;
        if(anares.max_load_time < cstatus.duration)
        {
            anares.max_load_time = cstatus.duration;
        }
    }else if(cstatus.state == STAGE_UNLOAD )
    {
//        anares.unload_cnt++;
//        anares.unload_time += cstatus.duration;
        if(anares.max_unload_time < cstatus.duration)
        {
            anares.max_unload_time = cstatus.duration;
        }
    }
    if(cstatus.acc_vsp_cnt>0)
        anares.ave_vsp = anares.ave_vsp/(float)cstatus.acc_vsp_cnt;
    anares.end_measure_time = cstatus.lastTime;

    anares.worktime = anares.load_time + anares.unload_time;
    anares.stanby_time = anares.end_measure_time - anares.start_measure_time - anares.worktime;

    Util::SysLogD("start and end time  : %d %d\n",anares.start_measure_time,anares.end_measure_time);
    Util::SysLogD("load and unload time  : %d %d\n",anares.load_time,anares.unload_time);
    Util::SysLogD("acc_flow : %f\n",anares.acc_flow);
    Util::SysLogD("cur : %d %d\n",max_cur_standby,max_cur_unload);
    Util::SysLogD("max time : %d %d\n",anares.max_load_time,anares.max_unload_time);
    Util::SysLogD("max time : %d %d\n",anares.max_load_time,anares.max_unload_time);
    Util::SysLogD("vas : %f %d\n",anares.ave_vsp,cstatus.acc_vsp_cnt);

    if(anares.worktime != 0)
    {
        anares.load_radio = ((float)anares.load_time)/(float)anares.worktime*100.0;
        anares.unload_radio = ((float)anares.unload_time)/(float)anares.worktime*100.0;
    }

    anares.acc_flow = anares.acc_flow/60;//m3/min
    anares.acc_power = anares.acc_power/3600;//kwh
    anares.load_power /= 3600;
    anares.unload_power /= 3600;

    if(charge_type == 1)
    {
        anares.acc_charge_normal =  anares.acc_charge_normal*power_charge_normal/3600;
        anares.acc_charge_peak =  anares.acc_charge_peak*power_charge_peak/3600;
        anares.acc_charge_valley =  anares.acc_charge_valley*power_charge_valley/3600;
        anares.acc_charge = anares.acc_charge_normal+anares.acc_charge_peak+anares.acc_charge_valley;
        anares.load_charge /= 3600;
        anares.unload_chargd /= 3600;

    }else if(charge_type == 0)
    {
        anares.acc_charge = anares.acc_power*power_charge;
        anares.load_charge = anares.load_power*power_charge;
        anares.unload_chargd = anares.unload_power*power_charge;
    }

    anares.permanent_magnet_frequency_conversion = anares.unload_power+anares.load_power*0.1;
    anares.first_order_energy_efficiency = -7.2*anares.acc_flow/60 + anares.acc_power;

    anares.permanent_magnet_frequency_conversion_day = anares.permanent_magnet_frequency_conversion * 12 / anares.worktime *3600;
    anares.permanent_magnet_frequency_conversion_month = anares.permanent_magnet_frequency_conversion * 30 * 12 / anares.worktime *3600;
    anares.permanent_magnet_frequency_conversion_year = anares.permanent_magnet_frequency_conversion * 365 * 30 * 12 / anares.worktime *3600;

    if(anares.first_order_energy_efficiency <0.00001)
    {
        anares.first_order_energy_efficiency = 0;
        anares.first_order_energy_efficiency_day = 0;
        anares.first_order_energy_efficiency_month = 0;
        anares.first_order_energy_efficiency_year = 0;
    }else
    {
        anares.first_order_energy_efficiency_day = anares.first_order_energy_efficiency * 12 / anares.worktime *3600;
        anares.first_order_energy_efficiency_month = anares.first_order_energy_efficiency * 30 * 12 / anares.worktime *3600;
        anares.first_order_energy_efficiency_year = anares.first_order_energy_efficiency * 365 * 30 * 12 / anares.worktime *3600;
    }

    anares.load_charge_radio = anares.load_charge/ anares.acc_charge *100.0;
    anares.unload_charge_radio = anares.unload_chargd/ anares.acc_charge *100.0;
    anares.ave_cost = anares.acc_charge / anares.acc_flow;
    anares.ave_power_cost = anares.acc_power / anares.acc_flow;

//    char temp[10];
//    sprintf(temp,"sheet%d",sheetNUM+1);
    ws = wb->sheet("分析结果");
    Util::writeResultWithFormat(ws,xf,anares);

    string path_post = title.toStdString();
    string path = path_pre + path_post; 
    wb->Dump(path);
    delete wb;
    Util::fileSync(path.c_str());
    Util::SysLogD("save file : %s\n",path.c_str());
    emit recordoverflow(2);
}
Exemple #21
0
CPoorZombie::CPoorZombie(void)
{
    initStatus();
}
Exemple #22
0
static int
WorkerBee(struct cmd_syndesc *as, void *arock)
{
    afs_int32 code, numClasses;
    struct rx_securityClass *(nullObjects[1]), **secObjs, **allObjs;
    struct rx_service *service;
    time_t tokenExpires;
    char cellName[64];
    int localauth;
    /*process arguments */
    afs_int32 portOffset = 0;
#ifdef AFS_PTHREAD_ENV
    pthread_t dbWatcherPid;
    pthread_attr_t tattr;
    AFS_SIGSET_DECL;
#else
    PROCESS dbWatcherPid;
#endif
    char hoststr[16];
    afs_uint32 host = htonl(INADDR_ANY);
    char *auditFileName = NULL;
    char *auditInterface = NULL;

    debugLevel = 0;

    /*initialize the error tables */
    initialize_KA_error_table();
    initialize_RXK_error_table();
    initialize_KTC_error_table();
    initialize_ACFG_error_table();
    initialize_CMD_error_table();
    initialize_VL_error_table();
    initialize_BUTM_error_table();
    initialize_BUTC_error_table();
#ifdef xbsa
    initialize_BUTX_error_table();
#endif /*xbs */
    initialize_VOLS_error_table();
    initialize_BUDB_error_table();
    initialize_BUCD_error_table();

    if (as->parms[0].items) {
	portOffset = SafeATOL(as->parms[0].items->data);
	if (portOffset == -1) {
	    fprintf(stderr, "Illegal port offset '%s'\n",
		    as->parms[0].items->data);
	    exit(1);
	} else if (portOffset > BC_MAXPORTOFFSET) {
	    fprintf(stderr, "%u exceeds max port offset %u\n", portOffset,
		    BC_MAXPORTOFFSET);
	    exit(1);
	}
    }

    xbsaType = XBSA_SERVER_TYPE_NONE;	/* default */
    if (as->parms[3].items) {	/* -device */
	globalTapeConfig.capacity = 0x7fffffff;	/* 2T for max tape capacity */
	globalTapeConfig.fileMarkSize = 0;
	globalTapeConfig.portOffset = portOffset;
	strncpy(globalTapeConfig.device, as->parms[3].items->data, 100);
	xbsaType = XBSA_SERVER_TYPE_NONE;	/* Not XBSA */
    } else {
	/* Search for an entry in tapeconfig file */
	code = GetDeviceConfig(tapeConfigFile, &globalTapeConfig, portOffset);
	if (code == -1) {
	    fprintf(stderr, "Problem in reading config file %s\n",
		    tapeConfigFile);
	    exit(1);
	}
	/* Set xbsaType. If code == 1, no entry was found in the tapeconfig file so
	 * it's an XBSA server. Don't know if its ADSM or not so its unknown.
	 */
	xbsaType =
	    ((code == 1) ? XBSA_SERVER_TYPE_UNKNOWN : XBSA_SERVER_TYPE_NONE);
    }

    if (as->parms[6].items) {	/* -restoretofile */
	restoretofile = strdup(as->parms[6].items->data);
	printf("Restore to file '%s'\n", restoretofile);
    }

    /* Go and read the config file: CFG_<device> or CFG_<port>. We will also set
     * the exact xbsaType within the call (won't be unknown) - double check.
     */
    code = GetConfigParams(pFile, portOffset);
    if (code)
	exit(code);
#ifdef xbsa
    if (xbsaType == XBSA_SERVER_TYPE_UNKNOWN) {
	printf
	    ("\nConfiguration file error, the TYPE parameter must be specified, or\n");
	printf("an entry must exist in %s for port %d\n", tapeConfigFile,
	       portOffset);
	exit(1);
    }
#else
    /* Not compiled for XBSA code so we can't support it */
    if (CONF_XBSA) {
	printf("\nNo entry found in %s for port %d\n", tapeConfigFile,
	       portOffset);
	printf("This binary does not have XBSA support\n");
	exit(1);
    }
#endif

    /* Open the log files. The pathnames were set in GetConfigParams() */
    logIO = fopen(logFile, "a");
    if (!logIO) {
	fprintf(stderr, "Failed to open %s\n", logFile);
	exit(1);
    }
    ErrorlogIO = fopen(ErrorlogFile, "a");
    if (!ErrorlogIO) {
	fprintf(stderr, "Failed to open %s\n", ErrorlogFile);
	exit(1);
    }
    if (lastLog) {
	lastLogIO = fopen(lastLogFile, "a");
	if (!lastLogIO) {
	    fprintf(stderr, "Failed to open %s\n", lastLogFile);
	    exit(1);
	}
    }
    if (centralLogFile) {
	struct stat sbuf;
	afs_int32 statcode;
#ifndef AFS_NT40_ENV
	char *path;
#endif

	statcode = stat(centralLogFile, &sbuf);
	centralLogIO = fopen(centralLogFile, "a");
	if (!centralLogIO) {
	    fprintf(stderr, "Failed to open %s; error %d\n", centralLogFile,
		    errno);
	    exit(1);
	}
#ifndef AFS_NT40_ENV
	/* Make sure it is not in AFS, has to have been created first */
	path = malloc(AFSDIR_PATH_MAX);
	if (path == NULL || !realpath(centralLogFile, path)) {
	    fprintf(stderr,
		    "Warning: can't determine real path of '%s' (%d)\n",
		    centralLogFile, errno);
	} else {
	    if (strncmp(path, "/afs/", 5) == 0) {
		fprintf(stderr, "The central log '%s' should not be in AFS\n",
			centralLogFile);
		exit(1);
	    }
	}
	free(path);
#endif

	/* Write header if created it */
	if (statcode) {
	    char *h1 =
		"TASK   START DATE/TIME      END DATE/TIME        ELAPSED   VOLUMESET\n";
	    char *h2 =
		"-----  -------------------  -------------------  --------  ---------\n";
	    /* File didn't exist before so write the header lines */
	    fwrite(h1, strlen(h1), 1, centralLogIO);
	    fwrite(h2, strlen(h2), 1, centralLogIO);
	    fflush(centralLogIO);
	}
    }

    /* Open the configuration directory */
    butc_confdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
    if (butc_confdir == NULL) {
	TLog(0, "Failed to open server configuration directory");
	exit(1);
    }

    /* Start auditing */
    osi_audit_init();
    if (as->parms[9].items) {
	auditFileName = as->parms[9].items->data;
    }
    if (auditFileName != NULL)
	osi_audit_file(auditFileName);
    if (as->parms[10].items) {
	auditInterface = as->parms[10].items->data;
	if (osi_audit_interface(auditInterface)) {
	    TLog(0, "Invalid audit interface '%s'\n", auditInterface);
	    exit(1);
	}
    }
    osi_audit(TC_StartEvent, 0, AUD_END);
    osi_audit_set_user_check(butc_confdir, tc_IsLocalRealmMatch);

    if (as->parms[1].items) {
	debugLevel = SafeATOL(as->parms[1].items->data);
	if (debugLevel == -1) {
	    TLog(0, "Illegal debug level '%s'\n", as->parms[1].items->data);
	    exit(1);
	}
    }
#ifdef xbsa
    /* Setup XBSA library interface */
    if (CONF_XBSA) {
	afs_int32 rc;
	rc = xbsa_MountLibrary(&butxInfo, xbsaType);
	if (rc != XBSA_SUCCESS) {
	    TapeLog(0, 0, rc, 0, "Unable to mount the XBSA library\n");
	    return (1);
	}

	forcemultiple = (as->parms[7].items ? 1 : 0);/*-xbsaforcemultiple */
	if (forcemultiple)
	    printf("Force XBSA multiple server support\n");

	rc = InitToServer(0 /*taskid */ , &butxInfo, adsmServerName);
	if (rc != XBSA_SUCCESS)
	    return (1);
	(void)signal(SIGINT, xbsa_shutdown);
	(void)signal(SIGHUP, xbsa_shutdown);
    }
#endif /*xbsa */

    /* cell switch */
    if (as->parms[2].items)
	strncpy(cellName, as->parms[2].items->data, sizeof(cellName));
    else
	cellName[0] = '\0';

    if (as->parms[4].items)
	autoQuery = 0;

    localauth = (as->parms[5].items ? 1 : 0);
    rxBind = (as->parms[8].items ? 1 : 0);
    allow_unauth = (as->parms[11].items ? 1 : 0);

    if (!allow_unauth && !localauth) {
	const char *errstr = "Neither -localauth nor -allow_unauthenticated was provided; refusing to start in unintended insecure configuration\n";
	TLog(0, "%s", (char *)errstr);
	exit(1);
    }

    if (rxBind) {
        afs_int32 ccode;
        if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
            AFSDIR_SERVER_NETINFO_FILEPATH) {
            char reason[1024];
            ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
                                          ADDRSPERSITE, reason,
                                          AFSDIR_SERVER_NETINFO_FILEPATH,
                                          AFSDIR_SERVER_NETRESTRICT_FILEPATH);
        } else
	{
            ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
        }
        if (ccode == 1)
            host = SHostAddrs[0];
    }

    TLog(0, "butc binding rx to %s:%d\n",
         afs_inet_ntoa_r(host, hoststr), BC_TAPEPORT + portOffset);
    code = rx_InitHost(host, htons(BC_TAPEPORT + portOffset));
    if (code) {
	TapeLog(0, 0, code, 0, "rx init failed on port %u\n",
		BC_TAPEPORT + portOffset);
	exit(1);
    }
    rx_SetRxDeadTime(150);

    /* Establish connection with the vldb server */
    code = vldbClientInit(0, localauth, cellName, &cstruct, &tokenExpires);
    if (code) {
	TapeLog(0, 0, code, 0, "Can't access vldb\n");
	return code;
    }

    strcpy(globalCellName, cellName);

    /*initialize the dumpNode list */
    InitNodeList(portOffset);

    deviceLatch = malloc(sizeof(struct deviceSyncNode));
    Lock_Init(&(deviceLatch->lock));
    deviceLatch->flags = 0;

    /* initialize database support, volume support, and logs */

    /*
     * Create security objects for the Rx server functionality.  Historically
     * this was a single rxnull security object, since the tape controller was
     * run by an operator that had local access to the tape device and some
     * administrative privilege in the cell (to be able to perform volume-level
     * accesses), but on a machine that was not necessarily trusted to hold the
     * cell-wide key.
     *
     * Such a configuration is, of course, insecure because anyone can make
     * inbound RPCs and manipulate the database, including creating bogus
     * dumps and restoring them!  Additionally, in modern usage, butc is
     * frequently run with -localauth to authenticate its outbound connections
     * to the volservers and budb with the cell-wide key, in which case the
     * cell-wide key is present and could be used to authenticate incoming
     * connections as well.
     *
     * If -localauth is in use, create the full barrage of server security
     * objects, including rxkad, so that inbound connections can be verified
     * to only be made by authenticated clients.  Otherwise, only the rxnull
     * class is in use with a single server security object.  Note that butc
     * will refuse to start in this configuration unless the
     * "-allow_unauthenticated" flag is provided, indicating that the operator
     * has ensured that incoming connections are appropriately restricted by
     * firewall configuration or network topology.
     */

    if (allow_unauth) {
	nullObjects[RX_SECIDX_NULL] = rxnull_NewServerSecurityObject();
	if (!nullObjects[RX_SECIDX_NULL]) {
	    TLog(0, "rxnull_NewServerSecurityObject");
	    exit(1);
	}
	numClasses = 1;
	secObjs = nullObjects;
    } else {
	/* Must be -localauth, so the cell keys are available. */
	afsconf_BuildServerSecurityObjects(butc_confdir, &allObjs, &numClasses);
	secObjs = allObjs;
    }

    service =
	rx_NewServiceHost(host, 0, 1, "BUTC", secObjs, numClasses, TC_ExecuteRequest);
    if (!service) {
	TLog(0, "rx_NewService");
	exit(1);
    }
    rx_SetMaxProcs(service, 4);

    /* Establish connection to the backup database */
    code = udbClientInit(0, localauth, cellName);
    if (code) {
	TapeLog(0, 0, code, 0, "Can't access backup database\n");
	exit(1);
    }
    /* This call is here to verify that we are authentiated.
     * The call does nothing and will return BUDB_NOTPERMITTED
     * if we don't belong.
     */
    code = bcdb_deleteDump(0, 0, 0, 0);
    if (code == BUDB_NOTPERMITTED) {
	TapeLog(0, 0, code, 0, "Can't access backup database\n");
	exit(1);
    }

    initStatus();
#ifdef AFS_PTHREAD_ENV
    code = pthread_attr_init(&tattr);
    if (code) {
	TapeLog(0, 0, code, 0,
		"Can't pthread_attr_init database monitor task");
	exit(1);
    }
    code = pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
    if (code) {
	TapeLog(0, 0, code, 0,
		"Can't pthread_attr_setdetachstate database monitor task");
	exit(1);
    }
    AFS_SIGSET_CLEAR();
    code = pthread_create(&dbWatcherPid, &tattr, dbWatcher, (void *)2);
    AFS_SIGSET_RESTORE();
#else
    code =
	LWP_CreateProcess(dbWatcher, 20480, LWP_NORMAL_PRIORITY, (void *)2,
			  "dbWatcher", &dbWatcherPid);
#endif
    if (code) {
	TapeLog(0, 0, code, 0, "Can't create database monitor task");
	exit(1);
    }

    TLog(0, "Starting Tape Coordinator: Port offset %u   Debug level %u\n",
	 portOffset, debugLevel);
    TLog(0, "Token expires: %s\n", cTIME(&tokenExpires));

    rx_StartServer(1);		/* Donate this process to the server process pool */
    TLog(0, "Error: StartServer returned");
    exit(1);
}
Exemple #23
0
void OPackageManager::loadInstalledPackages()
{
    OConfItemList *destList = m_ipkg.destinations();

    if ( destList )
    {
        // Initialize status messaging
        emit initStatus( destList->count() );
        int destCount = 0;

        bool categoryAdded = false;

        for ( OConfItemListIterator destIt( *destList ); destIt.current(); ++destIt )
        {
            OConfItem *destination = destIt.current();

            // Process destination only if it is active
            if ( destination->active() )
            {
                // Update status
                QString status = tr( "Reading installed packages:\n\t" );
                status.append( destination->name() );
                emit statusText( status );
                ++destCount;
                emit statusBar( destCount );
                qApp->processEvents();

                OPackageList *packageList = m_ipkg.installedPackages( destination->name(),
                                                                      destination->value() );
                if ( packageList )
                {
                    for ( OPackageListIterator packageIt( *packageList ); packageIt.current(); ++packageIt )
                    {
                        OPackage *package = packageIt.current();
                        OPackage *currPackage = m_packages[package->name()];
                        if ( currPackage )
                        {
                            // Package is in a current feed, update installed version, destination
                            currPackage->setVersionInstalled( package->versionInstalled() );
                            currPackage->setDestination( package->destination() );

                            delete package;
                        }
                        else
                        {
                            // Package isn't in a current feed, add to list
                            m_packages.insert( package->name(), package );

                            // Add category to list if it doesn't already exist
                            if ( m_categories.grep( package->category() ).isEmpty() )
                            {
                                m_categories << package->category();
                                categoryAdded = true;
                            }
                        }
                    }
                }
            }
        }
        delete destList;

        // Sort category list if categories were added
        if ( categoryAdded )
            m_categories.sort();
    }
}
Exemple #24
0
static int
WorkerBee(struct cmd_syndesc *as, void *arock)
{
    afs_int32 code;
    struct rx_securityClass *(securityObjects[3]);
    struct rx_service *service;
    time_t tokenExpires;
    char cellName[64];
    int localauth;
    /*process arguments */
    afs_int32 portOffset = 0;
#ifdef AFS_PTHREAD_ENV
    pthread_t dbWatcherPid;
    pthread_attr_t tattr;
    AFS_SIGSET_DECL;
#else
    PROCESS dbWatcherPid;
#endif
    afs_uint32 host = htonl(INADDR_ANY);

    debugLevel = 0;

    /*initialize the error tables */
    initialize_KA_error_table();
    initialize_RXK_error_table();
    initialize_KTC_error_table();
    initialize_ACFG_error_table();
    initialize_CMD_error_table();
    initialize_VL_error_table();
    initialize_BUTM_error_table();
    initialize_BUTC_error_table();
#ifdef xbsa
    initialize_BUTX_error_table();
#endif /*xbs */
    initialize_VOLS_error_table();
    initialize_BUDB_error_table();
    initialize_BUCD_error_table();

    if (as->parms[0].items) {
	portOffset = SafeATOL(as->parms[0].items->data);
	if (portOffset == -1) {
	    fprintf(stderr, "Illegal port offset '%s'\n",
		    as->parms[0].items->data);
	    exit(1);
	} else if (portOffset > BC_MAXPORTOFFSET) {
	    fprintf(stderr, "%u exceeds max port offset %u\n", portOffset,
		    BC_MAXPORTOFFSET);
	    exit(1);
	}
    }

    xbsaType = XBSA_SERVER_TYPE_NONE;	/* default */
    if (as->parms[3].items) {	/* -device */
	globalTapeConfig.capacity = 0x7fffffff;	/* 2T for max tape capacity */
	globalTapeConfig.fileMarkSize = 0;
	globalTapeConfig.portOffset = portOffset;
	strncpy(globalTapeConfig.device, as->parms[3].items->data, 100);
	xbsaType = XBSA_SERVER_TYPE_NONE;	/* Not XBSA */
    } else {
	/* Search for an entry in tapeconfig file */
	code = GetDeviceConfig(tapeConfigFile, &globalTapeConfig, portOffset);
	if (code == -1) {
	    fprintf(stderr, "Problem in reading config file %s\n",
		    tapeConfigFile);
	    exit(1);
	}
	/* Set xbsaType. If code == 1, no entry was found in the tapeconfig file so
	 * it's an XBSA server. Don't know if its ADSM or not so its unknown.
	 */
	xbsaType =
	    ((code == 1) ? XBSA_SERVER_TYPE_UNKNOWN : XBSA_SERVER_TYPE_NONE);
    }

    if (as->parms[6].items) {	/* -restoretofile */
	int s = strlen(as->parms[6].items->data);
	restoretofile = malloc(s + 1);
	strncpy(restoretofile, as->parms[6].items->data, s + 1);
	printf("Restore to file '%s'\n", restoretofile);
    }

    /* Go and read the config file: CFG_<device> or CFG_<port>. We will also set
     * the exact xbsaType within the call (won't be unknown) - double check.
     */
    code = GetConfigParams(pFile, portOffset);
    if (code)
	exit(code);
#ifdef xbsa
    if (xbsaType == XBSA_SERVER_TYPE_UNKNOWN) {
	printf
	    ("\nConfiguration file error, the TYPE parameter must be specified, or\n");
	printf("an entry must exist in %s for port %d\n", tapeConfigFile,
	       portOffset);
	exit(1);
    }
#else
    /* Not compiled for XBSA code so we can't support it */
    if (CONF_XBSA) {
	printf("\nNo entry found in %s for port %d\n", tapeConfigFile,
	       portOffset);
	printf("This binary does not have XBSA support\n");
	exit(1);
    }
#endif

    /* Open the log files. The pathnames were set in GetConfigParams() */
    logIO = fopen(logFile, "a");
    if (!logIO) {
	fprintf(stderr, "Failed to open %s\n", logFile);
	exit(1);
    }
    ErrorlogIO = fopen(ErrorlogFile, "a");
    if (!ErrorlogIO) {
	fprintf(stderr, "Failed to open %s\n", ErrorlogFile);
	exit(1);
    }
    if (lastLog) {
	lastLogIO = fopen(lastLogFile, "a");
	if (!lastLogIO) {
	    fprintf(stderr, "Failed to open %s\n", lastLogFile);
	    exit(1);
	}
    }
    if (centralLogFile) {
	struct stat sbuf;
	afs_int32 statcode;
#ifndef AFS_NT40_ENV
	char path[AFSDIR_PATH_MAX];
#endif

	statcode = stat(centralLogFile, &sbuf);
	centralLogIO = fopen(centralLogFile, "a");
	if (!centralLogIO) {
	    fprintf(stderr, "Failed to open %s; error %d\n", centralLogFile,
		    errno);
	    exit(1);
	}
#ifndef AFS_NT40_ENV
	/* Make sure it is not in AFS, has to have been created first */
	if (!realpath(centralLogFile, path)) {
	    fprintf(stderr,
		    "Warning: can't determine real path of '%s' (%d)\n",
		    centralLogFile, errno);
	} else {
	    if (strncmp(path, "/afs/", 5) == 0) {
		fprintf(stderr, "The central log '%s' should not be in AFS\n",
			centralLogFile);
		exit(1);
	    }
	}
#endif

	/* Write header if created it */
	if (statcode) {
	    char *h1 =
		"TASK   START DATE/TIME      END DATE/TIME        ELAPSED   VOLUMESET\n";
	    char *h2 =
		"-----  -------------------  -------------------  --------  ---------\n";
	    /* File didn't exist before so write the header lines */
	    fwrite(h1, strlen(h1), 1, centralLogIO);
	    fwrite(h2, strlen(h2), 1, centralLogIO);
	    fflush(centralLogIO);
	}
    }

    if (as->parms[1].items) {
	debugLevel = SafeATOL(as->parms[1].items->data);
	if (debugLevel == -1) {
	    TLog(0, "Illegal debug level '%s'\n", as->parms[1].items->data);
	    exit(1);
	}
    }
#ifdef xbsa
    /* Setup XBSA library interface */
    if (CONF_XBSA) {
	afs_int32 rc;
	rc = xbsa_MountLibrary(&butxInfo, xbsaType);
	if (rc != XBSA_SUCCESS) {
	    TapeLog(0, 0, rc, 0, "Unable to mount the XBSA library\n");
	    return (1);
	}

	forcemultiple = (as->parms[7].items ? 1 : 0);/*-xbsaforcemultiple */
	if (forcemultiple)
	    printf("Force XBSA multiple server support\n");

	rc = InitToServer(0 /*taskid */ , &butxInfo, adsmServerName);
	if (rc != XBSA_SUCCESS)
	    return (1);
    }
#endif /*xbsa */

    /* cell switch */
    if (as->parms[2].items)
	strncpy(cellName, as->parms[2].items->data, sizeof(cellName));
    else
	cellName[0] = '\0';

    if (as->parms[4].items)
	autoQuery = 0;

    localauth = (as->parms[5].items ? 1 : 0);
    rxBind = (as->parms[8].items ? 1 : 0);

    if (rxBind) {
        afs_int32 ccode;
        if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
            AFSDIR_SERVER_NETINFO_FILEPATH) {
            char reason[1024];
            ccode = parseNetFiles(SHostAddrs, NULL, NULL,
                                           ADDRSPERSITE, reason,
                                           AFSDIR_SERVER_NETINFO_FILEPATH,
                                           AFSDIR_SERVER_NETRESTRICT_FILEPATH);
        } else
	{
            ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
        }
        if (ccode == 1)
            host = SHostAddrs[0];
    }

    code = rx_InitHost(host, htons(BC_TAPEPORT + portOffset));
    if (code) {
	TapeLog(0, 0, code, 0, "rx init failed on port %u\n",
		BC_TAPEPORT + portOffset);
	exit(1);
    }
    rx_SetRxDeadTime(150);

    /* Establish connection with the vldb server */
    code = vldbClientInit(0, localauth, cellName, &cstruct, &tokenExpires);
    if (code) {
	TapeLog(0, 0, code, 0, "Can't access vldb\n");
	return code;
    }

    strcpy(globalCellName, cellName);

    /*initialize the dumpNode list */
    InitNodeList(portOffset);

    deviceLatch =
	(struct deviceSyncNode *)(malloc(sizeof(struct deviceSyncNode)));
    Lock_Init(&(deviceLatch->lock));
    deviceLatch->flags = 0;

    /* initialize database support, volume support, and logs */

    /* Create a single security object, in this case the null security
     * object, for unauthenticated connections, which will be used to control
     * security on connections made to this server
     */

    securityObjects[0] = rxnull_NewServerSecurityObject();
    securityObjects[1] = (struct rx_securityClass *)0;	/* don't bother with rxvab */
    if (!securityObjects[0]) {
	TLog(0, "rxnull_NewServerSecurityObject");
	exit(1);
    }

    service =
	rx_NewServiceHost(host, 0, 1, "BUTC", securityObjects, 3, TC_ExecuteRequest);
    if (!service) {
	TLog(0, "rx_NewService");
	exit(1);
    }
    rx_SetMaxProcs(service, 4);

    /* Establish connection to the backup database */
    code = udbClientInit(0, localauth, cellName);
    if (code) {
	TapeLog(0, 0, code, 0, "Can't access backup database\n");
	exit(1);
    }
    /* This call is here to verify that we are authentiated.
     * The call does nothing and will return BUDB_NOTPERMITTED
     * if we don't belong.
     */
    code = bcdb_deleteDump(0, 0, 0, 0);
    if (code == BUDB_NOTPERMITTED) {
	TapeLog(0, 0, code, 0, "Can't access backup database\n");
	exit(1);
    }

    initStatus();
#ifdef AFS_PTHREAD_ENV
    code = pthread_attr_init(&tattr);
    if (code) {
	TapeLog(0, 0, code, 0,
		"Can't pthread_attr_init database monitor task");
	exit(1);
    }
    code = pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
    if (code) {
	TapeLog(0, 0, code, 0,
		"Can't pthread_attr_setdetachstate database monitor task");
	exit(1);
    }
    AFS_SIGSET_CLEAR();
    code = pthread_create(&dbWatcherPid, &tattr, dbWatcher, (void *)2);
    AFS_SIGSET_RESTORE();
#else
    code =
	LWP_CreateProcess(dbWatcher, 20480, LWP_NORMAL_PRIORITY, (void *)2,
			  "dbWatcher", &dbWatcherPid);
#endif
    if (code) {
	TapeLog(0, 0, code, 0, "Can't create database monitor task");
	exit(1);
    }

    TLog(0, "Starting Tape Coordinator: Port offset %u   Debug level %u\n",
	 portOffset, debugLevel);
    TLog(0, "Token expires: %s\n", cTIME(&tokenExpires));

    rx_StartServer(1);		/* Donate this process to the server process pool */
    TLog(0, "Error: StartServer returned");
    exit(1);
}
Exemple #25
0
static int
backupInit(void)
{
    afs_int32 code;
    static int initd = 0;	/* ever called? */
    PROCESS watcherPid;
    PROCESS pid;		/* LWP process ID */

    /* Initialization */
    initialize_CMD_error_table();

    /* don't run more than once */
    if (initd) {
	afs_com_err(whoami, 0, "Backup already initialized.");
	return 0;
    }
    initd = 1;

    code = bc_InitConfig((char *)DefaultConfDir);
    if (code) {
	afs_com_err(whoami, code,
		"Can't initialize from config files in directory '%s'",
		DefaultConfDir);
	return (code);
    }

    /*
     * Set up Rx.
     */
    code = LWP_InitializeProcessSupport(LWP_NORMAL_PRIORITY, &pid);
    if (code) {
	afs_com_err(whoami, code, "; Can't initialize LWP");
	return (code);
    }

    code = rx_Init(htons(0));
    if (code) {
	afs_com_err(whoami, code, "; Can't initialize Rx");
	return (code);
    }

    rx_SetRxDeadTime(60);

    /* VLDB initialization */
    code = vldbClientInit(0, localauth, tcell, &cstruct, &tokenExpires);
    if (code)
	return (code);

    /* Backup database initialization */
    code = udbClientInit(0, localauth, tcell);
    if (code)
	return (code);

    /* setup status monitoring thread */
    initStatus();
    code =
	LWP_CreateProcess(statusWatcher, 20480, LWP_NORMAL_PRIORITY,
			  (void *)2, "statusWatcher", &watcherPid);
    if (code) {
	afs_com_err(whoami, code, "; Can't create status monitor task");
	return (code);
    }

    return (0);
}
Exemple #26
0
void OPackageManager::loadAvailablePackages()
{
    m_packages.clear();

    OConfItemList *serverList = m_ipkg.servers();

    if ( serverList )
    {
        // Initialize status messaging
        emit initStatus( serverList->count() );
        int serverCount = 0;

        bool categoryAdded = false;

        for ( OConfItemListIterator serverIt( *serverList ); serverIt.current(); ++serverIt )
        {
            OConfItem *server = serverIt.current();

            // Process server only if it is active
            if ( server->active() )
            {
                // Update status
                QString status = tr( "Reading available packages:\n\t" );
                status.append( server->name() );
                emit statusText( status );
                ++serverCount;
                emit statusBar( serverCount );
                qApp->processEvents();

                OPackageList *packageList = m_ipkg.availablePackages( server->name() );
                if ( packageList )
                {
                    for ( OPackageListIterator packageIt( *packageList ); packageIt.current(); ++packageIt )
                    {
                        OPackage *package = packageIt.current();

                        // Load package info
                        if ( !m_packages.find( package->name() ) )
                            m_packages.insert( package->name(), package );
                        else
                        {
                            // If new package is newer version, replace existing package
                            OPackage *currPackage = m_packages[package->name()];
                            if ( compareVersions( package->version(), currPackage->version() ) == 1 )
                                m_packages.replace( package->name(), package );
                        }

                        // Add category to list if it doesn't already exist
                        if ( m_categories.grep( package->category() ).isEmpty() )
                        {
                            m_categories << package->category();
                            categoryAdded = true;
                        }
                    }
                }
            }
        }
        delete serverList;

        // Sort category list if categories were added
        if ( categoryAdded )
            m_categories.sort();
    }
}
Exemple #27
0
FFDemo::FFDemo()
{
    mRunning = true;
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
    mScreen = SDL_SetVideoMode(320, 240, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_HWACCEL);
    SDL_EnableUNICODE(1);
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    SDL_ShowCursor(0);
    SDL_WM_SetCaption("Gui-chan FF demo", NULL);
    Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024);

    mChooseSound = Mix_LoadWAV("sound/sound1.wav");
    mEscapeSound = Mix_LoadWAV("sound/sound2.wav");

    mSDLImageLoader = new fcn::SDLImageLoader();
    fcn::Image::setImageLoader(mSDLImageLoader); 
    mSDLGraphics = new fcn::SDLGraphics();
    mSDLGraphics->setTarget(mScreen);
    mSDLInput = new fcn::SDLInput();
	
    mSplashImage = fcn::Image::load("images/splash.png");	

    mTop = new fcn::Container();
    mTop->setBaseColor(fcn::Color(0x000000));
    mTop->setDimension(fcn::Rectangle(0, 0, 320, 240));
    mGui = new fcn::Gui();
    mGui->setTabbingEnabled(false);
    mGui->setGraphics(mSDLGraphics);
    mGui->setInput(mSDLInput);	
    mGui->setTop(mTop);
    mFontWhite = new fcn::ImageFont("images/rpgfont.png", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&`'*#=[]\""); 	
    mFontCyan = new fcn::ImageFont("images/rpgfont2.png", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&`'*#=[]\"");	
    fcn::Widget::setGlobalFont(mFontWhite);
	
    initMain();

    mMenu = new FFContainer();
    mMenu->setDimension(fcn::Rectangle(230, 0, 90, 130));
    mMenu->setOpaque(false);
    mTop->add(mMenu);
	
    mGoldFootsteps = new FFContainer();
    mGoldFootsteps->setDimension(fcn::Rectangle(210, 170, 110, 70));
    mGoldFootsteps->setOpaque(false);
    mGoldFootsteps->setFrameSize(0);
    mTop->add(mGoldFootsteps);

    mTime = new FFContainer();
    mTime->setDimension(fcn::Rectangle(230, 130, 90, 40));
    mTime->setOpaque(false);
    mTop->add(mTime);
																	 
    mGoldFootstepsInfo1 = new fcn::TextBox("Steps\n\nGP");
    mGoldFootstepsInfo1->setFont(mFontCyan);
    mGoldFootstepsInfo1->setOpaque(false);
    mGoldFootstepsInfo1->setEditable(false);
    mGoldFootstepsInfo1->setFocusable(false);
    mGoldFootstepsInfo1->setFrameSize(0);
		
    mGoldFootstepsInfo2 = new fcn::TextBox("\n    9119092\n\n    1009213");
    mGoldFootstepsInfo2->setOpaque(false);
    mGoldFootstepsInfo2->setEditable(false);
    mGoldFootstepsInfo2->setFocusable(false);
    mGoldFootstepsInfo2->setFrameSize(0);
	
    mTimeLabel1 = new fcn::Label("Time");
    mTimeLabel1->setFont(mFontCyan);
    mTimeLabel2 = new fcn::Label();
    mTime->add(mTimeLabel1, 5, 5);	
    mTime->add(mTimeLabel2, 22, 20);

	
    mGoldFootsteps->add(mGoldFootstepsInfo2, 5, 0);
    mGoldFootsteps->add(mGoldFootstepsInfo1, 5, 5);
	
    mMenuListModel = new StringListModel();
    mMenuListModel->add("Items");
    mMenuListModel->add("Status");
    mMenuListModel->add("Skills");
    mMenuListModel->add("Magic");
    mMenuListModel->add("About");
    mMenuListModel->add("");
    mMenuListModel->add("Quit");
	
    mMenuList = new FFListBox();
    mMenuList->setActionEventId("menu");
    mMenuList->addActionListener(this);	
    mMenuList->setListModel(mMenuListModel);
    mMenu->add(mMenuList, 5, 5);
    mMenuList->setSelected(0);
    mMenuList->requestFocus();

    initStatus();
    initAbout();
    initItems();
    initMagicSkills();
}
Return<void> CameraDeviceSession::configureStreams_3_3(
        const StreamConfiguration& requestedConfiguration,
        ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb)  {
    Status status = initStatus();
    HalStreamConfiguration outStreams;

    // hold the inflight lock for entire configureStreams scope since there must not be any
    // inflight request/results during stream configuration.
    Mutex::Autolock _l(mInflightLock);
    if (!mInflightBuffers.empty()) {
        ALOGE("%s: trying to configureStreams while there are still %zu inflight buffers!",
                __FUNCTION__, mInflightBuffers.size());
        _hidl_cb(Status::INTERNAL_ERROR, outStreams);
        return Void();
    }

    if (!mInflightAETriggerOverrides.empty()) {
        ALOGE("%s: trying to configureStreams while there are still %zu inflight"
                " trigger overrides!", __FUNCTION__,
                mInflightAETriggerOverrides.size());
        _hidl_cb(Status::INTERNAL_ERROR, outStreams);
        return Void();
    }

    if (!mInflightRawBoostPresent.empty()) {
        ALOGE("%s: trying to configureStreams while there are still %zu inflight"
                " boost overrides!", __FUNCTION__,
                mInflightRawBoostPresent.size());
        _hidl_cb(Status::INTERNAL_ERROR, outStreams);
        return Void();
    }

    if (status != Status::OK) {
        _hidl_cb(status, outStreams);
        return Void();
    }

    camera3_stream_configuration_t stream_list;
    hidl_vec<camera3_stream_t*> streams;

    stream_list.operation_mode = (uint32_t) requestedConfiguration.operationMode;
    stream_list.num_streams = requestedConfiguration.streams.size();
    streams.resize(stream_list.num_streams);
    stream_list.streams = streams.data();

    for (uint32_t i = 0; i < stream_list.num_streams; i++) {
        int id = requestedConfiguration.streams[i].id;

        if (mStreamMap.count(id) == 0) {
            Camera3Stream stream;
            V3_2::implementation::convertFromHidl(requestedConfiguration.streams[i], &stream);
            mStreamMap[id] = stream;
            mStreamMap[id].data_space = mapToLegacyDataspace(
                    mStreamMap[id].data_space);
            mCirculatingBuffers.emplace(stream.mId, CirculatingBuffers{});
        } else {
            // width/height/format must not change, but usage/rotation might need to change
            if (mStreamMap[id].stream_type !=
                    (int) requestedConfiguration.streams[i].streamType ||
                    mStreamMap[id].width != requestedConfiguration.streams[i].width ||
                    mStreamMap[id].height != requestedConfiguration.streams[i].height ||
                    mStreamMap[id].format != (int) requestedConfiguration.streams[i].format ||
                    mStreamMap[id].data_space !=
                            mapToLegacyDataspace( static_cast<android_dataspace_t> (
                                    requestedConfiguration.streams[i].dataSpace))) {
                ALOGE("%s: stream %d configuration changed!", __FUNCTION__, id);
                _hidl_cb(Status::INTERNAL_ERROR, outStreams);
                return Void();
            }
            mStreamMap[id].rotation = (int) requestedConfiguration.streams[i].rotation;
            mStreamMap[id].usage = (uint32_t) requestedConfiguration.streams[i].usage;
        }
        streams[i] = &mStreamMap[id];
    }

    ATRACE_BEGIN("camera3->configure_streams");
    status_t ret = mDevice->ops->configure_streams(mDevice, &stream_list);
    ATRACE_END();

    // In case Hal returns error most likely it was not able to release
    // the corresponding resources of the deleted streams.
    if (ret == OK) {
        // delete unused streams, note we do this after adding new streams to ensure new stream
        // will not have the same address as deleted stream, and HAL has a chance to reference
        // the to be deleted stream in configure_streams call
        for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
            int id = it->first;
            bool found = false;
            for (const auto& stream : requestedConfiguration.streams) {
                if (id == stream.id) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                // Unmap all buffers of deleted stream
                // in case the configuration call succeeds and HAL
                // is able to release the corresponding resources too.
                cleanupBuffersLocked(id);
                it = mStreamMap.erase(it);
            } else {
                ++it;
            }
        }

        // Track video streams
        mVideoStreamIds.clear();
        for (const auto& stream : requestedConfiguration.streams) {
            if (stream.streamType == V3_2::StreamType::OUTPUT &&
                stream.usage &
                    graphics::common::V1_0::BufferUsage::VIDEO_ENCODER) {
                mVideoStreamIds.push_back(stream.id);
            }
        }
        mResultBatcher.setBatchedStreams(mVideoStreamIds);
    }

    if (ret == -EINVAL) {
        status = Status::ILLEGAL_ARGUMENT;
    } else if (ret != OK) {
        status = Status::INTERNAL_ERROR;
    } else {
        convertToHidl(stream_list, &outStreams);
        mFirstRequest = true;
    }

    _hidl_cb(status, outStreams);
    return Void();
}
Exemple #29
0
Common::Error HugoEngine::run() {
	s_Engine = this;
	initGraphics(320, 200, false);

	_mouse = new MouseHandler(this);
	_inventory = new InventoryHandler(this);
	_route = new Route(this);
	_sound = new SoundHandler(this);

	// Setup mixer
	syncSoundSettings();

	_text = new TextHandler(this);

	_topMenu = new TopMenu(this);

	switch (_gameVariant) {
	case kGameVariantH1Win: // H1 Win
		_file = new FileManager_v1w(this);
		_scheduler = new Scheduler_v1w(this);
		_intro = new intro_v1w(this);
		_screen = new Screen_v1w(this);
		_parser = new Parser_v1w(this);
		_object = new ObjectHandler_v1w(this);
		_normalTPS = 9;
		break;
	case kGameVariantH2Win:
		_file = new FileManager_v2w(this);
		_scheduler = new Scheduler_v1w(this);
		_intro = new intro_v2w(this);
		_screen = new Screen_v1w(this);
		_parser = new Parser_v1w(this);
		_object = new ObjectHandler_v1w(this);
		_normalTPS = 9;
		break;
	case kGameVariantH3Win:
		_file = new FileManager_v2w(this);
		_scheduler = new Scheduler_v1w(this);
		_intro = new intro_v3w(this);
		_screen = new Screen_v1w(this);
		_parser = new Parser_v1w(this);
		_object = new ObjectHandler_v1w(this);
		_normalTPS = 9;
		break;
	case kGameVariantH1Dos: // H1 DOS
		_file = new FileManager_v1d(this);
		_scheduler = new Scheduler_v1d(this);
		_intro = new intro_v1d(this);
		_screen = new Screen_v1d(this);
		_parser = new Parser_v1d(this);
		_object = new ObjectHandler_v1d(this);
		_normalTPS = 8;
		break;
	case kGameVariantH2Dos:
		_file = new FileManager_v2d(this);
		_scheduler = new Scheduler_v2d(this);
		_intro = new intro_v2d(this);
		_screen = new Screen_v1d(this);
		_parser = new Parser_v2d(this);
		_object = new ObjectHandler_v2d(this);
		_normalTPS = 8;
		break;
	case kGameVariantH3Dos:
		_file = new FileManager_v3d(this);
		_scheduler = new Scheduler_v3d(this);
		_intro = new intro_v3d(this);
		_screen = new Screen_v1d(this);
		_parser = new Parser_v3d(this);
		_object = new ObjectHandler_v3d(this);
		_normalTPS = 9;
		break;
	}

	if (!loadHugoDat())
		return Common::kUnknownError;

	// Use Windows-looking mouse cursor
	_screen->setCursorPal();
	_screen->resetInventoryObjId();

	_scheduler->initCypher();

	initStatus();                                   // Initialize game status
	initConfig();                                   // Initialize user's config
	if (!_status._doQuitFl) {
		initialize();
		resetConfig();                              // Reset user's config
		initMachine();

		// Start the state machine
		_status._viewState = kViewIntroInit;

		int16 loadSlot = Common::ConfigManager::instance().getInt("save_slot");
		if (loadSlot >= 0) {
			_status._skipIntroFl = true;
			_file->restoreGame(loadSlot);
		} else {
			_file->saveGame(0, "New Game");
		}
	}

	while (!_status._doQuitFl) {
		_screen->drawBoundaries();
		g_system->updateScreen();
		runMachine();

		// Handle input
		Common::Event event;
		while (_eventMan->pollEvent(event)) {
			switch (event.type) {
			case Common::EVENT_KEYDOWN:
				_parser->keyHandler(event);
				break;
			case Common::EVENT_MOUSEMOVE:
				_mouse->setMouseX(event.mouse.x);
				_mouse->setMouseY(event.mouse.y);
				break;
			case Common::EVENT_LBUTTONUP:
				_mouse->setLeftButton();
				break;
			case Common::EVENT_RBUTTONUP:
				_mouse->setRightButton();
				break;
			case Common::EVENT_QUIT:
				_status._doQuitFl = true;
				break;
			default:
				break;
			}
		}
		if (_status._helpFl) {
			_status._helpFl = false;
			_file->instructions();
		}

		_mouse->mouseHandler();                     // Mouse activity - adds to display list
		_screen->displayList(kDisplayDisplay);      // Blit the display list to screen
		_status._doQuitFl |= shouldQuit();           // update game quit flag
	}
	return Common::kNoError;
}
void ConfFile::readRootConfFile(const char* progId, char* mcuModel, char* filePath, byte& statusRes) {
  initStatus();
  mcuModel[0] = '\0';
  filePath[0] = '\0';
  byte pos = 0;
  boolean eol;
  char c;
  byte progIdLength = strLength(progId);
  logDebugD("l:", progIdLength);
  
  boolean matchDetected = false;
  while (!matchDetected && skipToValidData(statusRes)) { // loop for every valid line
    checkStatus(); // for skipToValidData

    logDebug("skipped");
    // read PROG_ID and match it
    pos = 0;
    while(true) {
      if (!_confFile.available()) {
        logDebug("readRootConfFile:unexp EOF");
        returnStatus(ERR(0x22)); // unexpected EOF
      }
      logDebug("avail");
      c = readCharSafe(eol, statusRes); checkStatus();
      logDebugC("readChar",c);
      if (eol) {
        logDebug("readRootConfFile:unexp EOF");
        returnStatus(ERR(0x22)); // unexpected EOL
      }
      if ((pos >= progIdLength) || (progId[pos] != c) || isWhiteChar(c)) {
           // if we are above expected progId length, no need to continue this line, or
           // if char at pos didn't match progId[pos], or
           // if white char
        break;
      }
      pos++;
    }

    logDebugD("step1:",pos);

    if (pos != progIdLength) {
      goto _skipLine;
    } else {
      matchDetected = true;
    }
      
    logDebugD("step2:",pos);
    
    // read MCU_MODEL
    skipWhiteCharactersExpectNoEolNoEof(statusRes); checkStatus();
    pos = 0;
    while (true) {
      if (pos >= UtilsAVR::MCU_MODEL_BUFFER_SIZE) {// too long MCU_MODEL in conf file!
        mcuModel[UtilsAVR::MCU_MODEL_BUFFER_SIZE-1] = '\0';
        returnStatus(ERR(0x23));
      }
      
      if (!_confFile.available()) {
        logDebug("!EOF");
        returnStatus(ERR(0x22)); // unexpected EOF
      }
      mcuModel[pos] = readCharSafe(eol, statusRes); checkStatus();
      if (eol) {
        logDebug("!EOL");
        returnStatus(ERR(0x22)); // unexpected EOL
      }
      if (isWhiteChar(mcuModel[pos])) {
        mcuModel[pos] = '\0';
        break;
      }
      pos++;
    }

    logDebugD("step3:",pos);
    
    // read FILE_PATH
    skipWhiteCharactersExpectNoEolNoEof(statusRes); checkStatus();
    pos = 0;
    while (true) {
      if (pos >= Utils::FILE_PATH_BUFFER_SIZE) {// too long FILE_PATH in conf file!
        filePath[Utils::FILE_PATH_BUFFER_SIZE-1] = '\0';
        returnStatus(ERR(0x24));
      }
      
      if (!_confFile.available()) {
        logDebug("!EOF");
        returnStatus(ERR(0x22)); // unexpected EOF
      }
      filePath[pos] = readCharSafe(eol, statusRes); checkStatus();
      if (eol || isWhiteChar(filePath[pos])) {
        filePath[pos] = '\0';
        break;
      }
      pos++;
    }

    logDebugD("step4:",pos);
    
    // Skip this line and proceed to next line
    _skipLine: skipLine(statusRes); checkStatus(); // skip the line, and continue to next one
  }
}