Exemple #1
0
void
Bchart::
add_edge(Edge* edge, int right)
{
  if(printDebug() > 250)
    cerr << "add_edge " << *edge << endl;

  int     loc = right ? edge->loc() : edge->start() ;
  int     i;

  int     stoploc = right ? loc : loc-1;
  extend_rule(edge, stops[loc], right); 
  // Iterate over i = the length of the constituent -1.;
  // looking for a reg item of length i and starting position start;
  if(right)
    for( i = 0 ; i < wrd_count_ - loc ; i++ )
      already_there_extention(i, loc, right, edge);
  else
    for( i = 0 ; i < loc ; i++)
      already_there_extention(loc - i -1, i, right, edge);

  assert(loc >= 0 && loc < MAXSENTLEN);
  waitingEdges[right][loc].push_back( edge ); 
}
void GameController::fullDebugPrint()
{
    printDebug("Next blocks:");
    for (const auto& blockPair : nextBlocks_)
    {
        std::string blockPairStr;
        blockPairStr += '[';
        blockPairStr += blockPair.first.color;
        blockPairStr += ' ';
        blockPairStr += blockPair.second.color;
        blockPairStr += ']';
        printDebug(blockPairStr);
    }
    printDebug("My current grid: ");
    for (const auto& gridLine : currentGrid_.getGrid())
    {
        printDebug(gridLine);
    }
    printDebug("My opponent's grid: ");
    for (const auto& gridLine : opponentGrid_.getGrid())
    {
        printDebug(gridLine);
    }
}
Exemple #3
0
///////////////////////////////////////////////////////////////////////////////
/// Simulate the given FMU using the forward euler method.
/// Time events are processed by reducing step size to exactly hit tNext.
/// State events are checked and fired only at the end of an Euler step. 
/// The simulator may therefore miss state events and fires state events typically too late.
///
///\param fmu FMU.
///\param tEnd Ending time of simulation.
///\param h Tiem step size.
///\param loggingOn Controller for logging.
///\param separator Separator character.
///\return 0 if there is no error occurred.
///////////////////////////////////////////////////////////////////////////////
static int simulate(FMU* fmu, double tEnd, double h, fmiBoolean loggingOn, char separator) {
		
  int i, n;
  fmiBoolean timeEvent, stateEvent, stepEvent;
  double time;  
  ModelDescription* md;            // handle to the parsed XML file        
  const char* guid;                // global unique id of the fmu
  fmiCallbackFunctions callbacks;  // called by the model during simulation
  fmiComponent c;                  // instance of the fmu 
  fmiStatus fmiFlag;               // return code of the fmu functions
  fmiReal t0 = 0;                  // start time
	fmiBoolean toleranceControlled = fmiFalse;
  int nSteps = 0;
  FILE* file;

	fmiValueReference vr;			// add it to get value reference for variables

  //Note: User defined references
  //Begin------------------------------------------------------------------
  fmiValueReference vru[1], vry[1]; // value references for two input and two output variables 
  //End--------------------------------------------------------------------

	ScalarVariable** vars = fmu->modelDescription->modelVariables;		// add it to get variables
	int k;							// add a counter for variables
	fmiReal ru1, ru2, ry, ry1, ry2;	// add real variables for input and output
	fmiInteger ix, iy;				// add integer variables for input and output
	fmiBoolean bx, by;				// add boolean variables for input and output
	fmiString sx, sy;				// Zuo: add string variables for input and output
	fmiStatus status;				// Zuo: add stauus for fmi

	printDebug("Instantiate the fmu.\n");		
  // instantiate the fmu
  md = fmu->modelDescription;
  guid = getString(md, att_guid);
	printfDebug("Got GUID = %s!\n", guid);	
  callbacks.logger = fmuLogger;
  callbacks.allocateMemory = calloc;
  callbacks.freeMemory = free;
	printDebug("Got callbacks!\n");
	printfDebug("Model Identifer is %s\n", getModelIdentifier(md));
 	c = fmu->instantiateSlave(getModelIdentifier(md), guid, "Model1", "", 10, fmiFalse, fmiFalse, callbacks, loggingOn);
  if (!c) {
    printError("could not instantiate slaves.\n");
    return 1;
  }
  printDebug("Instantiated slaves!\n");	

  // Open result file
  if (!(file=fopen(RESULT_FILE, "w"))) {
    printfError("could not write %s because:\n", RESULT_FILE);
    printfError("    %s\n", strerror(errno));
    return 1;
  }
  printDebug("Open results file!\n");    

  // Set the start time and initialize
  time = t0;

	printDebug("start to initialize fmu!\n");	   
	fmiFlag =  fmu->initializeSlave(c, t0, fmiTrue, tEnd);	
	printDebug("Initialized fmu!\n");
  if (fmiFlag > fmiWarning) {
    printError("could not initialize model");
    return 1;
  }
 
  // Output solution for time t0 
  printDebug("start to outputRow");
  //outputRow(fmu, c, t0, file, separator, TRUE);  // output column names
  //outputRow(fmu, c, t0, file, separator, FALSE); // output initla value of fmu 
  outputdata(t0, file, separator, 0, 0, TRUE);
  
  printDebug("start to getValueReference");
  ///////////////////////////////////////////////////////////////////////////// 
  // Get value references for input and output varibles
  // Note: User needs to specify the name of variables for their own fmus
  //Begin------------------------------------------------------------------
  vru[0] = getValueReference(getVariableByName(md, "Toa"));
  //vru[1] = getValueReference(getVariableByName(md, "u2"));
  vry[0] = getValueReference(getVariableByName(md, "TrmSou"));
  //vry[1] = getValueReference(getVariableByName(md, "y2"));
  //End--------------------------------------------------------------------
  
  printDebug("Enter in simulation loop.\n");	

  // enter the simulation loop
  while (time < tEnd) {
    if (loggingOn) printf("Step %d to t=%.4f\n", nSteps, time);		  

    ///////////////////////////////////////////////////////////////////////////
    // Step 1: get values of output variables	from slaves
    for (k=0; vars[k]; k++) {
	    ScalarVariable* sv = vars[k];
	    if (getAlias(sv)!=enu_noAlias) continue;	
	    if (getCausality(sv) != enu_output) continue; // only get output variable
      vr = getValueReference(sv);

      switch (sv->typeSpec->type){
        case elm_Real:
          fmu->getReal(c, &vr, 1, &ry); 
          break;
        case elm_Integer:
          fmu->getInteger(c, &vr, 1, &iy);  
          break;
        case elm_Boolean:
          fmu->getBoolean(c, &vr, 1, &by);
          break;
        case elm_String:
          fmu->getString(c, &vr, 1, &sy);
          break;
      }


      // Allocate values to cooresponding varibles on master program
      // Note: User needs to specify the output variables for their own fmu 
      //Begin------------------------------------------------------------------
      if (vr == vry[0]) ry1 = ry;
      //else if(vr == vry[1]) ry2 = ry;
      //End--------------------------------------------------------------------
    } 
    
    ///////////////////////////////////////////////////////////////////////////
    // Step 2: compute on master side 
    // Note: User can adjust the computing schemes of mater program
    //Begin------------------------------------------------------------------
     printf("Dymola output = %f\n", ry1);
	 //= ry2 + 3.0; 
    ru1 = 293;
    //End--------------------------------------------------------------------

    //////////////////////////////////////////////////////////////////////////
    // Step 3: set input variables back to slaves
    for (k=0; vars[k]; k++) {
      ScalarVariable* sv = vars[k];
      if (getAlias(sv)!=enu_noAlias) continue;
	    if (getCausality(sv) != enu_input) continue; // only set input variable
        vr = getValueReference(sv);
        // Note: User can adjust the settings for input variables
        //Begin------------------------------------------------------------------
        switch (sv->typeSpec->type){
          case elm_Real:

            if(vr == vru[0]) {
              fmu->setReal(c, &vr, 1, &ru1); 				
              printDebug("Set u1.\n");
            }
            //else if (vr == vru[1]) {
            //  fmu->setReal(c, &vr, 1, &ru2);
            //  printDebug("Set u2.\n");
            //}
            else
              printf("Warning: no data given for input variable.\n");
            break;
          case elm_Integer:
            fmu->setInteger(c, &vr, 1, &ix);  
            break;
          case elm_Boolean:
            fmu->setBoolean(c, &vr, 1, &bx);
            break;
          case elm_String:
		    printDebug("Get string in simulatio()");
            fmu->setString(c, &vr, 1, &sx);
            break;        
        }
        //End--------------------------------------------------------------------        
    } 
    
    // Advance to next time step
    status = fmu->doStep(c, time, h, fmiTrue);  
    // Terminate this row
    // fprintf(file, "\n");  (comment out this line to get rid of the blank line between the results in the csv file.)    
   
    time = min(time+h, tEnd);
    //outputRow(fmu, c, time, file, separator, FALSE); // output values for this step
	outputdata(time, file, separator, ru1, ry1, FALSE);
    nSteps++;
   
  } // end of while  

  // Cleanup
  fclose(file);

  // Print simulation summary 
  if (loggingOn) printf("Step %d to t=%.4f\n", nSteps, time);		
  printf("Simulation from %g to %g terminated successful\n", t0, tEnd);
  printf("  steps ............ %d\n", nSteps);
  printf("  fixed step size .. %g\n", h);

  return 0; // success
}
sgs::Derive::MSkill * AIGuanyu::useWushengInUsecard() {
	sgs::Derive::MWuSheng * returnWusheng = 0;
	if (!canUseSha())
		return returnWusheng;

	const CardVec& redShoupaiFound = redShoupai();
	if (redShoupaiFound.empty()) {
		printDebug("AIGuanyu::useWusheng: no red card");
		return returnWusheng;
	}

	PlayerVec attackTargetVec = shaTarget();
	if (attackTargetVec.empty()) {
		for (CardVec::const_iterator cardIter = redShoupaiFound.begin();
				cardIter != redShoupaiFound.end(); ++cardIter) {

			if (canUseFangtian() && attackTargetVec.size() > 1) {
				printDebug("AIGuanyu::useWusheng: using fangtian");
				returnWusheng = new sgs::Derive::MWuSheng(myPlayer(),
						sgs::ConstData::PHAND, (*cardIter).second);

				// push in the fisrt 3 enemies;
				int j = 0;
				PlayerVec arrangedTargets;
				for (PlayerVec::iterator iter = attackTargetVec.begin();
						iter != attackTargetVec.end() && j < 3; ++iter, ++j) {
					arrangedTargets.push_back(*iter);
				}

				// sort the targets by seat;
				sgsui::PlayerSort arrangeSeat(mySeat(), sgsui::BySeat);
				std::sort(arrangedTargets.begin(), arrangedTargets.end(),
						arrangeSeat);
				for (PlayerVec::iterator iter = arrangedTargets.begin();
						iter != arrangedTargets.end(); ++iter) {
					returnWusheng->addto(*iter);
				}
			} else {
				printDebug("AIGuanyu::useWusheng: not using fangtian");

				// Do not use black Sha to Renwang
				// try each player in range
				for (PlayerVec::reverse_iterator riter =
						attackTargetVec.rbegin();
						riter != attackTargetVec.rend(); ++riter) {
					sgs::DataType::Player * target = *riter;

					returnWusheng = new sgs::Derive::MWuSheng(myPlayer(),
							sgs::ConstData::PHAND, (*cardIter).second, target);
					printDebug(
							"AIGuanyu::useWusheng: will attack player "
									+ QString::number(target->seat())
									+ ", break and stop searching for target");
					break;
				}
			}
			return returnWusheng;
		}
	}
	return returnWusheng;
}
Exemple #5
0
///////////////////////////////////////////////////////////////////////////////
/// Output time and all non-alias variables in CSV format.
/// If separator is ',', columns are separated by ',' and '.' is used for floating-point numbers.
/// Otherwise, the given separator (e.g. ';' or '\t') is to separate columns, and ',' is used for 
/// floating-point numbers.
///
///\param fmu FMU.
///\param c FMI component.
///\param time Time when data is outputed.
///\param separator Separator in file.
///\param header Indicator of row head.
///////////////////////////////////////////////////////////////////////////////
static void outputRow(FMU *fmu, fmiComponent c, double time, FILE* file, char separator, boolean header, double x, double y) {
  int k;
  fmiReal r;
  fmiInteger i;
  fmiBoolean b;
  fmiString s;
  fmiValueReference vr;				
  ScalarVariable** vars = fmu->modelDescription->modelVariables;
  char buffer[32];
  
  // Print first column
  if (header) 
    fprintf(file, "time"); 
  else {
    if (separator==',') 
      fprintf(file, "%.4f", time);				
    else {
      // Separator is e.g. ';' or '\t'
      doubleToCommaString(buffer, time);
      fprintf(file, "%s", buffer);       
    }
  }
    
  // Print all other columns
  for (k=0; vars[k]; k++) {
    ScalarVariable* sv = vars[k];
    if (getAlias(sv)!=enu_noAlias) continue;
    if (header) {
      // Output names only
      fprintf(file, "%c%s", separator, getName(sv));
    }
    else {
      // Output values
      vr = getValueReference(sv);
      switch (sv->typeSpec->type){
        case elm_Real:
          fmu->getReal(c, &vr, 1, &r);
          if (separator==',') 
            fprintf(file, ",%.4f", r);				
        else {
          // Separator is e.g. ';' or '\t'
          doubleToCommaString(buffer, r);
          fprintf(file, "%c%s", separator, buffer);       
          }
          break;
        case elm_Integer:
          fmu->getInteger(c, &vr, 1, &i);
          fprintf(file, "%c%d", separator, i);
          break;
        case elm_Boolean:
          fmu->getBoolean(c, &vr, 1, &b);
          fprintf(file, "%c%d", separator, b);
          break;
        case elm_String:
		  printDebug("get string in outputrow");
          //fmu->getString(c, &vr, 1, &s);
          //fprintf(file, "%c%s", separator, s);
          break;
      }
    }
  } // for
    
  // Terminate this row
  fprintf(file, "\n"); 
}
Item*
Bchart::
edgesFromTree(InputTree* tree)
{
  int b, b0;
  b0 = tree->num();
  const Term* trm = Term::get(tree->term());
  assert(trm);
  //cerr << "ARI " << *trm << " " << b0 << endl;
  if(printDebug() > 1005)
    cerr << "EFIE " << trm->name() << " " << b0 << endl;
  /* If this is a terminal node, the rhs will be a word; otherwise it
     will be a rule expansion consisting of several Item s.
   */
  if(trm->terminal_p())
    {
      ECString tmpW1 = tree->word();
      char chars[512];
      ECString tmpW = toLower(tmpW1.c_str(), chars);
      
      int wInt = wtoInt(tmpW);
      Item* lhs = add_item(b0, trm, tree->start());
      lhs->start() = tree->start();
      lhs->finish() = tree->finish();
      Item* rhs = add_item2(b0, trm, wInt,tmpW);
      rhs->finish() = tree->finish();
      rhs->start() = tree->start();
      if(!lhs && !rhs)
	{
	  return NULL;
	}

      Items subItems;
      subItems.push_back(stops[tree->start()]);
      subItems.push_back(rhs);
      subItems.push_back(stops[tree->finish()]);
      Edge* edg = add_edge(lhs, subItems);
      if(!edg)
	{
	  return NULL;
	}
      edg->prob() = pHst(wInt,trm->toInt());
      edg->num() = b0;
      if(printDebug() > 5)
	cerr << "LHS " << *lhs << " " << tmpW  << edg->prob() << endl;
	  
      return lhs;
    }
  else
    {
      Item* lhs = add_item(b0, trm, -1);
      lhs->start() = tree->start();
      lhs->finish() = tree->finish();
      assert(lhs);
      Items subItems;
      subItems.push_back(stops[tree->start()]);
      InputTreesIter iti = tree->subTrees().begin();
      for( ; iti != tree->subTrees().end() ; iti++)
	{
	  InputTree* stree = (*iti);
	  cerr << "WBA "<< stree->term() << *stree   << endl;
	  Item* itm = edgesFromTree(stree);
	  if(!itm)
	    {
	      return NULL;
	    }
	  subItems.push_back(itm);
	}
      subItems.push_back(stops[tree->finish()]);
      Edge* edg = add_edge(lhs, subItems);
      if(!edg)
	{
	  return false;
	}
      edg->num() = b0;
      assignRProb(edg);
      if (printDebug() > 5)
	{
	  cerr << "Saw edge " << *edg << ": p=" << edg->prob() << endl;
	}
      //cerr << "endeFE " << *edg << endl;
      return lhs;
      rPendFactor();
    }
}
Exemple #7
0
void
Bchart::
extend_rule(Edge* edge, Item * item, int right)
{
    Edge*          newEdge = new Edge(*edge, *item, right);
    if(printDebug() > 140)
      cerr << "extend_rule " << *edge << " " << *item << endl;
    const Term* itemTerm = item->term();
    LeftRightGotIter lrgi(newEdge);
    globalGi = &lrgi;
	
    if(edge->loc() == edge->start())
      {
	newEdge->prob() *= meEdgeProb(item->term(), newEdge, MCALC); 
	/*stoprightp is p of stopping after seeing what currently
	  passes for the rhs of the edge */
	newEdge->rightMerit() = computeMerit(newEdge,RUCALC);
	delete edge; // just created;
      }
    else if(right)
      {
	newEdge->prob() *=     meEdgeProb(item->term(),newEdge, RCALC);
      }
    else newEdge->prob() *= meEdgeProb(item->term(),newEdge, LCALC);
    if(right)
      {
	newEdge->rightMerit()  = computeMerit(newEdge,RMCALC);
      }
    else
      {
	/* this is the left boundary stat for constituents that are
	   continuing left,  given the label and
	   whatever currently appears on the left boundary of the constit.
	   we only need this when going left */
	newEdge->leftMerit() = computeMerit(newEdge,LMCALC);
      }

    if(itemTerm == Term::stopTerm) newEdge->status() = right ? 2 : 1;

    if(newEdge->status() == 2) newEdge->prob() *= endFactorComp(newEdge);

    if(printDebug() > 250 )
      cerr << "Constructed " << *newEdge << "\t"
	<< newEdge->leftMerit() << "\t"
	  << newEdge->prob() << "\t" << newEdge->rightMerit() << endl;
    int tmp = curDemerits_[newEdge->start()][newEdge->loc()];
    newEdge->demerits() = tmp;
    if(repeatRule(newEdge))
      {
	newEdge->rightMerit() = 0;
      }
    newEdge->setmerit(); 
    //cerr << "DEM " << tmp << " " << newEdge->merit() << endl;
    globalGi = NULL;
    if(newEdge->merit() == 0)
      {
	assert(alreadyPopedNum < 450000);
	alreadyPoped[alreadyPopedNum++] = newEdge;
	Edge* prd = newEdge->pred();
	if(prd) prd->sucs().pop_front();
	return;
      }
    ++ruleiCounts_;
    heap->insert(newEdge);

    if(itemTerm != Term::stopTerm) item->needme().push_back(newEdge);
}
void main(void){
  SYSTEMConfigPerformance(10000000);
  STATE state = START;
  unsigned short int lineCount = 0;
  bool ignoreTurns = false;
  // Initialize Motor(s))
  Motor_Init();
  // Initialize IRSensor(s)
  IRSensor_Init();
  // LCD Initialize
  LCD_Init();
  while(1){
    printDebug(state);
    switch(state){
      case START:
        Motor_Disable();
        if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL))state = TRAVEL;
        break;
      case TRAVEL:
        Motor_Enable();
        if(IRSensor_CheckLeftFront(200)){
          state = TURN_LEFT;break;
        }else if(IRSensor_CheckRightFront(200)){
          state = TURN_RIGHT;break;
        }else if(IRSensor_GetCenterLeft() < 300 || IRSensor_GetCenterRight < 300){
          if(IRSensor_GetCenterLeft() > IRSensor_GetCenterRight()){
            Motor_Set1DutyCycle(0);
            Motor_Set2DutyCycle(STANDARD_DUTY_CYCLE);
          }else{
            Motor_Set1DutyCycle(STANDARD_DUTY_CYCLE);
            Motor_Set2DutyCycle(0);
          };
        }else if(IRSensor_GetCenterLeft() != IRSensor_GetCenterRight()){
          float biasValue = 1.0 + abs(IRSensor_GetCenterLeft() - IRSensor_GetCenterRight()) / 2000.0;
          if(IRSensor_GetCenterLeft() > IRSensor_GetCenterRight()){
            Motor_Set1DutyCycle(biasValue * STANDARD_DUTY_CYCLE);
            Motor_Set2DutyCycle(1.0/biasValue * STANDARD_DUTY_CYCLE);
          }else{
            Motor_Set1DutyCycle(1.0/biasValue * STANDARD_DUTY_CYCLE);
            Motor_Set2DutyCycle(biasValue * STANDARD_DUTY_CYCLE);
          };
        }else{
          Motor_Set1DutyCycle(STANDARD_DUTY_CYCLE);
          Motor_Set2DutyCycle(STANDARD_DUTY_CYCLE);
        };
        break;
      case TURN_LEFT:
        if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL)){
          Motor_Disable();
          state = TRAVEL;
        }else{
          Motor_Set1DutyCycle(0.0);
          Motor_Set2DutyCycle(STANDARD_DUTY_CYCLE * MOTOR_BIAS_TURN);
          Motor_Enable();
        };
        break;
      case TURN_RIGHT:
        if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL)){
          Motor_Disable();
          state = TRAVEL;
        }else{
          Motor_Set1DutyCycle(STANDARD_DUTY_CYCLE * MOTOR_BIAS_TURN);
          Motor_Set2DutyCycle(0.0);
          Motor_Enable();
        };
        break;
    };
  };
};
Bst&
MeChart::
bestParseGivenHead(int posInt, const Wrd& wd, Item* itm,
		   FullHist* h, ItmGHeadInfo& ighInfo, Val* cval, Val* gcval)
{
  EdgeSet& es = ighInfo.first;
  BstMap&  atm = ighInfo.second;
  curVal = cval;
  gcurVal = gcval;
  Bst& bst = recordedBPGH(itm, atm, h);
  if(bst.explored())
    {
      if(printDebug() > 19)
	{
	  int subfv[MAXNUMFS];
	  getHt(h, subfv);
	  CntxArray ca(subfv);
	  prDp();
	  cerr << "bpknown for " << posInt << ", " << wd
	       << ", " << *itm << ") : " << bst.prob() << " " << ca <<endl;
	}
      curVal=gcurVal=NULL;
      return bst;
    }
  bst.explored() = true;
  curVal=gcurVal=NULL;
  const Term* trm = itm->term();
  if(trm->terminal_p())
    {
      Val* nval = new Val;
      nval->prob() = 1;
      nval->trm1() = itm->term()->toInt();
      nval->wrd1() = itm->word()->toInt();
      nval->status = TERMINALVAL;
      bst.addnth(nval);
      bst.sum() = nval->prob();
      return bst;
    }
  if(printDebug() > 10)
    {
      prDp();
      cerr << "bestParseGivenHead(" << posInt << ", " << wd
	   << ", " << *itm  << ")" << endl;
    }
  double bestP = 0;
  double sumP = 0;
  EdgeSetIter ei = es.begin();
  for( ; ei != es.end() ; ei++)
    {
      Edge* e = *ei;
      if(!sufficiently_likely(e))
	{
	  continue;
	}

      float edgePg = 1;
      int finish = e->loc();

      int effVal = effEnd(finish);
      if(itm->term()->isRoot()) edgePg = 1;
      else if(Feature::isLM) edgePg == 1;
      else if(effVal == 1)
	edgePg = endFactor;
      else if(effVal == 0) edgePg = midFactor;
      h->e = e;
      if(printDebug() > 20)
	{
	  prDp();
	  cerr << "consid " << *e << endl;
	}
      
      gcurVal = gcval;
      float prob = meRuleProb(e,h);
      gcurVal=NULL;
 
      double nextP = prob * edgePg;
      double nextPs = nextP;
      Item* sitm;
      //LeftRightGotIter gi(e); 
      MiddleOutGotIter gi(e);
      Val* val = new Val(e, nextPs);
      val->trm1() = itm->term()->toInt();
      val->wrd1() = wd.toInt();
      int pos = 0;
      depth++;
      h = h->extendByEdge(e);
      bool zeroProb = false;
      while( gi.next(sitm,pos) )
	{
	  //cerr << "Looking at " << *sitm << endl;
	  if(zeroProb)
	    {
	      h = h->extendBySubConstit();
	      continue;
	    }
	  if(sitm->term() == Term::stopTerm)
	    {
	      h = h->extendBySubConstit(); 
	      continue;
	    }
	  if(pos == 0)
	    {
	      h->preTerm = posInt; 
	      h->hd = &wd;
	      ItmGHeadInfo& ighi = sitm->posAndheads()[posInt][wd]; 
	      Bst&
		bst2 = bestParseGivenHead(posInt,wd,sitm,h,ighi,val,cval);
              curVal = gcurVal = NULL;
              curDir = -1;
	      if(bst2.empty())
		{
		  zeroProb = true;
		}
              val->extendTrees(bst2,pos); 
              nextPs *= bst2.sum();

	    }
	  else
	    {
	      Bst& bst2 = bestParse(sitm,h,val,cval,pos);
	      if(bst2.empty())
		{
		  zeroProb = true;
		}
              val->extendTrees(bst2,pos); 
              nextPs *= bst2.sum();
	    }
	  if(printDebug() > 39)
	    {
	      prDp();
	      cerr << "FullHist from " << *h;
	    }
	  h = h->extendBySubConstit(); 
	  if(printDebug() > 39)
	    cerr << " -> " << *h << endl;
	}
      if(!zeroProb) bst.push(val);
      if(printDebug() > 20)
	{
	  prDp();
	  cerr << "P(" << *e << " | " << wd << " ) = " ;
	  cerr << bestP;
	  cerr << "\n"; 
	}
      depth--;
      sumP += nextPs;
      h->retractByEdge(); 
      if(printDebug() > 20)
        {
          prDp();
          cerr << "Val: " << *val << endl;
        }
    }
  Val* vbest = bst.pop();
  if(vbest) bst.addnth(vbest);
  bst.sum() = sumP;
  if(printDebug() > 10)
    {
      prDp();
      cerr << "Bestpgh for "<<*itm << ", " << wd << " = " << bst.prob()<< endl;
    }
  return bst;
}
Exemple #10
0
void CModem::clock(unsigned int ms)
{
	// Poll the modem status every 100ms
	m_statusTimer.clock(ms);
	if (m_statusTimer.hasExpired()) {
		readStatus();
		m_statusTimer.start();
	}

	unsigned int length;
	RESP_TYPE_MMDVM type = getResponse(m_buffer, length);

	if (type == RTM_TIMEOUT) {
		// Nothing to do
	} else if (type == RTM_ERROR) {
		LogError("Error when reading from the MMDVM");
	} else {
		// type == RTM_OK
		switch (m_buffer[2U]) {
			case MMDVM_DSTAR_HEADER: {
					if (m_debug)
						CUtils::dump(1U, "RX D-Star Header", m_buffer, length);

					unsigned char data = length - 2U;
					m_rxDStarData.addData(&data, 1U);

					data = TAG_HEADER;
					m_rxDStarData.addData(&data, 1U);

					m_rxDStarData.addData(m_buffer + 3U, length - 3U);
				}
				break;

			case MMDVM_DSTAR_DATA: {
					if (m_debug)
						CUtils::dump(1U, "RX D-Star Data", m_buffer, length);

					unsigned char data = length - 2U;
					m_rxDStarData.addData(&data, 1U);

					data = TAG_DATA;
					m_rxDStarData.addData(&data, 1U);

					m_rxDStarData.addData(m_buffer + 3U, length - 3U);
				}
				break;

			case MMDVM_DSTAR_LOST: {
					if (m_debug)
						CUtils::dump(1U, "RX D-Star Lost", m_buffer, length);

					unsigned char data = 1U;
					m_rxDStarData.addData(&data, 1U);

					data = TAG_LOST;
					m_rxDStarData.addData(&data, 1U);
				}
				break;

			case MMDVM_DSTAR_EOT: {
					if (m_debug)
						CUtils::dump(1U, "RX D-Star EOT", m_buffer, length);

					unsigned char data = 1U;
					m_rxDStarData.addData(&data, 1U);

					data = TAG_EOT;
					m_rxDStarData.addData(&data, 1U);
				}
				break;

			case MMDVM_DMR_DATA1: {
					if (m_debug)
						CUtils::dump(1U, "RX DMR Data 1", m_buffer, length);

					unsigned char data = length - 2U;
					m_rxDMRData1.addData(&data, 1U);

					if (m_buffer[3U] == (DMR_SYNC_DATA | DT_TERMINATOR_WITH_LC))
						data = TAG_EOT;
					else
						data = TAG_DATA;
					m_rxDMRData1.addData(&data, 1U);

					m_rxDMRData1.addData(m_buffer + 3U, length - 3U);
				}
				break;

			case MMDVM_DMR_DATA2: {
					if (m_debug)
						CUtils::dump(1U, "RX DMR Data 2", m_buffer, length);

					unsigned char data = length - 2U;
					m_rxDMRData2.addData(&data, 1U);

					if (m_buffer[3U] == (DMR_SYNC_DATA | DT_TERMINATOR_WITH_LC))
						data = TAG_EOT;
					else
						data = TAG_DATA;
					m_rxDMRData2.addData(&data, 1U);

					m_rxDMRData2.addData(m_buffer + 3U, length - 3U);
				}
				break;

			case MMDVM_DMR_LOST1: {
					if (m_debug)
						CUtils::dump(1U, "RX DMR Lost 1", m_buffer, length);

					unsigned char data = 1U;
					m_rxDMRData1.addData(&data, 1U);

					data = TAG_LOST;
					m_rxDMRData1.addData(&data, 1U);
				}
				break;

			case MMDVM_DMR_LOST2: {
					if (m_debug)
						CUtils::dump(1U, "RX DMR Lost 2", m_buffer, length);

					unsigned char data = 1U;
					m_rxDMRData2.addData(&data, 1U);

					data = TAG_LOST;
					m_rxDMRData2.addData(&data, 1U);
				}
				break;

			case MMDVM_YSF_DATA: {
					if (m_debug)
						CUtils::dump(1U, "RX YSF Data", m_buffer, length);

					unsigned char data = length - 2U;
					m_rxYSFData.addData(&data, 1U);

					if ((m_buffer[3U] & (YSF_CKSUM_OK | YSF_FI_MASK)) == (YSF_CKSUM_OK | YSF_DT_TERMINATOR_CHANNEL))
						data = TAG_EOT;
					else
						data = TAG_DATA;
					m_rxYSFData.addData(&data, 1U);

					m_rxYSFData.addData(m_buffer + 3U, length - 3U);
				}
				break;

			case MMDVM_YSF_LOST: {
					if (m_debug)
						CUtils::dump(1U, "RX YSF Lost", m_buffer, length);

					unsigned char data = 1U;
					m_rxYSFData.addData(&data, 1U);

					data = TAG_LOST;
					m_rxYSFData.addData(&data, 1U);
				}
				break;

			case MMDVM_GET_STATUS: {
					// if (m_debug)
					//	CUtils::dump(1U, "GET_STATUS", m_buffer, length);

					m_tx = (m_buffer[5U] & 0x01U) == 0x01U;

					bool adcOverflow = (m_buffer[5U] & 0x02U) == 0x02U;
					if (adcOverflow)
						LogError("MMDVM ADC levels have overflowed");

					bool rxOverflow = (m_buffer[5U] & 0x04U) == 0x04U;
					if (rxOverflow)
						LogError("MMDVM RX buffer has overflowed");

					bool txOverflow = (m_buffer[5U] & 0x08U) == 0x08U;
					if (txOverflow)
						LogError("MMDVM TX buffer has overflowed");

					m_dstarSpace = m_buffer[6U];
					m_dmrSpace1  = m_buffer[7U];
					m_dmrSpace2  = m_buffer[8U];
					m_ysfSpace   = m_buffer[9U];
					// LogMessage("status=%02X, tx=%d, space=%u,%u,%u,%u", m_buffer[5U], int(m_tx), m_dstarSpace, m_dmrSpace1, m_dmrSpace2, m_ysfSpace);
				}
				break;

			// These should not be received, but don't complain if we do
			case MMDVM_GET_VERSION:
			case MMDVM_ACK:
				break;

			case MMDVM_NAK:
				LogWarning("Received a NAK from the MMDVM, command = 0x%02X, reason = %u", m_buffer[3U], m_buffer[4U]);
				break;

			case MMDVM_DEBUG1:
			case MMDVM_DEBUG2:
			case MMDVM_DEBUG3:
			case MMDVM_DEBUG4:
			case MMDVM_DEBUG5:
				printDebug();
				break;

			case MMDVM_SAMPLES:
				// printSamples();
				break;

			default:
				LogMessage("Unknown message, type: %02X", m_buffer[2U]);
				CUtils::dump("Buffer dump", m_buffer, length);
				break;
		}
	}

	if (m_dstarSpace > 1U && !m_txDStarData.isEmpty()) {
		unsigned char buffer[4U];
		m_txDStarData.peek(buffer, 4U);

		if ((buffer[3U] == MMDVM_DSTAR_HEADER && m_dstarSpace > 4U) ||
			(buffer[3U] == MMDVM_DSTAR_DATA   && m_dstarSpace > 1U) ||
			(buffer[3U] == MMDVM_DSTAR_EOT    && m_dstarSpace > 1U)) {
			unsigned char len = 0U;
			m_txDStarData.getData(&len, 1U);
			m_txDStarData.getData(m_buffer, len);

			if (m_debug) {
				switch (buffer[3U]) {
				case MMDVM_DSTAR_HEADER:
					CUtils::dump(1U, "TX D-Star Header", m_buffer, len);
					m_dstarSpace -= 4U;
					break;
				case MMDVM_DSTAR_DATA:
					CUtils::dump(1U, "TX D-Star Data", m_buffer, len);
					m_dstarSpace -= 1U;
					break;
				default:
					CUtils::dump(1U, "TX D-Star EOT", m_buffer, len);
					m_dstarSpace -= 1U;
					break;
				}
			}

			int ret = m_serial.write(m_buffer, len);
			if (ret != int(len))
				LogWarning("Error when writing D-Star data to the MMDVM");
		}
	}

	if (m_dmrSpace1 > 1U && !m_txDMRData1.isEmpty()) {
		unsigned char len = 0U;
		m_txDMRData1.getData(&len, 1U);
		m_txDMRData1.getData(m_buffer, len);

		if (m_debug)
			CUtils::dump(1U, "TX DMR Data 1", m_buffer, len);

		int ret = m_serial.write(m_buffer, len);
		if (ret != int(len))
			LogWarning("Error when writing DMR data to the MMDVM");

		m_dmrSpace1--;
	}

	if (m_dmrSpace2 > 1U && !m_txDMRData2.isEmpty()) {
		unsigned char len = 0U;
		m_txDMRData2.getData(&len, 1U);
		m_txDMRData2.getData(m_buffer, len);

		if (m_debug)
			CUtils::dump(1U, "TX DMR Data 2", m_buffer, len);

		int ret = m_serial.write(m_buffer, len);
		if (ret != int(len))
			LogWarning("Error when writing DMR data to the MMDVM");

		m_dmrSpace2--;
	}

	if (m_ysfSpace > 1U && !m_txYSFData.isEmpty()) {
		unsigned char len = 0U;
		m_txYSFData.getData(&len, 1U);
		m_txYSFData.getData(m_buffer, len);

		if (m_debug)
			CUtils::dump(1U, "TX YSF Data", m_buffer, len);

		int ret = m_serial.write(m_buffer, len);
		if (ret != int(len))
			LogWarning("Error when writing YSF data to the MMDVM");

		m_ysfSpace--;
	}
}
Exemple #11
0
void KoGenStyle::writeStyle(KoXmlWriter* writer, const KoGenStyles& styles, const char* elementName, const QString& name, const char* propertiesElementName, bool closeElement, bool drawElement) const
{
    //debugOdf <<"writing out style" << name <<" display-name=" << m_attributes["style:display-name"] <<" family=" << m_familyName;
    writer->startElement(elementName);
    const KoGenStyle* parentStyle = 0;
    if (!m_defaultStyle) {
        if (!drawElement)
            writer->addAttribute("style:name", name);
        else
            writer->addAttribute("draw:name", name);
        if (!m_parentName.isEmpty()) {
            Q_ASSERT(!m_familyName.isEmpty());
            parentStyle = styles.style(m_parentName, m_familyName);
            if (parentStyle && m_familyName.isEmpty()) {
                // get family from parent style, just in case
                // Note: this is saving code, don't convert to attributeNS!
                const_cast<KoGenStyle *>(this)->
                m_familyName = parentStyle->attribute("style:family").toLatin1();
                //debugOdf <<"Got familyname" << m_familyName <<" from parent";
            }
            if (parentStyle && !parentStyle->isDefaultStyle())
                writer->addAttribute("style:parent-style-name", m_parentName);
        }
    } else { // default-style
        Q_ASSERT(qstrcmp(elementName, "style:default-style") == 0);
        Q_ASSERT(m_parentName.isEmpty());
    }
    if (!m_familyName.isEmpty())
        const_cast<KoGenStyle *>(this)->
        addAttribute("style:family", QString::fromLatin1(m_familyName));
    else {
        if (qstrcmp(elementName, "style:style") == 0)
            warnOdf << "User style " << name << " is without family - invalid. m_type=" << m_type;
    }

#if 0 // #ifndef NDEBUG
    debugOdf << "style:" << name;
    printDebug();
    if (parentStyle) {
        debugOdf << " parent:" << m_parentName;
        parentStyle->printDebug();
    }
#endif

    // Write attributes [which differ from the parent style]
    // We only look at the direct parent style because we assume
    // that styles are fully specified, i.e. the inheritance is
    // only in the final file, not in the caller's code.
    QMap<QString, QString>::const_iterator it = m_attributes.constBegin();
    for (; it != m_attributes.constEnd(); ++it) {
        bool writeit = true;
        if (parentStyle && it.key() != "style:family"  // always write the family out
                && parentStyle->attribute(it.key()) == it.value())
            writeit = false;
        if (writeit)
            writer->addAttribute(it.key().toUtf8(), it.value().toUtf8());
    }
    bool createPropertiesTag = propertiesElementName && propertiesElementName[0] != '\0';
    KoGenStyle::PropertyType i = KoGenStyle::DefaultType;
    KoGenStyle::PropertyType defaultPropertyType = KoGenStyle::DefaultType;
    if (createPropertiesTag)
        defaultPropertyType = propertyTypeByElementName(propertiesElementName);
    if (!m_properties[i].isEmpty() ||
            !m_childProperties[defaultPropertyType].isEmpty() ||
            !m_properties[defaultPropertyType].isEmpty()) {
        if (createPropertiesTag)
            writer->startElement(propertiesElementName);   // e.g. paragraph-properties
        it = m_properties[i].constBegin();
        for (; it != m_properties[i].constEnd(); ++it) {
            if (!parentStyle || parentStyle->property(it.key(), i) != it.value())
                writer->addAttribute(it.key().toUtf8(), it.value().toUtf8());
        }
        //write the explicitly-defined properties that are the same type as the default,
        //but only if defaultPropertyType is Text, Paragraph, or GraphicType
        if (defaultPropertyType != 0) {
            it = m_properties[defaultPropertyType].constBegin();
            for (; it != m_properties[defaultPropertyType].constEnd(); ++it) {
                if (!parentStyle || parentStyle->property(it .key(), defaultPropertyType) != it.value())
                    writer->addAttribute(it.key().toUtf8(), it.value().toUtf8());
            }
        }
        //write child elements of the properties elements
        it = m_childProperties[defaultPropertyType].constBegin();
        for (; it != m_childProperties[defaultPropertyType].constEnd(); ++it) {
            if (!parentStyle || parentStyle->childProperty(it.key(), defaultPropertyType) != it.value()) {
                writer->addCompleteElement(it.value().toUtf8());
            }
        }
        if (createPropertiesTag)
            writer->endElement();
    }

    // now write out any other properties elements
    //start with i=1 to skip the defaultType that we already took care of
    for (int i = 1; i < s_propertyNamesCount; ++i) {
        //skip any properties that are the same as the defaultType
        if (s_propertyTypes[i] != defaultPropertyType) {
            writeStyleProperties(writer, s_propertyTypes[i], parentStyle);
        }
    }

    //write child elements that aren't in any of the properties elements
    i = KoGenStyle::StyleChildElement;
    it = m_properties[i].constBegin();
    for (; it != m_properties[i].constEnd(); ++it) {
        if (!parentStyle || parentStyle->property(it.key(), i) != it.value()) {
            writer->addCompleteElement(it.value().toUtf8());
        }
    }

    // And now the style maps
    for (int i = 0; i < m_maps.count(); ++i) {
        bool writeit = true;
        if (parentStyle && compareMap(m_maps[i], parentStyle->m_maps[i]) == 0)
            writeit = false;
        if (writeit) {
            writer->startElement("style:map");
            QMap<QString, QString>::const_iterator it = m_maps[i].constBegin();
            for (; it != m_maps[i].constEnd(); ++it) {
                writer->addAttribute(it.key().toUtf8(), it.value().toUtf8());
            }
            writer->endElement(); // style:map
        }
    }
    if (closeElement)
        writer->endElement();
}
Exemple #12
0
/*
 * main for testing
 */
int main (int argc, char **argv)
{
    Bool success = true;
    UInt8 i;
    UInt8 x;
    SInt32 portNumber = 0;
    UInt8 numBatteryDevices;
    UInt8 numIODevices;
    UInt8 batteryDeviceArray[MAX_BATTERY_DEVICES][NUM_BYTES_IN_SERIAL_NUM];
    UInt8 ioDeviceArray[MAX_IO_DEVICES][NUM_BYTES_IN_SERIAL_NUM];
    UInt8 pageBuffer[DS2408_MAX_BYTES_IN_CHANNEL_ACCESS];
    SInt16 current;
    double temperature;
    UInt16 voltage;
    SInt16 offsetCalibration;

    setDebugPrintsOn();
    setProgressPrintsOn();

    if (argc == 2)
    {
        portNumber = oneWireStartBus (argv[1]);
    }
    else
    {
        portNumber = oneWireStartBus (ONEWIRE_PORT);
    }

    if (portNumber < 0)
    {
        printDebug ("Failed to acquire port.\n");
        success = false;
    }
    else
    {  
        numBatteryDevices = FindDevices (portNumber, &batteryDeviceArray[0], FAMILY_SBATTERY, MAX_BATTERY_DEVICES);
        numIODevices = FindDevices (portNumber, &ioDeviceArray[0], FAMILY_PIO, MAX_IO_DEVICES);

        if (numBatteryDevices == 0)
        {
            success = false;
            ASSERT_ALWAYS_STRING ("No battery monitoring devices found.\n");
        }
        else
        {
            printProgress ("Found %d battery monitoring devices.\n", numBatteryDevices);
            for (i = 0; (i < numBatteryDevices) && success; i++)
            {
                UInt32 longOne1 = 0xFFFFFF01;
                UInt32 longOne2 = 0xFFFFFF02;
                UInt16 capacity = 1000;                
                
                printProgress ("Writing time %lu and capacity %d.\n", longOne1, capacity);
                success = writeTimeCapacityDS2438 (portNumber, &batteryDeviceArray[i][0], &longOne1, &capacity, false);
                if (success)
                {
                    printProgress ("Writing something to DISC/EOC page.\n");
                    pageBuffer[0] = 0xFF;
                    pageBuffer[1] = 0xFF;
                    pageBuffer[2] = 0xFF;
                    pageBuffer[3] = 0xFF;
                    pageBuffer[4] = 0xFF;
                    pageBuffer[5] = 0xFF;
                    pageBuffer[6] = 0xFF;
                    pageBuffer[7] = 0xFF;
        
                    success = writeNVPageDS2438 (portNumber, &batteryDeviceArray[i][0], 2, &pageBuffer[0], DS2438_NUM_BYTES_IN_PAGE);
                    if (success)
                    {
                        printProgress ("Writing something to CCA and DCA registers.\n");
                        success = writeNVChargeDischargeDS2438 (portNumber, &batteryDeviceArray[i][0], &longOne1, &longOne2);
                        
                        if (success)
                        {
                            printProgress ("Writing something to user data pages.\n");
                            for (x = 0; (x < DS2438_NUM_USER_DATA_PAGES) && success; x++)
                            {
                                pageBuffer[0] = x + 1;
                                pageBuffer[1] = x + 2;
                                pageBuffer[2] = x + 3;
                                pageBuffer[3] = x + 4;
                                pageBuffer[4] = x + 5;
                                pageBuffer[5] = x + 6;
                                pageBuffer[6] = x + 7;
                                pageBuffer[7] = x + 8;
                                success = writeNVUserDataDS2438 (portNumber, &batteryDeviceArray[i][0], x, &pageBuffer[0], (x + 1) * 2);
                            }
                            
                            if (success)
                            {
#if 0
                                printProgress ("Calibrating: MAKE SURE NO CURRENT GOING THROUGH RSENS!\n");
                                success = performCalDS2438 (portNumber, &batteryDeviceArray[i][0], &offsetCalibration);
                                printProgress ("New offset %d.\n", offsetCalibration);
#endif                                
                            }
                        }
                    }
                }
            }
            /* Check that the configurations are setup correctly and if
             * not write in the values we need and flush them to NV so
             * that they will be correct next time */
            for (i = 0; (i < numBatteryDevices) && success; i++)
            {
                UInt8 config;
                
                success = readNVConfigThresholdDS2438 (portNumber, &batteryDeviceArray[i][0], &config, PNULL);
                if (success &&
                    ((config | DS2438_IAD_IS_ENABLED) == 0 ||
                     (config | DS2438_CA_IS_ENABLED) == 0 ||
                     (config | DS2438_EE_IS_ENABLED) == 0))
                {
                    config = DS2438_IAD_IS_ENABLED | DS2438_CA_IS_ENABLED | DS2438_EE_IS_ENABLED;
                    success = writeNVConfigThresholdDS2438 (portNumber, &batteryDeviceArray[i][0], &config, PNULL);                        
                }
            }
        } /* numBatteryDevices > 0 */
        
        if (numIODevices == 0)
        {
            success = false;
            ASSERT_ALWAYS_STRING ("No IO devices found.\n");
        }
        else
        {
            printProgress ("Found %d IO devices.\n", numIODevices);
            for (i = 0; (i < numIODevices) && success; i++)
            {              
                UInt8 controlByte = 0;
                
                printProgress ("Disable test mode.\n");
                success = disableTestModeDS2408 (portNumber, &ioDeviceArray[i][0]);
                if (success)
                {
                    printProgress ("Reset activity latches.\n");
                    success = resetActivityLatchesDS2408 (portNumber, &ioDeviceArray[i][0]);
                    if (success)
                    {
                        controlByte &= ~(DS2408_DEVICE_HAS_POWER_ON_RESET | DS2408_RSTZ_IS_STROBE);
                        controlByte |= (DS2408_SEARCH_IS_AND | DS2408_SEARCH_IS_ACTIVITY_LATCHED);
                        printProgress ("Setup the control registers.\n");
                        success = writeControlRegisterDS2408 (portNumber, &ioDeviceArray[i][0], controlByte);
                        if (success)
                        {
                            printProgress ("Setup the conditional search channel selection mask registers.\n");
                            success = writeCSChannelSelectionMaskRegisterDS2408 (portNumber, &ioDeviceArray[i][0], 0x18);                        
                            if (success)
                            {
                                printProgress ("Setup the conditional search channel priority selection registers.\n");
                                success = writeCSChannelPolaritySelectionRegisterDS2408 (portNumber, &ioDeviceArray[i][0], 0x28);                        
                                if (success)
                                {
                                    UInt8 outputByte = 0x80;
                                    
                                    printProgress ("Set P7 of each device to be high.\n");
                                    success = channelAccessWriteDS2408 (portNumber, &ioDeviceArray[i][0], &outputByte);                        
                                }
                            }
                        }
                    }
                }
            }
        }  /* numIODevices > 0 */
                
        if (success)
        {
            do
            {
                printProgress("---- IO Devices ---- \n");
                for (i = 0; (i < numIODevices) && success; i++)
                {
                    printProgress ("Device %d, address %.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", i, ioDeviceArray[i][0], ioDeviceArray[i][1], ioDeviceArray[i][2], ioDeviceArray[i][3], ioDeviceArray[i][4], ioDeviceArray[i][5], ioDeviceArray[i][6], ioDeviceArray[i][7]);
                    success = readControlRegisterDS2408 (portNumber, &ioDeviceArray[i][0], &pageBuffer[0]);
                    if (success)
                    {
                        printProgress (" status reg: 0x%.2x", pageBuffer[0]);
                        success = readPIOLogicStateDS2408 (portNumber, &ioDeviceArray[i][0], &pageBuffer[0]);
                        if (success)
                        {
                            printProgress (", IO reg: 0x%.2x", pageBuffer[0]);
                            success = readPIOOutputLatchStateRegisterDS2408 (portNumber, &ioDeviceArray[i][0], &pageBuffer[0]);
                            if (success)
                            {
                                UInt8 bytesRead;
                                
                                printProgress (", IO O/P latch reg: 0x%.2x", pageBuffer[0]);
                                bytesRead = channelAccessReadDS2408 (portNumber, &ioDeviceArray[i][0], &pageBuffer[0], DS2408_MAX_BYTES_IN_CHANNEL_ACCESS);                                    
                                if (bytesRead > 0)
                                {
                                    printProgress (", IO %d times: ", bytesRead);
                                    for (x = 0; x < bytesRead; x++)
                                    {
                                        printProgress (" 0x%.2x", pageBuffer[x]);                                            
                                    }
                                    success = readCSChannelSelectionMaskRegisterDS2408 (portNumber, &ioDeviceArray[i][0], &pageBuffer[0]);
                                    if (success)
                                    {
                                        printProgress (", CS select reg: 0x%.2x", pageBuffer[0]);
                                        success = readCSChannelPolaritySelectionRegisterDS2408 (portNumber, &ioDeviceArray[i][0], &pageBuffer[0]);
                                        if (success)
                                        {
                                            printProgress (", CS polarity reg: 0x%.2x.\n", pageBuffer[0]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    printProgress("\n");
                } /* IO Devices for loop */
                
                printProgress("---- Battery Devices ---- \n");
                for (i = 0; (i < numBatteryDevices) && success; i++)
                {
                    printProgress ("Device %d, address %.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n", i, batteryDeviceArray[i][0], batteryDeviceArray[i][1], batteryDeviceArray[i][2], batteryDeviceArray[i][3], batteryDeviceArray[i][4], batteryDeviceArray[i][5], batteryDeviceArray[i][6], batteryDeviceArray[i][7]);
                    success = readVddDS2438 (portNumber, &batteryDeviceArray[i][0], &voltage);
                    if (success)
                    {
                        printProgress (" Vdd was:  %d mV\n", voltage);
                        success = readVadDS2438 (portNumber, &batteryDeviceArray[i][0], &voltage);
                        if (success)
                        {
                            printProgress (" Vad was:  %d mV\n", voltage);
                            success = readTemperatureDS2438 (portNumber, &batteryDeviceArray[i][0], &temperature);
                            if (success)
                            {
                                printProgress (" Temperature was:  %2.2f C\n", temperature);
                                success = readCurrentDS2438 (portNumber, &batteryDeviceArray[i][0], &current);
                                if (success)
                                {
                                    printProgress (" Current was:  %d ma (-ve means discharge)\n", current);
                                    success = readBatteryDS2438 (portNumber, &batteryDeviceArray[i][0], &voltage, &current);
                                    if (success)
                                    {
                                        printProgress ("Battery was %2.2f V, %1.3f A, %2.3f W\n", (double) voltage/1000, (double) current/1000, ((double) (voltage *  current * -1)) / 1000000);
                                    }
                                }
                            }
                            for (x = 0; (x < 8) && success; x++)
                            {
                                success = readNVPageDS2438 (portNumber, &batteryDeviceArray[i][0], x, &pageBuffer[0]);
                                printProgress ("Page %d contents: %2x:%2x:%2x:%2x:%2x:%2x:%2x:%2x\n", x, pageBuffer[0], pageBuffer[1], pageBuffer[2], pageBuffer[3], pageBuffer[4], pageBuffer[5], pageBuffer[6], pageBuffer[7]);
                            }
                        }
                    }
                    
                    /* Check other data */
                    if (success)
                    {
                        UInt32 elapsedTime;
                        UInt16 remainingCapacity;
                        UInt32 piOff;
                        UInt32 chargingStopped;
                        UInt32 accumulatedCharge;
                        UInt32 accumulatedDischarge;
                        
                        success = readTimeCapacityCalDS2438 (portNumber, &batteryDeviceArray[i][0], &elapsedTime, &remainingCapacity, &offsetCalibration, false);
                        if (success)
                        {
                            printProgress ("Elapsed time: %lu secs, remaining capacity: %u mAHr, cal. offset: %d\n", elapsedTime, remainingCapacity, offsetCalibration);
                            success = readTimePiOffChargingStoppedDS2438 (portNumber, &batteryDeviceArray[i][0], &piOff, &chargingStopped);
                            if (success)
                            {
                                printProgress ("Pi last switched off: %lu secs, charging last stopped: %lu secs\n", piOff, chargingStopped);                                
                                success = readNVChargeDischargeDS2438 (portNumber, &batteryDeviceArray[i][0], &accumulatedCharge, &accumulatedDischarge);
                                if (success)
                                {
                                    printProgress ("Accumulated charge: %lu mAHr, accumulated discharge %lu mAHr\n", accumulatedCharge, accumulatedDischarge);
                                    for (x = 0; (x < DS2438_NUM_USER_DATA_PAGES) && success; x++)
                                    {
                                        success = readNVUserDataDS2438 (portNumber, &batteryDeviceArray[i][0], x, &pageBuffer[0]);
                                        if (success)
                                        {
                                            printProgress ("UserData %d contents: %2x:%2x:%2x:%2x:%2x:%2x:%2x:%2x\n", x, pageBuffer[0], pageBuffer[1], pageBuffer[2], pageBuffer[3], pageBuffer[4], pageBuffer[5], pageBuffer[6], pageBuffer[7]);
                                        }
                                    }
                                }
                            }                            
                        }
                    }                    
                    printProgress("\n");
                } /* Battery devices for loop */
            } while (!key_abort() && success);
        }
        
        if (!success)
        {
            printDebug ("Either something returned false or at least one IO device and at least one Battery device were not found.\n");
        }
    
        oneWireStopBus (portNumber);
        printProgress ("Port released.\n");    
    }

    return success;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Pop the children from the stack and check for correct type and sequence of children
/// This is the end handler of parser. The parser ends here.
///
///\param context
///\param elm 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void XMLCALL endElement(void *context, const char *elm) {
    Elm el;
    el = checkElement(elm);
    printfDebug(" **** ending element %s.\n", elmNames[el]);
    switch(el) {        
        case elm_fmiModelDescription: 
            {
                 ModelDescription* md;
                 ListElement** im = NULL;  		//  NULL or list of CoSimulation_StandAlone under Implementation
                 ListElement** ud = NULL;     	//  NULL or list of BaseUnits under UnitDefinitions
                 Type**        td = NULL;     	//  NULL or list of Types under TypeDefinitions
                 Element*      de = NULL;     	// NULL or DefaultExperiment
                 ListElement** va = NULL;     	// NULL or list of Tools
                 ScalarVariable** mv = NULL;  	// NULL or list of ScalarVariables under ModelVariables
                 ListElement* child;
                 printDebug("$$$$$ entered endElement 'elm_fmiModelDescription'\n");
                 child = checkPop(ANY_TYPE); // get a child from stack

                 while (child && child->type != elm_fmiModelDescription)  // add while-loop in case the elements in the random order
                 {
					 if (child->type == elm_VendorAnnotations){
						 va = (ListElement**)child->list;    // VendorAnnotations (ListElement) contains Tool (ListElement))
						 free(child);
						 child = checkPop(ANY_TYPE);
						 if (!child) return;
					 }
					 if (child->type == elm_DefaultExperiment){
						 de = (Element*)child;				// DefaultExperiment (Element) with only attributes
						 child = checkPop(ANY_TYPE);
						 if (!child) return;
					 }
					 if (child->type == elm_TypeDefinitions){
						 td = (Type**)child->list;     		// TypeDefinitions (ListElement) contains Type (Type)
						 free(child);
						 child = checkPop(ANY_TYPE);
						 if (!child) return;
					 }
					 if (child->type == elm_UnitDefinitions){
						 ud = (ListElement**)child->list;   // UnitDefinitions (ListElement) contains BaseUnit (ListElement)
						 free(child);
						 child = checkPop(ANY_TYPE);
						 if (!child) return;
					 }
					 if (child->type == elm_Implementation){ 	// Implementation is listElement, it can be treated the same as UnitDefinitions
						 im = (ListElement**)child->list; 		// Implementation (Implementation) contains CoSimulation_StandAlone (ListElement)
						 free(child);							// Zuo:
						 child = checkPop(ANY_TYPE);			// Zuo:
						 if (!child) return;					// Zuo:
					 }											// Zuo:
					 if (child->type == elm_ModelVariables){
						  mv = (ScalarVariable**)child->list;  // ModelVariables (ListElement) contains ScalarVariable (ScalarVariable)
						  free(child);
						  child = checkPop(ANY_TYPE);
						  if (!child) return;
					 }
                 }
		         printDebug("$$$$$ checking element type \n");
                 if (checkElementType(child, elm_fmiModelDescription)) return;
                 printDebug("$$$$$ checked  element type \n");
                 md = (ModelDescription*)child;

                 // the following build the link of elements for ModelDescriptions
                 md->modelVariables = mv;
                 md->implementation = im; // added M. Wetter
                 md->vendorAnnotations = va;
                 md->defaultExperiment = de;
                 md->typeDefinitions = td;
                 md->unitDefinitions = ud;
                 printDebug("$$$$$ calling stackPush \n");
                 stackPush(stack, md);
                 printDebug("$$$$$ called stackPush \n");
                 break;
            }
        case elm_Type:
            {
                Type* tp;
                Element* ts = checkPop(ANY_TYPE);
                if (!ts) return;  // If there is no sub-element, return
                if (checkPeek(elm_Type)) return; // If the sub-element is not Type, return
                tp = (Type*)stackPeek(stack);  // Get the element
                switch (ts->type) {
                    case elm_RealType:
                    case elm_IntegerType:
                    case elm_BooleanType:
                    case elm_EnumerationType:
                    case elm_StringType:
                        break;
                    default: 		// Element type does not match
                         logFatalTypeError("RealType or similar", ts->type);
                         return;
                }
                tp->typeSpec = ts;  	// parent (tp) links to sub-element (ts)
                break;
            }
        case elm_ScalarVariable:
            {
                ScalarVariable* sv;
                Element** list = NULL;
                Element* child = checkPop(ANY_TYPE);
                if (!child) return;
                if (child->type==elm_DirectDependency){
                    list = ((ListElement*)child)->list; // DirectDependency is ListElement
                    free(child);
                    child = checkPop(ANY_TYPE);
                    if (!child) return;
                }
                if (checkPeek(elm_ScalarVariable)) return;  // If next element is not ScalarVariable, return
                sv = (ScalarVariable*)stackPeek(stack);
                switch (child->type) {
                    case elm_Real:
                    case elm_Integer:
                    case elm_Boolean:
                    case elm_Enumeration:
                    case elm_String:
                        break;
                    default:
                         logFatalTypeError("Real or similar", child->type);
                         return;
                }
                sv->directDependencies = list;
                sv->typeSpec = child;
                break;
            }
        case elm_Implementation:  	popList(elm_CoSimulation_StandAlone); break; // Needs to be modified if CoSimulation_Tool is added
	    case elm_CoSimulation_StandAlone:  popList(elm_Capabilities); break; // CoSimulation_StandAlone only has Capabilities
        case elm_ModelVariables:    popList(elm_ScalarVariable); break;
        case elm_VendorAnnotations: popList(elm_Tool);break;
        case elm_Tool:              popList(elm_Annotation); break;
        case elm_TypeDefinitions:   popList(elm_Type); break;
        case elm_EnumerationType:   popList(elm_Item); break;
        case elm_UnitDefinitions:   popList(elm_BaseUnit); break;
        case elm_BaseUnit:          popList(elm_DisplayUnitDefinition); break;
        case elm_DirectDependency:  popList(elm_Name); break;
        case elm_Name:
            {
                 // Exception: the name value is represented as element content.
                 // All other values of the XML file are represented using attributes.
                 Element* name = checkPop(elm_Name);
                 if (!name) return;
                 name->n = 2;
                 name->attributes = malloc(2*sizeof(char*));
                 name->attributes[0] = attNames[att_input];
                 name->attributes[1] = data;
                 data = NULL;
                 skipData = 1; // stop recording element content
                 stackPush(stack, name);
                 break;
            }
        case -1: return; // illegal element error
        default: // must be a leaf Element
				printDebug("+++++++ got a leaf element\n");
                assert(getAstNodeType(el)==astElement);
                break;
    }
    // All children of el removed from the stack.
    // The top element must be of type el now.
    checkPeek(el);
}
Exemple #14
0
int main() {
  
  int spacecount = 0;
  coordgrid grid;
  for(int i = 0; i < HIGH; i++) {
    	for(int j = 0; j < WIDE; j++) {
	  //	  if ((rand() % 100) > BLOCKPERCENT) {
          //          	  	  	  	   if ((i != 25) || (j == 5)) {
	            if (true) {
		coord foo (i, j);
		grid.push_back(foo);
		spacecount++;
		//		printf(".");
	  } else {
		//printf("O");
	  }
	}
	//	printf("\n");
  }
  grid.endcoord = pair<int, int>(HIGH-1,WIDE-1);
  grid.startcoord = pair<int, int>(HIGH-1, 1);

  printf("%d spaces.  Beginning DLAware!\n", spacecount);
  fflush(stdout);

  
  list<node<coord, dir> > path =
    dlaware<coord, coordgrid, dir>(&grid, slowclock, 15000);

  list<coord> copath;
  //  for(list<coord>::iterator i = path.begin(); i != path.end(); ++i) {
  //	copath.push_back((*i).id);
  //}
  int steps = path.size();
  double totalcost = 0;
  for(int i = 0; i < steps; i++) {
    printf("%.2lf %lf %lf %lf\n", path.front().stepstaken, path.front().derror, path.front().pathderror, path.front().g);
    copath.push_back(path.front().id);
	//printf("%d %d | %d %d %d\n", path.front().id.first, path.front().id.second, path.front().g, path.front().heuristic, path.front().g + path.front().heuristic);
    totalcost = path.front().g;
    path.pop_front();
  }

  map<coord, node<coord, dir> > bar = debug;
  //  for(set<node<coord> >::iterator i = visited.begin(); i != visited.end(); ++i) {
  //	bar.insert(i->id);
  //}

  /*
  for(int i = 0; i < HIGH; i++) {
    for(int j = 0; j < WIDE; j++) {
      coord foo = pair<int, int> (i, j);
      if (oldnodes.find(foo) == oldnodes.end()) {
	printf("XXXX");
	continue;
      } else {
	node<coord> foobar = oldnodes[foo];

	if (std::find(copath.begin(), copath.end(), pair<int, int>(i, j)) != copath.end()) {
	  printf(" *%2.1f", foobar.g);
	} else {
	  printf("  %2.1f", foobar.g);
	}
      }
    }
    printf("\n");
  } 
  */

  printDebug();
  
  int solutionlength = copath.size();
  for(int i = 0; i < HIGH; i++) {
	for(int j = 0; j < WIDE; j++) {
	  if (std::find(copath.begin(), copath.end(), pair<int, int>(i, j)) != copath.end()) {
		printf("X");
	  } else if (find(grid.begin(), grid.end(), pair<int, int>(i, j)) != grid.end()) {
		if (bar.find(pair<int, int>(i,j)) != bar.end()) {
		  printf("*");
		} else {
		  printf(".");
		}
	  } else {
		printf("O");
	  }
	}
	printf("\n");
  }
  printf("%d steps, cost %lf, time %d, unprunes %d %d\n", solutionlength, totalcost, simtime, prunecount, enprunecount);
  //printf("%d steps.\n", solutionlength);
  return 0;

}
Exemple #15
0
/*
 * Entry point
 */
int main (int argc, char **argv)
{
    Bool success = true;
    pid_t serverPID;
    SInt32 oneWireServerPort = -1;
    
    setDebugPrintsOn();
    setProgressPrintsOn();
    
    printProgress ("This will test that the messaging client and server libraries talk.\n");
    printProgress ("Make sure that %s is present 'cos we'll be running it.\n", SERVER_EXE);

    oneWireServerPort = atoi (SERVER_PORT_STRING);
    
    /* Spawn a child that will become the One Wire server. */
    serverPID = fork();
    
    if (serverPID == 0)
    {
        /* Start OneWire server process on port oneWireServerPort */
        static char *argv[]={SERVER_EXE, SERVER_PORT_STRING, PNULL};
        
        execv (SERVER_EXE, argv);
        printDebug ("Couldn't launch %s, err: %s\n", SERVER_EXE, strerror (errno));
    }
    else
    { /* Parent process */
      /* Setup what's necessary for OneWire bus stuff */
        int serverStatus;
        Bool returnCode;
        Msg *pSendMsg;
        Msg *pReceivedMsg;
        SInt32 i; /* Deliberately signed */
        UInt32 x;

        /* Wait for the server to start */
        usleep (SERVER_START_DELAY_PI_US);
        
        /* Check that it is running (looks strange but it is the standard method apparently) */
        if (kill (serverPID, 0) == 0)
        {
            pSendMsg = malloc (sizeof (Msg));
            
            if (pSendMsg != PNULL)
            {
                /* Send all the possible message lengths,
                 * ending with a zero length message which
                 * will cause the test server to exit */
                for (i = MAX_MSG_LENGTH; i >= 0; i--)
                {
                    printDebug ("+%d", i);
                    pSendMsg->msgLength = (MsgLength) i;            
                    pSendMsg->msgType = (MsgType) (i - 1);
                    
                    for (x = 0; x < i; x++)
                    {
                        pSendMsg->msgBody[x] = x;
                    }
                    
                    pReceivedMsg = malloc (sizeof(Msg));
                    
                    if (pReceivedMsg != PNULL)
                    {
                        /* Send the message and get a response */
                        if (i > 0)
                        {
                            returnCode = runMessagingClient (oneWireServerPort, PNULL, pSendMsg, pReceivedMsg);
                        }
                        else
                        {
                            returnCode = runMessagingClient (oneWireServerPort, PNULL, pSendMsg, PNULL); /* No echo will result for a zero length message */                    
                        }
                        
                        if (returnCode == CLIENT_SUCCESS)
                        {
                            if (i > 0)
                            {                            
                                printDebug ("-%d", i);
                                if (!checkReceivedMsgContents (pSendMsg, pReceivedMsg))
                                {
                                    success = false;;
                                }
                            }
                        }
                        else
                        {
                            success = false;;
                        }
                        
                        free (pReceivedMsg);
                    }        
                    else
                    {
                        success = false;;
                        printDebug ("Failed to get memory to receive test message.\n");            
                    }            
                }
                
                free (pSendMsg);
            }
            else
            {
                success = false;
                printDebug ("Failed to get memory to send test message.\n");
            }
            
            /* Wait for server to exit */
            if (waitpid (serverPID, &serverStatus, 0) >= 0)
            {
                printDebug ("\nServer process exited, status = 0x%x.\n", serverStatus);
            }
            else
            {
                printDebug ("\nFailed to wait for server to exit, error %s.\n", strerror (errno));            
            }
        }
        else
        {
            success = false;
            printDebug ("Server process failed to start.\n");            
        }
    }
    
    if (success)
    {
        printProgress ("\nTests PASSED, messaging server will now exit.\n");        
    }
    else
    {
        printProgress ("\nTests FAILED, messaging server will now exit.\n");
    }
        
    return success;
}
Exemple #16
0
void* CMMDVMController::Entry()
{
	wxLogMessage(wxT("Starting MMDVM Controller thread"));

	// Clock every 5ms-ish
	CTimer pollTimer(200U, 0U, 100U);
	pollTimer.start();

	unsigned char  writeType   = DSMTT_NONE;
	unsigned char  writeLength = 0U;
	unsigned char* writeBuffer = new unsigned char[BUFFER_LENGTH];

	unsigned int space = 0U;

	while (!m_stopped) {
		// Poll the modem status every 100ms
		if (pollTimer.hasExpired()) {
			bool ret = readStatus();
			if (!ret) {
				ret = findModem();
				if (!ret) {
					wxLogError(wxT("Stopping MMDVM Controller thread"));
					return NULL;
				}
			}

			pollTimer.start();
		}

		unsigned int length;
		RESP_TYPE_MMDVM type = getResponse(m_buffer, length);

		switch (type) {
			case RTDVM_TIMEOUT:
				break;

			case RTDVM_ERROR: {
					bool ret = findModem();
					if (!ret) {
						wxLogError(wxT("Stopping MMDVM Controller thread"));
						return NULL;
					}
				}
				break;

			case RTDVM_DSTAR_HEADER: {
					// CUtils::dump(wxT("RT_DSTAR_HEADER"), m_buffer, length);
					wxMutexLocker locker(m_mutex);

					unsigned char data[2U];
					data[0U] = DSMTT_HEADER;
					data[1U] = RADIO_HEADER_LENGTH_BYTES;
					m_rxData.addData(data, 2U);

					m_rxData.addData(m_buffer + 3U, RADIO_HEADER_LENGTH_BYTES);

					m_rx = true;
				}
				break;

			case RTDVM_DSTAR_DATA: {
					// CUtils::dump(wxT("RT_DSTAR_DATA"), m_buffer, length);
					wxMutexLocker locker(m_mutex);

					unsigned char data[2U];
					data[0U] = DSMTT_DATA;
					data[1U] = DV_FRAME_LENGTH_BYTES;
					m_rxData.addData(data, 2U);

					m_rxData.addData(m_buffer + 3U, DV_FRAME_LENGTH_BYTES);

					m_rx = true;
				}
				break;

			case RTDVM_DSTAR_EOT: {
					// wxLogMessage(wxT("RT_DSTAR_EOT"));
					wxMutexLocker locker(m_mutex);

					unsigned char data[2U];
					data[0U] = DSMTT_EOT;
					data[1U] = 0U;
					m_rxData.addData(data, 2U);

					m_rx = false;
				}
				break;

			case RTDVM_DSTAR_LOST: {
					// wxLogMessage(wxT("RT_DSTAR_LOST"));
					wxMutexLocker locker(m_mutex);

					unsigned char data[2U];
					data[0U] = DSMTT_LOST;
					data[1U] = 0U;
					m_rxData.addData(data, 2U);

					m_rx = false;
				}
				break;

			case RTDVM_GET_STATUS: {
					bool dstar = (m_buffer[3U] & 0x01U) == 0x01U;
					if (!dstar) {
						wxLogError(wxT("D-Star not enabled in the MMDVM!!!"));
						wxLogError(wxT("Stopping MMDVM Controller thread"));
						return NULL;
					}

					m_tx  = (m_buffer[5U] & 0x01U) == 0x01U;

					bool adcOverflow = (m_buffer[5U] & 0x02U) == 0x02U;
					if (adcOverflow)
						wxLogWarning(wxT("MMDVM ADC levels have overflowed"));

					space = m_buffer[6U];
					// CUtils::dump(wxT("GET_STATUS"), m_buffer, length);
					// wxLogMessage(wxT("PTT=%d space=%u"), int(m_tx), space);
				}
				break;

			// These should not be received in this loop, but don't complain if we do
			case RTDVM_GET_VERSION:
			case RTDVM_ACK:
				break;

			case RTDVM_NAK: {
					switch (m_buffer[3U]) {
						case MMDVM_DSTAR_HEADER:
							wxLogWarning(wxT("Received a header NAK from the MMDVM, reason = %u"), m_buffer[4U]);
							break;
						case MMDVM_DSTAR_DATA:
							wxLogWarning(wxT("Received a data NAK from the MMDVM, reason = %u"), m_buffer[4U]);
							break;
						case MMDVM_DSTAR_EOT:
							wxLogWarning(wxT("Received an EOT NAK from the MMDVM, reason = %u"), m_buffer[4U]);
							break;
						default:
							wxLogWarning(wxT("Received a NAK from the MMDVM, command = 0x%02X, reason = %u"), m_buffer[3U], m_buffer[4U]);
							break;
					}
				}
				break;

			case RTDVM_DUMP:
				CUtils::dump(wxT("Modem dump"), m_buffer + 3U, length - 3U);
				break;

			case RTDVM_DEBUG1:
			case RTDVM_DEBUG2:
			case RTDVM_DEBUG3:
			case RTDVM_DEBUG4:
			case RTDVM_DEBUG5:
				printDebug();
				break;

			default:
				wxLogMessage(wxT("Unknown message, type: %02X"), m_buffer[2U]);
				CUtils::dump(wxT("Buffer dump"), m_buffer, length);
				break;
		}

		if (writeType == DSMTT_NONE && m_txData.hasData()) {
			wxMutexLocker locker(m_mutex);

			m_txData.getData(&writeType, 1U);
			m_txData.getData(&writeLength, 1U);
			m_txData.getData(writeBuffer, writeLength);
		}

		if (space > 4U && writeType == DSMTT_HEADER) {
			// CUtils::dump(wxT("Write Header"), writeBuffer, writeLength);

			int ret = m_serial.write(writeBuffer, writeLength);
			if (ret != int(writeLength))
				wxLogWarning(wxT("Error when writing the header to the MMDVM"));

			writeType = DSMTT_NONE;
			space -= 4U;
		}

		if (space > 1U && (writeType == DSMTT_DATA || writeType == DSMTT_EOT)) {
			// CUtils::dump(wxT("Write Data"), writeBuffer, writeLength);

			int ret = m_serial.write(writeBuffer, writeLength);
			if (ret != int(writeLength))
				wxLogWarning(wxT("Error when writing data to the MMDVM"));

			writeType = DSMTT_NONE;
			space--;
		}

		Sleep(5UL);

		pollTimer.clock();
	}

	wxLogMessage(wxT("Stopping MMDVM Controller thread"));

	delete[] writeBuffer;

	m_serial.close();

	return NULL;
}
Exemple #17
0
///////////////////////////////////////////////////////////////////////////////
/// main routine of the demo code
///
///\param argc Number of arguments
///\param argv Arguments
///\return 0 if no error occurred
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
    const char* fmuFilNam;
    char* fmuPat;
    char* tmpPat;
    char* xmlPat;
    char* dllPat;
    
    // define default argument values
    double tEnd = 1.0;
    double h=0.1;
    int loggingOn = 0;
    char csv_separator = ',';  
   
    // parse command line arguments
    if (argc>1) {
        fmuFilNam = argv[1];
        
        if(!strcmp(fmuFilNam, "-h") | !strcmp(fmuFilNam, "--help")) {
          printHelp(argv[0]);
          return 0;
        }

        /*if(!strstr(fmuFilNam,"DoubleInputDoubleOutput.fmu")) {
          printf("Sorry, this demo only works with the FMU file DoubleInputDoubleOutput.fmu");
          return 0;
        }*/
    }
    else {
        printError("No fmu file.\n");
        printHelp(argv[0]);
        exit(EXIT_FAILURE);
    }
    if (argc>2) {
        if (sscanf(argv[2],"%lf", &tEnd) != 1) {
            printfError("The given end time (%s) is not a number.\n", argv[2]);
            exit(EXIT_FAILURE);
        }
    }
    if (argc>3) {
        if (sscanf(argv[3],"%lf", &h) != 1) {
            printfError("The given stepsize (%s) is not a number.\n", argv[3]);
            exit(EXIT_FAILURE);
        }
    }
    if (argc>4) {
        if (sscanf(argv[4],"%d", &loggingOn) != 1 || loggingOn<0 || loggingOn>1) {
            printfError("The given logging flag (%s) is not boolean.\n", argv[4]);
            exit(EXIT_FAILURE);
        }
        if(loggingOn) setDebug();
    }
    if (argc>5) {
        if (strlen(argv[5]) != 1) {
            printfError("The given CSV separator char (%s) is not valid.\n", argv[5]);
            exit(EXIT_FAILURE);
        }
        csv_separator = argv[5][0];
    }
    if (argc>6) {
        printf("warning: Ignoring %d additional arguments: %s ...\n", argc-6, argv[6]);
        printHelp(argv[0]);
    }

    // Get absolute path to FMU, NULL if not found  
    tmpPat = getTmpPath(fmuFilNam, strlen(fmuFilNam)-4);
    if(tmpPat==NULL){
      printError("Cannot allocate temporary path.\n");
      exit(EXIT_FAILURE);
    }

    // Unzip the FMU to the tmpPat directory
    if (unpack(fmuFilNam, tmpPat)) {  
        printfError("Fail to unpack fmu \"%s\".\n", fmuFilNam);
        exit(EXIT_FAILURE);
    }

    printDebug("parse tmpPat\\modelDescription.xml.\n");
    xmlPat = calloc(sizeof(char), strlen(tmpPat) + strlen(XML_FILE) + 1);
    sprintf(xmlPat, "%s%s", tmpPat, XML_FILE);

    // Parse only parses the model description and store in structure fmu.modelDescription
    fmu.modelDescription = parse(xmlPat); 
    free(xmlPat);
    if (!fmu.modelDescription) exit(EXIT_FAILURE);

    // Allocate the memory for dllPat
    dllPat = calloc(sizeof(char), strlen(tmpPat) + strlen(DLL_DIR) 
            + strlen( getModelIdentifier(fmu.modelDescription)) +  strlen(".dll") + 1); 
    sprintf(dllPat,"%s%s%s.dll", tmpPat, DLL_DIR, getModelIdentifier(fmu.modelDescription)); 

    // Load the FMU dll
    if (loadDll(dllPat, &fmu)) exit(EXIT_FAILURE); 
	  printfDebug("Loaded \"%s\"\n", dllPat); 

    free(dllPat);
    free(tmpPat);

    // Run the simulation
    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c'\n", 
            fmuFilNam, tEnd, h, loggingOn, csv_separator);
    if (simulate(&fmu, tEnd, h, loggingOn, csv_separator)){
      printError("Simulation failed.\n");
      exit(EXIT_FAILURE);
    }

    printf("CSV file '%s' written", RESULT_FILE);

    // Release FMU 
    FreeLibrary(fmu.dllHandle);
    freeElement(fmu.modelDescription);
    return EXIT_SUCCESS;
}
/*
 * Entry point
 */
int main (int argc, char **argv)
{
    Bool   success = false;
    UInt16 remainingCapacity;
    pid_t  hwServerPID;
    
    setDebugPrintsOnToFile ("robooneremainingcapacitysync.log");
    setProgressPrintsOn();

    printProgress ("Synchronising remaining battery capacity values...\n");
    /* Spawn a child that will become the Hardware server. */
    hwServerPID = fork();
    if (hwServerPID == 0)
    {
        /* Start Hardware Server process on a given port */
        static char *argv1[] = {HARDWARE_SERVER_EXE, HARDWARE_SERVER_PORT_STRING, PNULL};
        
        execv (HARDWARE_SERVER_EXE, argv1);
        printDebug ("!!! Couldn't launch %s, err: %s. !!!\n", HARDWARE_SERVER_EXE, strerror (errno));
    }
    else
    {
        if (hwServerPID < 0)
        {
            printDebug ("!!! Couldn't fork to launch %s, err: %s. !!!\n", HARDWARE_SERVER_EXE, strerror (errno));
        }
        else
        {   /* Parent process */
            /* Wait for the server to start */
            usleep (HARDWARE_SERVER_START_DELAY_PI_US);
            /* Now setup the Hardware Server, batteries
             * only on this occasion. This will restore
             * the remaining battery capacity from
             * non-volatile storage if it is out of date,
             * which would be the case at power-on. */
            success = startHardwareServer (true);

            if (success)
            {
                /* Now do a remaining capacity reading to complete the sync back to
                 * non-volatile storage in case we are about to power off */
                if (hardwareServerSendReceive (HARDWARE_READ_RIO_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("Rio battery has %d mAh remaining.\n", remainingCapacity);
                }
                if (hardwareServerSendReceive (HARDWARE_READ_O1_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("O1 battery has %d mAh remaining.\n", remainingCapacity);
                }
                if (hardwareServerSendReceive (HARDWARE_READ_O2_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("O2 battery has %d mAh remaining.\n", remainingCapacity);
                }
                if (hardwareServerSendReceive (HARDWARE_READ_O3_REMAINING_CAPACITY, PNULL, 0, &remainingCapacity))
                {
                    printProgress ("O3 battery has %d mAh remaining.\n", remainingCapacity);
                }
            }

            /* Shut the Hardware Server down gracefully */
            stopHardwareServer();
            waitpid (hwServerPID, 0, 0); /* wait for Hardware Server process to exit */
        }
    }
    
    setDebugPrintsOff();

    if (success)
    {
        printProgress ("Synchronisation complete.\n");
    }
    else
    {
        printProgress ("\nSynchronisation failed!\n");
        exit (-1);
    }

    return success;
}
void oldmain(void){
  SYSTEMConfigPerformance(10000000);
  STATE state = START;
  unsigned short int lineCount = 0;
  bool ignoreTurns = false;
  // Initialize Motor(s))
  Motor_Init();
  // Initialize IRSensor(s)
  IRSensor_Init();
  // LCD Initialize
  LCD_Init();
  Motor_Enable();
  while(1){
    printDebug(state);
    switch(state){
      case START:
        Motor_Disable();
        if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL))state = TRAVEL;
        break;
      case TURN_LEFT:
        if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL)){
          Motor_Disable();
          state = TRAVEL;
        }else{
          Motor_Set1DutyCycle(0.0);
          Motor_Set2DutyCycle(STANDARD_DUTY_CYCLE * MOTOR_BIAS_TURN);
          Motor_Enable();
        };
        break;
      case TURN_RIGHT:
        if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL)){
          Motor_Disable();
          state = TRAVEL;
        }else{
          Motor_Set1DutyCycle(STANDARD_DUTY_CYCLE * MOTOR_BIAS_TURN);
          Motor_Set2DutyCycle(0.0);
          Motor_Enable();
        };
        break;
      case TRAVEL:
        Motor_Set1Forward();
        Motor_Set2Forward();
        Motor_Set1DutyCycle(STANDARD_DUTY_CYCLE);
        Motor_Set2DutyCycle(STANDARD_DUTY_CYCLE);
        Motor_Enable();
        if(!IRSensor_CheckCenterRight(IR_TRIGGER_ADJUST) && IRSensor_CheckCenterLeft(IR_TRIGGER_ADJUST)){
          Motor_Disable();
          state = ADJUST_RIGHT;break;
        }else if(!IRSensor_CheckCenterLeft(IR_TRIGGER_ADJUST) && IRSensor_CheckCenterRight(IR_TRIGGER_ADJUST)){
          Motor_Disable();
          state = ADJUST_LEFT;break;};
        //  if(IRSensor_CheckFront()){
        //  lineCount++;
        //  if(lineCount == 1){// Entering Extra Credit 'T' Intersection
        //    state = TURN_LEFT;
        //  }else if(lineCount == 2){// Exiting Extra Credit 'T' Intersection
        //    state = TURN_RIGHT;
        //  }else if(lineCount == 5){// End of First Time Through
        //    state = TURN_AROUND;
        //  };
        //};
        if(!ignoreTurns && IRSensor_CheckLeftFront(IR_TRIGGER_TURN)){Motor_Disable();state = TURN_LEFT;break;};
        if(!ignoreTurns && IRSensor_CheckRightFront(IR_TRIGGER_TURN)){Motor_Disable();state = TURN_RIGHT;break;};//
        break;
      case ADJUST_LEFT:
        Motor_Set1DutyCycle(MOTOR_BIAS_ADJUST * STANDARD_DUTY_CYCLE);
        Motor_Set2DutyCycle(0.75 * MOTOR_BIAS_ADJUST * STANDARD_DUTY_CYCLE);
        Motor_Enable();
        if(IRSensor_CheckLeftFront(IR_TRIGGER_TURN)){
          state = TURN_LEFT;
          break;
        }else if(IRSensor_CheckRightFront(IR_TRIGGER_TURN)){
          state = TURN_RIGHT;
          break;
        }else if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL)){
          Motor_Set1DutyCycle(STANDARD_DUTY_CYCLE);
          Motor_Set2DutyCycle(STANDARD_DUTY_CYCLE);
          state = TRAVEL;
          break;
        }else{
          break;
        };
      case ADJUST_RIGHT:
        Motor_Set1DutyCycle(0.75 * MOTOR_BIAS_ADJUST * STANDARD_DUTY_CYCLE);
        Motor_Set2DutyCycle(MOTOR_BIAS_ADJUST * STANDARD_DUTY_CYCLE);
        Motor_Enable();
        if(IRSensor_CheckLeftFront(IR_TRIGGER_TURN)){
          state = TURN_LEFT;
          break;
        }else if(IRSensor_CheckRightFront(IR_TRIGGER_TURN)){
          state = TURN_RIGHT;
          break;
        }else if(IRSensor_CheckCenter(IR_TRIGGER_TRAVEL)){
          Motor_Set1DutyCycle(STANDARD_DUTY_CYCLE);
          Motor_Set2DutyCycle(STANDARD_DUTY_CYCLE);
          state = TRAVEL;
          break;
        }else{
          break;
        };
      //case TURN_AROUND:
      //  while(IRSensor_CheckCenterLeft(IR_TRIGGER_TRAVEL)){
      //    Motor_Set1Backward();
      //    Motor_Set2Forward();
      //  };
      //  delayMs(IR_DELAY_TURNAROUND);
      //  state = TRAVEL;
      //  ignoreTurns = true;
      //  break;
      //case END:
      //  Motor_Disable();
      //  break;
    };
  };
};
void LegendManager::procDirectDebugInstruction(StringBuilder *input) {
  char* str = input->position(0);

  uint8_t temp_byte = 0;
  if (*(str) != 0) {
    temp_byte = atoi((char*) str+1);
  }

  StringBuilder parse_mule;

  switch (*(str)) {
    case 'v':
      parse_mule.concat(str);
      local_log.concatf("parse_mule split (%s) into %d positions.\n", str, parse_mule.split(","));
      parse_mule.drop_position(0);
      if (temp_byte < 17) {
        if (parse_mule.count() > 0) {
          int temp_int = parse_mule.position_as_int(0);
          iius[temp_byte].setVerbosity(temp_int);
        }
        local_log.concatf("Verbosity on IIU %d is %d.\n", temp_byte, iius[temp_byte].getVerbosity());
      }
      break;

    case 'i':
      if (1 == temp_byte) {
        local_log.concatf("The IIU preallocated measurements are stored at %p.\n", (uintptr_t) __prealloc);
      }
      else if (2 == temp_byte) {
        if (operating_legend) {
          operating_legend->printDebug(&local_log);
        }
      }
      else {
        int8_t old_verbosity = getVerbosity();
        if (temp_byte && (temp_byte < 7)) setVerbosity(temp_byte);
        printDebug(&local_log);
        if (temp_byte && (temp_byte < 7)) setVerbosity(old_verbosity);
      }
      break;

    case '-':
      if (operating_legend) {
        operating_legend->copy_frame();
        local_log.concat("Frame copied.\n");
        operating_legend->printDataset(&local_log);
      }
      break;
    case '+':
      if (temp_byte < 17) {
        iius[temp_byte].dumpPointers(&local_log);
      }
      break;


    // IMU DEBUG //////////////////////////////////////////////////////////////////
    case 'c':
      if (temp_byte < 17) {
        iius[temp_byte].printDebug(&local_log);
      }
      break;

    // IMU STATE CONTROL //////////////////////////////////////////////////////////
    case 'g':
      if (255 == temp_byte) {
        local_log.concat("Syncing all IIUs...\n");
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].sync();
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].sync();
        local_log.concatf("Syncing IIU %d.\n", temp_byte);
      }
      break;

    case 's':
      parse_mule.concat(str);
      parse_mule.split(",");
      parse_mule.drop_position(0);
      if (parse_mule.count() > 0) {
        int temp_int = parse_mule.position_as_int(0);

        if (255 == temp_byte) {
          for (uint8_t i = 0; i < 17; i++) {
            iius[i].setOperatingState(temp_int);
          }
        }
        else if (temp_byte < 17) {
          local_log.concatf("Setting the state of IMU %d to %d\n", temp_byte, temp_int);
          iius[temp_byte].setOperatingState(temp_int);
        }

      }
      break;

    case 'k':
      if ((temp_byte < 6) && (temp_byte >= 0)) {
        ManuvrMsg *event = Kernel::returnEvent(DIGITABULUM_MSG_IMU_INIT);
        event->addArg((uint8_t) temp_byte);  // Set the desired init stage.
        event->priority(0);
        raiseEvent(event);
        local_log.concatf("Broadcasting IMU_INIT for stage %u...\n", temp_byte);
      }
      else {
        local_log.concatf("Illegal INIT stage: %u\n", temp_byte);
      }
      break;

    case 'r':
      if (255 == temp_byte) {
        local_log.concat("Reseting all IIUs...\n");
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].reset();
        }
      }
      else if (temp_byte < 17) {
        local_log.concatf("Resetting IIU %d.\n", temp_byte);
        iius[temp_byte].reset();
      }
      break;


    case 'T':
    case 't':
      if (temp_byte < 17) {
        ManuvrMsg *event = Kernel::returnEvent((*(str) == 'T') ? DIGITABULUM_MSG_IMU_DOUBLE_TAP : DIGITABULUM_MSG_IMU_TAP);
        event->setOriginator((EventReceiver*) this);
        event->addArg((uint8_t) temp_byte);
        Kernel::staticRaiseEvent(event);
        local_log.concatf("Sent %stap event for IMU %d.\n", ((*(str) == 'T') ? "double ":""), temp_byte);
      }
      break;

    case 'q':
      if (temp_byte < 17) {
        ManuvrMsg *event = Kernel::returnEvent(DIGITABULUM_MSG_IMU_QUAT_CRUNCH);
        event->specific_target = (EventReceiver*) this;
        event->addArg((uint8_t) temp_byte);
        Kernel::staticRaiseEvent(event);
        local_log.concatf("Running quat on IIU %d.\n", temp_byte);
      }
      break;



    // IMU DATA ///////////////////////////////////////////////////////////////////
    case 'j':
      switch (*(str+1)) {
        case '0':
          reflection_acc.x = -1;
          reflection_acc.y = 1;
          reflection_acc.z = -1;
          reflection_gyr.set(-1, 1, -1);
          reflection_mag.x = 1;
          reflection_mag.y = 1;
          reflection_mag.z = -1;
          break;
        case 'm':
          if (*(str+2) == 'x')      reflection_mag.x *= -1;
          else if (*(str+2) == 'y') reflection_mag.y *= -1;
          else if (*(str+2) == 'z') reflection_mag.z *= -1;
          break;

        case 'a':
          if (*(str+2) == 'x')      reflection_acc.x *= -1;
          else if (*(str+2) == 'y') reflection_acc.y *= -1;
          else if (*(str+2) == 'z') reflection_acc.z *= -1;
          break;

        case 'g':
          if (*(str+2) == 'x')      reflection_gyr.x *= -1;
          else if (*(str+2) == 'y') reflection_gyr.y *= -1;
          else if (*(str+2) == 'z') reflection_gyr.z *= -1;
          break;
      }
      local_log.concatf("Reflection vectors\n\tMag (%d, %d, %d)\n\tAcc (%d, %d, %d)\n\tGyr (%d, %d, %d)\n", reflection_mag.x, reflection_mag.y, reflection_mag.z, reflection_acc.x, reflection_acc.y, reflection_acc.z, reflection_gyr.x, reflection_gyr.y, reflection_gyr.z);
      break;

    case '[':
    case ']':
      if (255 == temp_byte) {
        local_log.concatf("%sabling spherical abberation correction on all IIUs.\n", ((*(str) == ']') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].correctSphericalAbberation((*(str) == ']'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].correctSphericalAbberation((*(str) == ']'));
        local_log.concatf("%sabling spherical abberation correction on IIU %d.\n", ((*(str) == ']') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'u':
    case 'U':
      if (255 == temp_byte) {
        local_log.concatf("%sabling (clean-mag-is-zero) on all IIUs.\n", ((*(str) == 'U') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].cleanMagZero((*(str) == 'U'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].cleanMagZero((*(str) == 'U'));
        local_log.concatf("%sabling (clean-mag-is-zero) on IIU %d.\n", ((*(str) == 'U') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'w':
    case 'W':
      if (255 == temp_byte) {
        local_log.concatf("%sabling mag data scrutiny on all IIUs.\n", ((*(str) == 'Z') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].dropObviousBadMag((*(str) == 'Z'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].dropObviousBadMag((*(str) == 'Z'));
        local_log.concatf("%sabling mag data scrutiny on IIU %d.\n", ((*(str) == 'Z') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'z':
    case 'Z':
      if (255 == temp_byte) {
        local_log.concatf("%sabling autoscale on all IIUs.\n", ((*(str) == 'Z') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].enableAutoscale((*(str) == 'Z'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].enableAutoscale((*(str) == 'Z'));
        local_log.concatf("%sabling autoscale on IIU %d.\n", ((*(str) == 'Z') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'n':
    case 'N':
      if (255 == temp_byte) {
        local_log.concatf("%sabling range-binding on all IIUs.\n", ((*(str) == 'N') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].rangeBind((*(str) == 'N'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].rangeBind((*(str) == 'N'));
        local_log.concatf("%sabling range-binding on IIU %d.\n", ((*(str) == 'N') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'h':
    case 'H':
      if (255 == temp_byte) {
        local_log.concatf("%sabling quats on all IIUs.\n", ((*(str) == 'H') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].processQuats((*(str) == 'H'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].processQuats((*(str) == 'H'));
        local_log.concatf("%sabling quats on IIU %d.\n", ((*(str) == 'H') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'x':
    case 'X':
      if (255 == temp_byte) {
        local_log.concatf("%sabling gyro error compensation on all IIUs.\n", ((*(str) == 'X') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].nullGyroError((*(str) == 'X'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].nullGyroError((*(str) == 'X'));
        local_log.concatf("%sabling gyro error compensation on IIU %d.\n", ((*(str) == 'X') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'm':
    case 'M':
      if (255 == temp_byte) {
        local_log.concatf("%sabling gravity nullification on all IIUs.\n", ((*(str) == 'M') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].nullifyGravity((*(str) == 'M'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].nullifyGravity((*(str) == 'M'));
        local_log.concatf("%sabling gravity nullification on IIU %d.\n", ((*(str) == 'M') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'y':
    case 'Y':
      if (255 == temp_byte) {
        local_log.concatf("%sabling bearing nullification on all IIUs.\n", ((*(str) == 'Y') ? "En":"Dis"));
        for (uint8_t i = 0; i < 17; i++) {
          iius[i].nullifyBearing((*(str) == 'Y'));
        }
      }
      else if (temp_byte < 17) {
        iius[temp_byte].nullifyBearing((*(str) == 'Y'));
        local_log.concatf("%sabling bearing nullification on IIU %d.\n", ((*(str) == 'Y') ? "En":"Dis"), temp_byte);
      }
      break;

    case 'Q':
      local_log.concatf("Madgwick iterations to %d on all IIUs.\n", temp_byte);
      for (uint8_t i = 0; i < 17; i++) {
        iius[i].madgwickIterations(temp_byte);
      }
      break;



    case ',':
      IIU::max_quats_per_event = temp_byte;
      local_log.concatf("IIU class now runs a maximum of %u quats per event.\n", IIU::max_quats_per_event);
      break;

    case 'b':
      for (uint8_t i = 0; i < 17; i++) {
        iius[i].beta = (float)temp_byte * 0.1;
      }
      local_log.concatf("Beta value is now %f.\n", (double) (temp_byte * 0.1f));
      break;

    case 'L':
      for (uint8_t i = 0; i < 17; i++) {
        iius[i].setSampleRateProfile(temp_byte);
      }
      local_log.concatf("Moving to sample rate profile %d.\n", temp_byte);
      break;

    case 'o':
      for (uint8_t i = 0; i < 17; i++) {
        iius[i].setGyroBaseFiler(temp_byte);
      }
      local_log.concatf("Setting GYR base filter to %d.\n", temp_byte);
      break;

    case 'O':
      for (uint8_t i = 0; i < 17; i++) {
        iius[i].setAccelBaseFiler(temp_byte);
      }
      local_log.concatf("Setting ACC base filter to %d.\n", temp_byte);
      break;

    case 'a':
      if (255 == temp_byte) {
        refreshIMU();
      }
      else if (17 > temp_byte) {
        refreshIMU(temp_byte);
      }
      break;

    case 'd':
      switch (temp_byte) {
        case 255:
          event_legend_frame_ready.fireNow();  // Fire a single frame transmission.
          local_log.concat("We are manually firing the IMU frame broadcasts schedule.\n");
          break;
        case 254:
          event_legend_frame_ready.enableSchedule(true);  // Enable the periodic read.
          local_log.concat("Enabled frame broadcasts.\n");
          break;
        #if defined(__MANUVR_DEBUG)
          case 253:
            event_legend_frame_ready.printDebug(&local_log);
            break;
        #endif
        case 252:
          send_map_event();
          local_log.concat("We are manually firing the IMU frame broadcasts schedule.\n");
          break;
        default:
          if (temp_byte) {
            event_legend_frame_ready.alterSchedulePeriod(temp_byte*10);
            local_log.concatf("Set periodic frame broadcast to once every %dms.\n", temp_byte*10);
          }
          else {
            event_legend_frame_ready.enableSchedule(false);  // Disable the periodic read.
            local_log.concat("Disabled frame broadcasts.\n");
          }
          break;
      }
      break;

    case 'f':
      switch (temp_byte) {
        case 255:
          event_iiu_read.fireNow();
          local_log.concat("We are manually firing the IMU read schedule.\n");
          break;
        case 254:
          event_iiu_read.enableSchedule(true);
          local_log.concat("Enabled periodic readback.\n");
          break;
        default:
          if (temp_byte) {
            event_iiu_read.alterSchedulePeriod(temp_byte*10);
            local_log.concatf("Set periodic read schedule to once every %dms.\n", temp_byte*10);
          }
          else {
            event_iiu_read.enableSchedule(false);  // Disable the periodic read.
            local_log.concat("Disabled periodic readback.\n");
          }
          break;
      }
      break;

    case 'p':
      {
        parse_mule.concat(str);
        parse_mule.split(",");
        parse_mule.drop_position(0);
        uint8_t start = (temp_byte < 17) ? temp_byte   : 0;
        uint8_t stop  = (temp_byte < 17) ? temp_byte+1 : 17;
        int temp_int  = (parse_mule.count() > 0) ? parse_mule.position_as_int(0) : 255;
        for (uint8_t i = start; i < stop; i++) {
          if (255 != temp_int) {  // The user wants to make a change..
            iius[i].enableProfiling(temp_int ? true:false);
          }
          local_log.concatf("Profiling IIU %d: %sabled.\n", i, (iius[i].enableProfiling() ? "en":"dis"));
        }
      }
      break;

    case 'e':
      if (temp_byte < 17) {
        iius[temp_byte].dumpPreformedElements(&local_log);
      }
      break;


    default:
      EventReceiver::procDirectDebugInstruction(input);
      break;
  }

  flushLocalLog();
}
Exemple #21
0
Bst&
MeChart::
bestParse(Item* itm, FullHist* h, Val* cval, Val* gcval, int cdir)
{
  curVal = cval;
  gcurVal = gcval;
  curDir = cdir;
  Bst& bst = recordedBP(itm, h);
  curVal = gcurVal = NULL;
  curDir = -1;
  if(bst.explored())
    {
      if(printDebug() > 19)
	{
	  prDp();
	  cerr << "already known bestParse(" << *itm << ", ...) has p = "
	       << bst.prob() << endl;
	}
      return bst;
    }
  if(printDebug() > 10)
    {
      prDp();
      cerr << "bestParse(" << *itm << ", ...)" << endl;
    }
  bst.explored() = true;  //David McClosky bug;
  int itermInt = itm->term()->toInt();
  PosMap& pm = itm->posAndheads();
  PosIter pi = pm.begin();
  ECString bestW;
  for( ; pi != pm.end() ; pi++ )
    {
      int posInt = (*pi).first;
      if(printDebug() > 16)
	{
	  prDp();
	  cerr << "consider Pos(" << *itm << ") = " << posInt << endl;
	}
      HeadMap& hm = (*pi).second;
      /* we are using collected counts for p(u|t) */
      float hposprob = 1;
      /* if we have reached a preterminal, then termInt == posInt
	 and p(posInt|termInt) == 1 */
      if( itermInt != posInt)
	{
          curVal = cval;
          gcurVal = gcval;
          curDir = cdir;
	  hposprob = meProb(posInt, h, UCALC); 
	  if(hposprob == 0) hposprob = .00001; //??? this can happen;
          curVal = gcurVal = NULL;
          curDir = -1;
	  if(printDebug() > 16)
	    {
	      prDp();
	      cerr <<  "p(pos) = " <<  hposprob << endl;
	    }
	}
      h->preTerm = posInt;
      HeadIter hi = hm.begin(); 
      for( ;hi != hm.end();hi++)
	{
	  const Wrd& subhw = (*hi).first;
	  int wrdInt = subhw.toInt();
	  ECString subh = subhw.lexeme();
	  if(printDebug() > 16)
	    {
	      prDp();
	      cerr << "consider head(" << *itm << ") = " << subh << endl;
	    }
	  float hprob = 0;
	  if(wrdInt >= 0 && wrdInt <= lastKnownWord)
	    {
	      hprob = pCapgt(&subhw,posInt); 
	      hprob *= (1 - pHugt(posInt)); 
              curVal = cval;
              gcurVal = gcval;
              curDir = cdir;
	      float hprob2 = meHeadProb(wrdInt, h);
              curVal = gcurVal = NULL;
              curDir = -1;
	      hprob *= hprob2;
	      if(hprob < 0)
		{
		  cerr << posInt << " " << pHugt(posInt) <<" "<<hprob2 << endl;
		  assert(hprob >=0);
		}
	    }
	  //hprob can be zero if lower case NNPS.
	  if(wrdInt > lastKnownWord || hprob == 0)
	    {
	      hprob = psutt(&subhw,posInt);
	    }
	  if(printDebug() > 16)
	    {
	      prDp();
	      cerr << "p(hd) = "<< hprob << endl;
	    }
	  float hhprob = (hposprob * hprob);
	  if(hhprob < 0)
	    {
	      cerr << hposprob << " " << hprob << endl;
	      assert(hhprob >= 0);
	    }
	  h->hd = &subhw;
	  Bst&  
	    bst2 = bestParseGivenHead(posInt,subhw,itm,h,(*hi).second,cval,gcval);
          if(bst2.empty()) continue;
          Val* nval = new Val();
	  Val* oldval0 = bst2.nth(0);
          nval->prob() = oldval0->prob()*hhprob;
          nval->bsts().push_back(&bst2);
	  nval->status = EXTRAVAL;
          bst.push(nval);
          bst.sum() += bst2.sum()*hhprob;
	}
    }
  Val* nbest = bst.pop();
  if(nbest) bst.addnth(nbest);
  if(printDebug() > 10)
    {
      prDp();
      cerr << "Bestp for " << *itm << " = " << bst.prob() <<endl;
    }
  return bst;
}
Exemple #22
0
int interpret(tListOfInstr * ilist)
{
  tListItem * listItem = ilist->first;
  tInstr * i;
  while(listItem != NULL)
  {
    i = &listItem->Instruction;
    printDebug("zpracovavam instrukci typu %d\n", i->instType);
    switch(i->instType)
    {
      case I_READ:
        switch(i->type)
        {
          unsigned int size, length;
          char ch;
          case k_int:
            if ( scanf("%d", (int *)i->addr3) != 1) return EXIT_READ_STDIN_ERROR;
            break;
          case k_real:
            if (scanf("%lf", (double *)i->addr3) != 1) return EXIT_READ_STDIN_ERROR;
            break;
          case k_string:
            size = 8; length = 0;
            if ((((string *)i->addr3)->str = realloc(((string *)i->addr3)->str, sizeof(char) * size)) == NULL)
              return EXIT_INTERNAL_ERROR;
            while (EOF != (ch = getchar()) && ch != '\n')
            {
              ((string *)i->addr3)->str[length++] = ch;
              if (length == size)
              {
                if ((((string *)i->addr3)->str = realloc(((string *)i->addr3)->str, sizeof(char) * (size += 8))) == NULL)
                  return EXIT_INTERNAL_ERROR;
              }
            }
            ((string *)i->addr3)->str[length] = '\0';
            if ((((string *)i->addr3)->str = realloc(((string *)i->addr3)->str, sizeof(char) * length)) == NULL)
               return EXIT_INTERNAL_ERROR;
            ((string *)i->addr3)->alloc = length;
            ((string *)i->addr3)->length = length;
            break;
          case k_bool:
            return EXIT_TYPE_ERROR;
          default:
            printDebug("%d", i->type); return EXIT_READ_STDIN_ERROR;
        }
        printDebug("Nacteno ze vstupu.\n");
        break;
      case I_WRITE:
        switch(i->type)
        {
          case k_int:
            printf("%d", *(int *)i->addr1); break;
          case k_real:
            printf("%g", *(double *)i->addr1); break;
          case k_string:
            printf("%s", ((string *)i->addr1)->str); break;
          case k_bool:
            if (*(bool *)i->addr1 == true) printf("TRUE");
            else printf("FALSE");
            break;
          default:
            return EXIT_TYPE_ERROR;
        }
        break;
      case I_JUMP: // instrukce skoku, jen se nastavim na zadanou v adrese (ve volani si beru addr1 = ilist->last)
        if (i->addr1 == NULL || !(*(bool *)i->addr1)) listItem = *(tListItem **)i->addr2;
        break;
      case I_ASSIGN: // isntukce prirazeni, jedina komplikace je string (kopiruju retezec, musim realloc)
        switch(i->type)
        {
          case k_int:
            *(int *)i->addr3 = *(int *)i->addr1;
            break;
          case k_real:
            *(double *)i->addr3 = *(double *)i->addr1;
            break;
          case k_string:
            if (((string *)i->addr3)->alloc < ((string *)i->addr1)->alloc)
            {
              ((string *)i->addr3)->alloc = ((string *)i->addr1)->alloc;
              if ((((string *)i->addr3)->str = realloc(((string *)i->addr3)->str, sizeof(char) * ((string *)i->addr1)->alloc)) == NULL)
                return EXIT_INTERNAL_ERROR;
            }
            strncpy(((string *)i->addr3)->str, ((string *)i->addr1)->str, ((string *)i->addr3)->alloc);
            ((string *)i->addr3)->length = ((string *)i->addr1)->length;
            break;
          case k_bool:
            *(bool *)i->addr3 = *(bool *)i->addr1;
            break;
          default:
            return EXIT_TYPE_ERROR;
        }
        printDebug("prirazuji z adresy %d (hodnota %d) na adresu %d nova hodnota je %d\n", i->addr1, i->addr3, *(int *)i->addr3, *(int *)i->addr3);
        break;
      case I_CALL_FUNCTION: // volani funkce (zaradim instrukce funkce jako nasledujici instrukci a za posledni instrukci fukce zaradim nasledujici instrukci (co by naseldovala v ilistu))
        ((tListOfInstr *)i->addr1)->last->nextItem = listItem->nextItem;
        listItem->nextItem = ((tListOfInstr *)i->addr1)->first;
        break;
      case I_CLEAR: // free nad docasnou hodnotou (u stringu jeste samotny string) -> provede se az pri uklidu na konci, kvuli jumpum...
        //if (i->type == k_string) free(((string *)i->addr1)->str);
        //free(i->addr1);
        break;
      case I_MUL: // jak resit int * real?
        if (i->type == k_int) *(int *)i->addr3 = *(int *)i->addr1 * *(int *)i->addr2;
        else if (i->type == k_real) *(double *)i->addr3 = *(double *)i->addr1 * *(double *)i->addr2;
        else return EXIT_RUNTIME_ERROR;
        break;
      case I_DIV:
        if (i->type == k_int) *(int *)i->addr3 = *(int *)i->addr1 / *(int *)i->addr2;
        else if (i->type == k_real) *(double *)i->addr3 = *(double *)i->addr1 / *(double *)i->addr2;
        else return EXIT_RUNTIME_ERROR;
        break;
      case I_ADD:
        if (i->type == k_int) *(int *)i->addr3 = *(int *)i->addr1 +*(int *)i->addr2;
        else if (i->type == k_real) *(double *)i->addr3 = *(double *)i->addr1 + *(double *)i->addr2;
        else if (i->type == k_string)
        {
          ((string *)i->addr3)->alloc = (((string *)i->addr1)->alloc + ((string *)i->addr2)->alloc);
          if ((((string *)i->addr3)->str = malloc(sizeof(char) * ((string *)i->addr3)->alloc)) == NULL)
            return EXIT_INTERNAL_ERROR;
          strcpy(((string *)i->addr3)->str, ((string *)i->addr1)->str);
          strcat(((string *)i->addr3)->str, ((string *)i->addr2)->str);
        }
        else return EXIT_RUNTIME_ERROR;
        break;
      case I_SUB:
        if(i->type == k_int) *(int *)i->addr3 = *(int *)i->addr1 - *(int *)i->addr2;
        else if(i->type == k_real) *(double *)i->addr3 = *(double *)i->addr1 - *(double *)i->addr2;
        else return EXIT_RUNTIME_ERROR;
        break;
      case I_LESS:
        switch(i->type)
        {
          case k_int: *(bool *)i->addr3 = *(int *)i->addr1 < *(int *)i->addr2; break;
          case k_real: *(bool *)i->addr3 = *(double *)i->addr1 < *(double *)i->addr2; break;
          case k_string: *(bool *)i->addr3 = (strcmp(((string *)i->addr1)->str, ((string *)i->addr2)->str) < EXIT_SUCCESS); break;
          case k_bool: *(bool *)i->addr3 = *(bool *)i->addr1 < *(bool *)i->addr2; break;
          default:
            return EXIT_TYPE_ERROR;
        }
        break;
      case I_GREATER:
        switch(i->type)
        {
          case k_int: *(bool *)i->addr3 = *(int *)i->addr1 > *(int *)i->addr2; break;
          case k_real: *(bool *)i->addr3 = *(double *)i->addr1 > *(double *)i->addr2; break;
          case k_string: *(bool *)i->addr3 = (strcmp(((string *)i->addr1)->str, ((string *)i->addr2)->str) > EXIT_SUCCESS); break;
          case k_bool: *(bool *)i->addr3 = *(bool *)i->addr1 > *(bool *)i->addr2; break;
          default:
            return EXIT_TYPE_ERROR;
        }
        break;
      case I_LESS_EQUAL:
        switch(i->type)
        {
          case k_int: *(bool *)i->addr3 = *(int *)i->addr1 <= *(int *)i->addr2; break;
          case k_real: *(bool *)i->addr3 = *(double *)i->addr1 <= *(double *)i->addr2; break;
          case k_string: *(bool *)i->addr3 = (strcmp(((string *)i->addr1)->str, ((string *)i->addr2)->str) <= EXIT_SUCCESS); break;
          case k_bool: *(bool *)i->addr3 = *(bool *)i->addr1 <= *(bool *)i->addr2; break;
          default:
            return EXIT_TYPE_ERROR;
        }
        break;
      case I_GREATER_EQUAL:
        switch(i->type)
        {
          case k_int: *(bool *)i->addr3 = *(int *)i->addr1 >= *(int *)i->addr2; break;
          case k_real: *(bool *)i->addr3 = *(double *)i->addr1 >= *(double *)i->addr2; break;
          case k_string: *(bool *)i->addr3 = (strcmp(((string *)i->addr1)->str, ((string *)i->addr2)->str) >= EXIT_SUCCESS); break;
          case k_bool: *(bool *)i->addr3 = *(bool *)i->addr1 >= *(bool *)i->addr2; break;
          default:
            return EXIT_TYPE_ERROR;
        }
        break;
      case I_EQUAL:
        switch(i->type)
        {
          case k_int: *(bool *)i->addr3 = *(int *)i->addr1 == *(int *)i->addr2; break;
          case k_real: *(bool *)i->addr3 = *(double *)i->addr1 == *(double *)i->addr2; break;
          case k_string: *(bool *)i->addr3 = (strcmp(((string *)i->addr1)->str, ((string *)i->addr2)->str) == EXIT_SUCCESS); break;
          case k_bool: *(bool *)i->addr3 = *(bool *)i->addr1 == *(bool *)i->addr2; break;
          default:
            return EXIT_TYPE_ERROR;
        }
        break;
      case I_NOT_EQUAL:
        switch(i->type)
        {
          case k_int: *(bool *)i->addr3 = *(int *)i->addr1 != *(int *)i->addr2; break;
          case k_real: *(bool *)i->addr3 = *(double *)i->addr1 != *(double *)i->addr2; break;
          case k_string: *(bool *)i->addr3 = (strcmp(((string *)i->addr1)->str, ((string *)i->addr2)->str) != EXIT_SUCCESS); break;
          case k_bool: *(bool *)i->addr3 = *(bool *)i->addr1 != *(bool *)i->addr2; break;
          default:
            return EXIT_TYPE_ERROR;
        }
        break;
      case I_COPY:
        if (((string *)i->addr1)->length < (*((struct srange *)i->addr2)->length + *((struct srange *)i->addr2)->start)) return EXIT_RUNTIME_ERROR;
        if ((((string *)i->addr3)->str = realloc(((string *)i->addr3)->str, *((struct srange *)i->addr2)->length * sizeof(char))) == NULL)
          return EXIT_INTERNAL_ERROR;
        strncpy(&((string *)i->addr3)->str[*((struct srange *)i->addr2)->start], ((string *)i->addr1)->str, *((struct srange *)i->addr2)->length);
        ((string *)i->addr3)->length = *((struct srange *)i->addr2)->length;
        break;
      case I_FIND:
        if(!strlen(((string *)i->addr2)->str) || !strlen(((string *)i->addr1)->str) || 
          ((strlen(((string *)i->addr1)->str)) < (strlen(((string *)i->addr2)->str)))) return EXIT_RUNTIME_ERROR;
        *(int *)i->addr3 = findSubString(((string *)i->addr2)->str, ((string *)i->addr1)->str);
        break;
      case I_SORT:
        if (((string *)i->addr1)->length <= 1) return EXIT_INTERNAL_ERROR; //zkopirovat string
        else
        {
          //alloc na cilovy string
          if (((string *)i->addr3)->str != NULL) free(((string *)i->addr3)->str);
          if ((((string *)i->addr3)->str = malloc(sizeof(char) * ((string *)i->addr1)->alloc)) == NULL)
            return EXIT_INTERNAL_ERROR;

          // zkopiruju string a seradim ho
          ((string *)i->addr3)->length = ((string *)i->addr1)->length;
          strcpy(((string *)i->addr3)->str, ((string *)i->addr1)->str);
          shellSort(((string *)i->addr3)->str, ((string *)i->addr3)->length);
        }
        break;
      case I_TABLE_BACKUP:
        stackPUSH((stack *)i->addr3, (btree *)i->addr1);
        break;
      case I_TABLE_RESTORE:
        stackPOP((stack *)i->addr3, (btree *)i->addr1, (char *)i->addr2);
        break;
      default:
        return EXIT_INTERNAL_ERROR;
    }
    listItem = listItem->nextItem;
  }
  return EXIT_SUCCESS;
}
Exemple #23
0
float
MeChart::
meProb(int cVal, FullHist* h, int whichInt)
{
  if(printDebug() > 68)
    {
      prDp();
      cerr << "meP" << whichInt << "(" << cVal << " | " << *h << ")" <<endl;
    }
  FeatureTree* ginfo[MAXNUMFS];  
  ginfo[0] = FeatureTree::roots(whichInt);
  float smoothedPs[MAXNUMFS];
  Feature::whichInt = whichInt;

  float ans = 1;
 
  for(int i = 1 ; i <= Feature::total[whichInt] ; i++)
    {
      int knp = useKn(i,whichInt);
      ginfo[i] = NULL;
      Feature* feat = Feature::fromInt(i, whichInt); 
      /* e.g., g(rtlu) starts from where g(rtl) left off (after tl)*/
      int searchStartInd = feat->startPos;

      if(i > 1) smoothedPs[i] = smoothedPs[i-1];
      FeatureTree* strt = ginfo[searchStartInd];
      if(!strt)
	{
	  continue;
	}
      SubFeature* sf = SubFeature::fromInt(feat->subFeat, whichInt);
      int nfeatV = (*(sf->fun))(h);
      FeatureTree* histPt = strt->follow(nfeatV, feat->auxCnt); 
      ginfo[i] = histPt;
      if(i == 1)
	{
	  smoothedPs[0] = 1;
	  if(!histPt)
	    {
	      cerr << cVal << " " << whichInt << " " << nfeatV << " " << searchStartInd <<" " << feat->auxCnt << endl;
	      assert(histPt);
	    }
	  Feat* f =histPt->feats.find(cVal);
	  if(!f)
	    {
	      if(printDebug() > 60)
		{
		  prDp();
		  cerr << "Zero p" << feat->name << " " << nfeatV << endl;
		}
	      if(whichInt == HCALC) return 0.001;
	      return 0.0;
	    }
	  smoothedPs[1] = f->g();
	  if(printDebug() > 68)
	    {
	      prDp();
	      cerr << i << " " << nfeatV << " " << smoothedPs[1] << endl;
	    }
	  for(int j = 2; j <= Feature::total[whichInt] ; j++)
	    smoothedPs[j] = 0;
	  ans = smoothedPs[1];
	  continue;
	}
      if(!histPt)
	{
	  continue;
	}

      int b;
      if(Feature::isLM)
	{
	  /* this section for new bucketing */
	  float sz = (float)histPt->feats.size();
	  float estm = (float)histPt->count / sz;
	  b = bucket(estm, whichInt,i);
	}
      else
	{
	  /* this section for old bucketing */
	  float estm = histPt->count * smoothedPs[1];
	  b = bucket(estm);
	}

      Feat* ft = histPt->feats.find(cVal);
      float unsmoothedVal;
      if(!ft) unsmoothedVal = 0;
      else unsmoothedVal = ft->g();
      float lam = 1;
      if(!knp) lam = Feature::getLambda(whichInt, i, b);
      float uspathprob = lam*unsmoothedVal;

      float osmoothedVal;
      /* First version is for parsing, second for language modeling */
      if(Feature::isLM)
	osmoothedVal = smoothedPs[i-1]; //for deleted interp.
      else osmoothedVal = smoothedPs[searchStartInd];

      float oneMlam = (1-lam);
      if(knp)
        {
          oneMlam = histPt->count/1000.0;
        }

      float smpathprob = oneMlam*osmoothedVal;
      float nsmoothedVal = uspathprob+smpathprob;
      smoothedPs[i] = nsmoothedVal;
      ans *= (nsmoothedVal/osmoothedVal);

      if(printDebug() > 68)
	{
	  prDp();
	  cerr << i << " " << nfeatV << " "
	       << b <<" "<<unsmoothedVal << " " << lam << " " 
	       << nsmoothedVal <<  endl;
	}
    }
  if(whichInt == HCALC) ans *= 600;
  if(printDebug() > 30)
    {
      prDp();
      cerr<<"p"<<whichInt<< "(" << cVal << "|" << *h << ") = " << ans << endl;
    }
  return ans;
}
Exemple #24
0
double
Bchart::
parse()
{
    alreadyPopedNum = 0;
    SentRepIter     sri(sentence_);
    
    bool   haveS = false;
    int locTimeout = ruleiCountTimeout_;
    int count = 0;
    for (;; count ++)
    {
      //check();
      if( ruleiCounts_ > locTimeout )
	{
	  break;
	}

      if(get_S() && !haveS)
	{
	  // once we have found a parse, the total edes is set to edges * 3.5;
	  haveS = true;
	  if(printDebug(10)) cerr << "Found S " << popedEdgeCount_ << endl;
	  popedEdgeCountAtS_ = popedEdgeCount_;
	  totEdgeCountAtS_ = ruleiCounts_;
	  int newTime = (int)(ruleiCounts_ * timeFactor);  
	  if(newTime < ruleiCountTimeout_)
	    locTimeout = newTime;
	}
      // We keep track of number of ruleis to decide when time out on parsing.;
      /* get best thing off of keylist */
      Edge* edge = heap->pop(); 
      if (!edge)
	{
	  break;
	}
      int stus = edge->status();
      int cD = curDemerits_[edge->start()][edge->loc()];
      if(edge->demerits() < cD - 5 && !haveS)
	{
	  edge->demerits() = cD;
	  edge->setmerit();
	  heap->insert(edge);
	  continue;
	}
      if(alreadyPopedNum >= 400000)
	{
	  cerr << "alreadyPoped got too large" << endl;
	  break;
	}
      if(printDebug() > 10)
	{
	  cerr << popedEdgeCount_ << "\tPop";
	  if(stus == 0) cerr << "< ";
	  else if(stus == 2) cerr << ". ";
	  else cerr << "> ";
	  cerr << *edge << "\t" << edge->prob() << "\t" << edge->merit();
	  cerr << endl;
	}
      popedEdgeCount_++;
      alreadyPoped[alreadyPopedNum++] = edge;
      if(!haveS) addToDemerits(edge);
      /* and add it to chart */
      //heap->check();
      switch (stus)
	{
	  case 0 : add_edge(edge, 0); break; //0 => continuing left;
	  case 1 : add_edge(edge, 1); break; //1 => continung right;
	  case 2 : addFinishedEdge(edge);
	}
    }

    /* at this point we are done looking for edges etc. */
    Item           *snode = get_S();
    /* No "S" node means the sentence was unparsable. */
    if (!snode)
	return badParse;
    double          ans = snode->prob();

    if (ans <= 0.0L)
	error("zero probability parse?");
    /*
    ans = -log2(ans);
    if (ans == quiet_nan(0L))
	error("log returned quiet_nan()");
    */
    static double	nat_log_2 = log( 2.0 );
    ans = -log( ans )/ nat_log_2;
    crossEntropy_ = ans;
    return ans;
}
Exemple #25
0
void serial_update(void){
    static uchar fnNum = 0;
    static uint byteNum;
    static uchar buffer[32];
    uint ack;
    uchar read; 
    if(rxQueueTail == rxQueueHead){
    	return;
    }
    // FIFO
    read = rxQueue[rxQueueHead];
    if(++rxQueueHead >= rxQueueSize)
    	rxQueueHead = 0;
	
    // If this is the first byte, translate the command number to
    // its correspondent position in the commands array
    if(waiting_tkn){
        byteNum = 0;
        waiting_tkn = False;
        fnNum = 0;

        printDebug("Inicio de funcion\r\n");

        switch(read){
        	case (DATA | PRECODED | INTERLACED_BURST):
            case (DATA | INTERLACED_BURST): 			fnNum++;
            case (DATA | PRECODED | BURST):
            case (DATA | BURST):                        fnNum++;
            case (DATA | PRECODED | WRITE_SECTION):
            case (DATA | WRITE_SECTION):                fnNum++;
            case (DATA | PRECODED | WRITE_COLUMN):
            case (DATA | WRITE_COLUMN):                 fnNum++;
            case (COMMAND | SET | DIMM):         		fnNum++;
            case (COMMAND | SET | SPEED):         		fnNum++;
            case (COMMAND | SET | TOTAL_WIDTH):         fnNum++;
            case (COMMAND | SET | DEPTH):               fnNum++;
            case (COMMAND | SET | WIDTH):               fnNum++;
            case (COMMAND | SET | HEIGHT):              fnNum++;
            case (COMMAND | GET | DIMM):         		fnNum++;
            case (COMMAND | GET | SPEED):         		fnNum++;
            case (COMMAND | GET | TOTAL_WIDTH):         fnNum++;
            case (COMMAND | GET | DEPTH):               fnNum++;
            case (COMMAND | GET | WIDTH):               fnNum++;
            case (COMMAND | GET | HEIGHT):              fnNum++;
            case (COMMAND | SET | STORE):               fnNum++;
            case (COMMAND | SET | CLEAN):               fnNum++;
            case (COMMAND | GET | FPS):                 fnNum++;
            case (COMMAND | GET | PING):                break;

            default:
                waiting_tkn = True;
        }
    }
    // Call the function if there's any selected
    // and send the response if it has finished
    if (!waiting_tkn){
        receivedLastSecond = True;
    	// Stop blinking while we receive the data,
    	// so we have the time to process it
    	//LED_enabled = 0;
    	
    	waiting_tkn = commands[fnNum](read,buffer,byteNum++,&ack);
    	if (waiting_tkn){
			SCI_WRITE((uchar)(ack>>8));
			SCI_WRITE((uchar)(ack&0xFF));
        	// Stop blinking while we receive the data,
        	// so we have the time to process it
        	//LED_enabled = 1;
		}
    }
Exemple #26
0
/*
 * Sort the list of user timers so that the ones
 * going to expires soonest are at the start using
 * a simple bubble sort.
 *
 * IMPORTANT: the lockLinkedLists mutex MUST be held
 * by the calling function!!!  It is not grabbed
 * here as this function is only called from places
 * where it is already held and recursive mutexes appear
 * to be only unreliably present in Linux.
 */
static void sortUsedListUnprotected (void)
{
    UInt32 x = 0;
    UInt32 i = 0;
    UInt32 z = 0;
    TimerEntry * pEntry = pgUsedTimerListHead;
    UInt32 sortingStartNanoSeconds;

    sortingStartNanoSeconds = getProcessTimeNanoSeconds();

    printDebug ("sortUsedList: starting...\n");
    for (x = 0; (pEntry != PNULL) && (x < (MAX_NUM_TIMERS * MAX_NUM_TIMERS)); x++)
    {
        if ((pEntry->pNextEntry != PNULL) && (pEntry->timer.expiryTimeDeciSeconds > pEntry->pNextEntry->timer.expiryTimeDeciSeconds))
        {
            TimerEntry * pThisEntry = pEntry;
            TimerEntry * pNextEntry = pEntry->pNextEntry;

            z++;
            printDebug ("sortUsedList: swapping entry %d (%d, 0x%08x) with entry %d (%d, 0x%08x).\n", i, pEntry->timer.expiryTimeDeciSeconds, &(pEntry->timer), i + 1, pNextEntry->timer.expiryTimeDeciSeconds, &(pNextEntry->timer));
            /* If this entry has a later expiry time than the next one, swap them */
            if (pThisEntry->pPrevEntry != PNULL)
            {
                pThisEntry->pPrevEntry->pNextEntry = pNextEntry;
            }
            if (pNextEntry->pNextEntry != PNULL)
            {
                pNextEntry->pNextEntry->pPrevEntry = pThisEntry;
            }
            pThisEntry->pNextEntry = pNextEntry->pNextEntry;
            pNextEntry->pPrevEntry = pThisEntry->pPrevEntry;
            pThisEntry->pPrevEntry = pNextEntry;
            pNextEntry->pNextEntry = pThisEntry;            
            
            /* If we have just changed the head, swap it around too */
            if (pThisEntry == pgUsedTimerListHead)
            {
                pgUsedTimerListHead = pNextEntry;
            }
            
            /* Restart the sort from the beginning */
            pEntry = pgUsedTimerListHead;
            i = 0;
        }
        else
        {
            pEntry = pEntry->pNextEntry;
            i++;
        }
    }
    
    if (x == MAX_NUM_TIMERS * MAX_NUM_TIMERS)
    {
        printDebug ("sortUsedList: WARNING, sorting the timer list hit the buffers (%d iteration(s) (%d swap(s)), %d microsecond(s)).\n", x, z, (getProcessTimeNanoSeconds() - sortingStartNanoSeconds) / 1000);
    }
    else
    {
        printDebug ("sortUsedList: sorting the timer list took %d iteration(s) (%d swap(s)), %d microsecond(s).\n", x, z, (getProcessTimeNanoSeconds() - sortingStartNanoSeconds) / 1000);        
    }
    printDebugUsedTimerListUnprotected();
}
Exemple #27
0
float
Bchart::
meFHProb(const Term* trm, FullHist& fh, int whichInt)
{
  Edge* edge = fh.e;
  int pos = 0;
  /* the left to right position we are working on is either the far left (0)
     or the far right */
  if(!globalGi) {}
  //else if(edge->item() != globalGi->index(0)) ;
  else if(whichInt == RUCALC || whichInt == RMCALC || whichInt == RCALC)
    pos = globalGi->size()-1;
  fh.pos = pos;

  int cVal = trm->toInt();
  if(printDebug() > 138)
    {
      cerr << "meP " << *trm << " " << cVal << " " << whichInt << " ";
      if(edge) cerr << *edge << endl;
      else cerr << fh.preTerm  << endl;
    }
  //int subfVals[MAXNUMFS];
  FeatureTree* ginfo[MAXNUMFS];  
  ginfo[0] = FeatureTree::roots(whichInt);
  assert(ginfo[0]);
  float smoothedPs[MAXNUMFS];

  float ans = 1;

  for(int i = 1 ; i <= Feature::total[whichInt] ; i++)
    {
      ginfo[i] = NULL;
      Feature* feat = Feature::fromInt(i, whichInt); 
      /* e.g., g(rtlu) starts from where g(rtl) left off (after tl)*/
      int searchStartInd = feat->startPos;

      FeatureTree* strt = ginfo[searchStartInd];
      if(!strt)
	{
	  continue;
	}
      SubFeature* sf = SubFeature::fromInt(feat->subFeat, whichInt);
      int usf = sf->usf;
      int nfeatV = (edgeFnsArray[usf])(&fh);
      FeatureTree* histPt = strt->follow(nfeatV, feat->auxCnt); 
      ginfo[i] = histPt;
      if(i == 1)
	{
	  smoothedPs[0] = 1;
	  assert(histPt);
	  Feat* f =histPt->feats.find(cVal);
	  if(!f)
	    {
	      return 0.0;
	    }
	  smoothedPs[1] = f->g();
	  if(printDebug() > 238)
	    {
	      cerr << i << " " << nfeatV << " " << smoothedPs[1] << endl;
	    }
	  for(int j = 2; j <= Feature::total[whichInt] ; j++)
	    smoothedPs[j] = 0;
	  ans = smoothedPs[1];
	  continue;
	}
      if(nfeatV < -1)
	{
	  if(printDebug() > 128)
	    {
	      cerr<<"p"<<whichInt<< "(" << cVal << "|";
	      if(edge) cerr << *edge;
	      else cerr << fh.preTerm;
	      cerr << ") = " << ans << endl;
	    }
	  return ans;
	}
      if(!histPt)
	{
	  continue;
	}

      int b;

      if(Feature::isLM)
	{
	  /*new bucketing */
	  float sz = (float)histPt->feats.size();
	  float estm = (float)histPt->count / sz;
	  assert(i >= 2);
	  b = bucket(estm, whichInt,i);
	}
      else
	{
	  /* old bucketing*/
	  float estm;
	  //estm = histPt->count * smoothedPs[1];
	  estm = histPt->count * 0.1;
	  b = bucket(estm);
	}

      Feat* ft = histPt->feats.find(cVal);
      float unsmoothedVal;
      if(!ft) unsmoothedVal = 0;
      else unsmoothedVal = ft->g();
      float lam = Feature::getLambda(whichInt, i, b);
      float uspathprob = lam*unsmoothedVal;
      float osmoothedVal = smoothedPs[searchStartInd];
      //float osmoothedVal = smoothedPs[i-1]; //for deleted interp.
      float smpathprob = (1-lam)*osmoothedVal;
      float nsmoothedVal = uspathprob+smpathprob;
      if(printDebug() > 238)
	{
	  cerr << i << " " << nfeatV << " " << usf << " "
	       << b <<" "<<unsmoothedVal << " " << lam << " " 
	       << nsmoothedVal <<  endl;
	}
      smoothedPs[i] = nsmoothedVal;
      ans *= (nsmoothedVal/osmoothedVal);
    }
  if(printDebug() > 128)
    {
      cerr<<"p"<<whichInt<< "(" << cVal << "|";
      if(edge) cerr << *edge;
      else cerr << fh.preTerm;
      cerr << ") = " << ans << endl;
    }
  return ans;
}
Exemple #28
0
/*
 * Allocate a timer and re-sort the timer list.
 * 
 * periodDeciSeconds  the timer period in deciSeconds
 * sourcePort         the port to send the expiry message to
 * id                 the id for the timer
 * pExpiryMsg         a pointer to the expiry message to send
 * 
 * @return  a pointer to the timer or PNULL if
 *          unable to allocate one.
 */
static Timer * allocTimer (UInt32 periodDeciSeconds, SInt32 sourcePort, TimerId id, ShortMsg * pExpiryMsg)
{
    Timer * pAlloc = PNULL;
    UInt32 x = 0;
    TimerEntry * pEntry;
    TimerEntry * pPrevEntry = PNULL;

    ASSERT_PARAM (pExpiryMsg != PNULL, (unsigned long) pExpiryMsg);
    
    pthread_mutex_lock (&lockLinkedLists);
    pEntry = pgFreeTimerListHead; /* Assign this here in case it has been changed by whoever held the lock */

    printDebug ("allocTimer: finding entry in the free list...\n");
    /* Find the entry at the end of the free list. TODO quicker to take it from the front */
    for (x = 0; (pEntry != PNULL) && (x < MAX_NUM_TIMERS); x++)
    {
        pPrevEntry = pEntry;
        pEntry = pEntry->pNextEntry;
    }

    /* If there is one, move it to the used list */
    if (pPrevEntry != PNULL)
    {
        TimerEntry * pWantedEntry = pPrevEntry;
        TimerEntry ** ppEntry = PNULL;

        /* Unlink it from the end of the free list */
        if (pWantedEntry->pPrevEntry != PNULL)
        {
            pWantedEntry->pPrevEntry->pNextEntry = pWantedEntry->pNextEntry;
        }
        if (pWantedEntry == pgFreeTimerListHead) /* Deal with empty free list case */
        {
            pgFreeTimerListHead = PNULL;
        }        

        /* Attach it to the end of the used list */
        ppEntry = &pgUsedTimerListHead;
        pPrevEntry = PNULL;
        for (x = 0; (*ppEntry != PNULL) && (x < MAX_NUM_TIMERS); x++)
        {
            pPrevEntry = *ppEntry; 
            ppEntry = &((*ppEntry)->pNextEntry);
        }

        if (*ppEntry == PNULL)
        {
            *ppEntry = pWantedEntry;
            pWantedEntry->pPrevEntry = pPrevEntry;
            pWantedEntry->pNextEntry = PNULL;
            pAlloc = &(pWantedEntry->timer);
            
            /* Copy the data in */
            pAlloc->expiryTimeDeciSeconds = gTimerTickDeciSeconds + periodDeciSeconds;
            pAlloc->id = id;
            pAlloc->sourcePort = sourcePort;
            memcpy (&(pAlloc->expiryMsg), pExpiryMsg, sizeof (pAlloc->expiryMsg));

            printDebug ("allocTimer: timer should expire at tick %d.\n", pAlloc->expiryTimeDeciSeconds);

            /* Now sort the list */
            sortUsedListUnprotected();
        }
        else
        {
            ASSERT_ALWAYS_PARAM (x);   
        }
    }
    
    pthread_mutex_unlock (&lockLinkedLists);

    return pAlloc;
}
Exemple #29
0
int _tmain(int argc, _TCHAR* argv[])
{

	printDebug();
	return 0;
}
void MainWindow::createPlayers() {
	printDebug("MainWindow::createPlayers: start");

	// initiate battlefield infomation
	playerCount = GUIStaticData::getPlayerCount();
	playerIndex = GUIStaticData::getHumanIndex();

	// initiate myself
	zhuangbeiA = new ZhuangbeiArea(this, zhuangbeiArea);
	wujiangA = new WujiangArea(playerIndex, wujiangArea);
	innerAI = Interface::createInterface(playerIndex - 1,
			wujiangA->getHeroType(), true);

	// initiate others
	switch (playerCount - 1) {
	case 1:
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 0) % playerCount + 1,
						playerFrame4));
		break;
	case 2:
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 0) % playerCount + 1,
						playerFrame3));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 1) % playerCount + 1,
						playerFrame4));
		centralPlayerLayout->removeItem(player5spacer);
		playerFrame5->hide();
		break;
	case 3:
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 0) % playerCount + 1,
						playerFrame3));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 1) % playerCount + 1,
						playerFrame4));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 2) % playerCount + 1,
						playerFrame5));
		break;
	case 4:
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 0) % playerCount + 1,
						playerFrame2));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 1) % playerCount + 1,
						playerFrame3));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 2) % playerCount + 1,
						playerFrame4));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 3) % playerCount + 1,
						playerFrame6));
		centralPlayerLayout->removeItem(player5spacer);
		playerFrame5->hide();
		break;
	case 5:
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 0) % playerCount + 1,
						playerFrame2));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 1) % playerCount + 1,
						playerFrame3));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 2) % playerCount + 1,
						playerFrame4));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 3) % playerCount + 1,
						playerFrame5));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 4) % playerCount + 1,
						playerFrame6));
		break;
	case 6:
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 0) % playerCount + 1,
						playerFrame1));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 1) % playerCount + 1,
						playerFrame2));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 2) % playerCount + 1,
						playerFrame3));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 3) % playerCount + 1,
						playerFrame4));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 4) % playerCount + 1,
						playerFrame6));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 5) % playerCount + 1,
						playerFrame7));
		centralPlayerLayout->removeItem(player5spacer);
		playerFrame5->hide();
		break;
	case 7:
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 0) % playerCount + 1,
						playerFrame1));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 1) % playerCount + 1,
						playerFrame2));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 2) % playerCount + 1,
						playerFrame3));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 3) % playerCount + 1,
						playerFrame4));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 4) % playerCount + 1,
						playerFrame5));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 5) % playerCount + 1,
						playerFrame6));
		otherPlayerAreaVector.push_back(
				new PlayerArea((playerIndex + 6) % playerCount + 1,
						playerFrame7));
		break;
	}

	// display role label
	int zhugongNum = 0, zhongchenNum = 0, fanzeiNum = 0, neijianNum = 0;
	for (int i = 1; i <= playerCount; ++i) {
		switch (GUIStaticData::getPlayerRole(i)) {
		case sgs::ConstData::ZHU:
			++zhugongNum;
			break;
		case sgs::ConstData::ZHONG:
			++zhongchenNum;
			break;
		case sgs::ConstData::FAN:
			++fanzeiNum;
			break;
		case sgs::ConstData::NEI:
			++neijianNum;
			break;
		default:
			break;
		}
	}

	connect(wujiangA, SIGNAL(skillClicked(sgs::ConstData::HeroSkill, int)),
			this, SLOT(skillClicked(sgs::ConstData::HeroSkill, int)));
	QApplication::processEvents();
	sleepSomeTime(GUIStaticData::createPlayerDuration);
	for (std::vector<PlayerArea *>::iterator iter =
			otherPlayerAreaVector.begin(); iter != otherPlayerAreaVector.end();
			++iter) {
		(*iter)->show();
	}
	zhuangbeiA->show();
	wujiangA->show();
	roleFrame->setupRole(zhugongNum, zhongchenNum, fanzeiNum, neijianNum);
	cardDeckLabel->show();
	GUIStaticData::setPlayersCreated();

	printDebug("MainWindow::createPlayers: over");
}