Esempio n. 1
0
bool Contest::setupPrizes(void) {

#ifdef DEBUG
  stringstream debug;
#endif

	PrizeNames.push_back("Nothing");
  PrizeNames.push_back("Ringtones");
	PrizeNames.push_back("Obsolete");
	PrizeNames.push_back("Philips MP3 player");
	PrizeNames.push_back("Philips Home Cinema");
	PrizeNames.push_back("Peugeot 206 CC");

	size_t ind = 0;
	TimePeriod tp;
	giftDetails p;
	stringstream index;
	while (ind < EOD.size() -1) {
		tp = TimePeriod(EOD[ind], EOD[ind+1]);
		index << EOD[ind].toString(true) << ":" << giftDetails::ID_MINUTEPRIZES;
		p = giftDetails(giftDetails::ID_MINUTEPRIZES, PrizeNames[giftDetails::ID_MINUTEPRIZES], tp, MINUTEPRIZES, MINUTEPRIZES);
		Prizes.insertObject(index.str(), p);
#ifdef EXTRADEBUG
		debug << index.str() << ": ";
		debug << p.insertString() << endl;
	  logMsg(debug.str());
	  debug.str("");
#endif

/*    index.str("");
		index << current.toString(true) << ":" << giftDetails::ID_HOURLYPRIZES;
		p = giftDetails(giftDetails::ID_HOURLYPRIZES, PrizeNames[giftDetails::ID_HOURLYPRIZES], tp, HOURLYPRIZES, HOURLYPRIZES);
		Prizes.insertObject(index.str(), p);
#ifdef EXTRADEBUG
		debug << index.str() << ": ";
		debug << p.insertString() << endl;
	  logMsg(debug.str());
	  debug.str("");
#endif*/

    index.str("");
		index << EOD[ind].toString(true) << ":" << giftDetails::ID_DAILYPRIZES;
		p = giftDetails(giftDetails::ID_DAILYPRIZES, PrizeNames[giftDetails::ID_DAILYPRIZES], tp, DAILYPRIZES, DAILYPRIZES);
		Prizes.insertObject(index.str(), p);
#ifdef EXTRADEBUG
		debug << index.str() << ": ";
		debug << p.insertString() << endl;
	  logMsg(debug.str());
	  debug.str("");
#endif
		ind++;
	  index.str("");
	}

	ind = 0;
 	while (ind < EOW.size()-1) {
		tp = TimePeriod(EOW[ind], EOW[ind+1]);
		index << EOW[ind].toString(true) << ":" << giftDetails::ID_WEEKLYPRIZES;
		p = giftDetails(giftDetails::ID_WEEKLYPRIZES, PrizeNames[giftDetails::ID_WEEKLYPRIZES], tp, WEEKLYPRIZES, WEEKLYPRIZES);
		Prizes.insertObject(index.str(), p);
#ifdef EXTRADEBUG
		debug << index.str() << ": ";
		debug << p.insertString() << endl;
	  logMsg(debug.str());
	  debug.str("");
#endif
		ind++;
	  index.str("");
	}
  
	tp = TimePeriod(EOW[ind], EOC);
 	index << EOW[ind].toString(true) << ":" << giftDetails::ID_WEEKLYPRIZES;
 	p = giftDetails(giftDetails::ID_WEEKLYPRIZES, PrizeNames[giftDetails::ID_WEEKLYPRIZES], tp, WEEKLYPRIZES, WEEKLYPRIZES);
 	Prizes.insertObject(index.str(), p);
#ifdef EXTRADEBUG
  debug << index.str() << ": ";
  debug << p.insertString() << endl;
  logMsg(debug.str());
  debug.str("");
#endif
 	ind++;
  index.str("");

	ind = 0;
 	while (ind < EOM.size() -1) {
		tp = TimePeriod(EOM[ind], EOM[ind+1]);
		index << EOM[ind].toString(true) << ":" << giftDetails::ID_MONTHLYPRIZES;
		p = giftDetails(giftDetails::ID_MONTHLYPRIZES, PrizeNames[giftDetails::ID_MONTHLYPRIZES], tp, MONTHLYPRIZES, MONTHLYPRIZES);
		Prizes.insertObject(index.str(), p);
#ifdef EXTRADEBUG
		debug << index.str() << ": ";
		debug << p.insertString() << endl;
	  logMsg(debug.str());
	  debug.str("");
#endif
		ind++;
	  index.str("");
	}

#ifdef DEBUG
	debug.str("");
	string colname = "qty_rem";
	string iname = "gid";
	stringstream val;
  for (u_int i = giftDetails::ID_MINUTEPRIZES; i <= giftDetails::ID_MONTHLYPRIZES; i++) {
    val.str("");
    val << i;
   	debug << dec << "There are " << Prizes.sumColumn(val.str(), iname, colname)
	  			<< " " << PrizeNames[i] << " available" << endl;
  }
  logMsg(debug.str());
#endif

	return true;
}
Esempio n. 2
0
static void
__download()
{
  int i1, i2, i3;
  char *ch, tmp[64];

#ifdef POLLING_MODE
  rol->poll = 1;
#else
  rol->poll = 0;
#endif

  printf("\n>>>>>>>>>>>>>>> ROCID=%d, CLASSID=%d <<<<<<<<<<<<<<<<\n",rol->pid,rol->classid);
  printf("CONFFILE >%s<\n\n",rol->confFile);
  printf("LAST COMPILED: %s %s\n", __DATE__, __TIME__);

  printf("USRSTRING >%s<\n\n",rol->usrString);

  /* if slave, get fiber port number from user string */
#ifdef TI_SLAVE
  ti_slave_fiber_port = 1; /* default */

  ch = strstr(rol->usrString,"fp=");
  if(ch != NULL)
  {
    strcpy(tmp,ch+strlen("fp="));
    printf("tmp >>>>>>>>>>>>>>>>>>>>>%s<<<<<<<<<<<<<<<<<<<<<\n",tmp);
    ti_slave_fiber_port = atoi(tmp);
    printf("ti_slave_fiber_port =%d\n",ti_slave_fiber_port);
    tiSetFiberIn_preInit(ti_slave_fiber_port);
  }
#endif

  /*
  printf("rol1: downloading DDL table ...\n");
  clonbanks_();
  printf("rol1: ... done.\n");
  */

  /**/
  CTRIGINIT;

  /* initialize OS windows and TI board */
#ifdef VXWORKS
  CDOINIT(TIPRIMARY);
#else
  CDOINIT(TIPRIMARY,TIR_SOURCE);
#endif


  /************/
  /* init daq */

  daqInit();
  DAQ_READ_CONF_FILE;


  /*************************************/
  /* redefine TI settings if neseccary */

#ifndef TI_SLAVE
  /* TS 1-6 create physics trigger, no sync event pin, no trigger 2 */
vmeBusLock();
  tiLoadTriggerTable(3);
  tiSetTriggerWindow(14);	// (7+1)*4ns trigger it coincidence time to form trigger type
  /*
  tiSetTriggerHoldoff(1,20,1);
  tiSetTriggerHoldoff(2,0,1);
  tiSetTriggerHoldoff(3,0,1);
  tiSetTriggerHoldoff(4,0,1);
  */
//  tiAddSlave(7);
//  tiAddSlave(8);
  
vmeBusUnlock();
#endif


  /*********************************************************/
  /*********************************************************/

#ifdef USE_PRAD
  /* (width + 3)*4 ns, 300 ns width */
vmeBusLock();
  tiSetPromptTriggerWidth(60);
  int ii;
  for(ii = 1; ii <= 6; ++ii)
    tiSetTSInputDelay(ii, 0);
vmeBusUnlock();
#endif


  /* set wide pulse */
vmeBusLock();
/*sergey: WAS tiSetSyncDelayWidth(1,127,1);*/
/*worked for bit pattern latch tiSetSyncDelayWidth(0x54,127,1);*/
vmeBusUnlock();

  usrVmeDmaSetConfig(2,5,1); /*A32,2eSST,267MB/s*/
  /*usrVmeDmaSetConfig(2,5,0);*/ /*A32,2eSST,160MB/s*/
  /*usrVmeDmaSetConfig(2,3,0);*/ /*A32,MBLT*/



  /*
if(rol->pid==18)
{
  usrVmeDmaSetConfig(2,3,0);
}
  */


  /*
  usrVmeDmaSetChannel(1);
  printf("===== Use DMA Channel %d\n\n\n",usrVmeDmaGetChannel());
  */

  tdcbuf = (unsigned int *)i2_from_rol1;



  /******************/
  /* USER code here */




#ifdef USE_PRAD

vmeBusLock();

 dsc2Init(0x400000,0x80000,5,0/*1<<19*/);
  ndsc2 = dsc2GetNdsc();
  printf("!!!!!!!!!!! ndsc2=%d\n",ndsc2);
  if(ndsc2>0)
  {
    DSC2_READ_CONF_FILE;
    ndsc2_daq = dsc2GetNdsc_daq();
    printf("!!!!!!!!!!! ndsc2_daq=%d\n",ndsc2_daq);
  }
 printf("Set Gate Source... \n");
 dsc2SetGateSource(9, 1, 1);
 //dsc2SetGateSource(9, 2, 3);
/*
  dsc2Init(0x480000,0x80000,5,1<<19);
  int dsc_ch, dsc_sl;
  for(dsc_ch = 0; dsc_ch < 6; ++dsc_ch)
      dsc2SetThreshold(0, dsc_ch, 100, TDCTRG);
  for(dsc_sl = 1; dsc_sl < 5; ++dsc_sl) {
      dsc2SetDelay(dsc_sl, 0, 3);
      for(dsc_ch = 0; dsc_ch < 16; ++dsc_ch)
          dsc2SetThreshold(dsc_sl, dsc_ch, 10, TDCTRG);
  }
  dsc2SetChannelMask(0,0xffff,TDCTRG);
  dsc2SetChannelORMask(0,0xffff,TDCTRG);
  dsc2Status(0,0);
*/
vmeBusUnlock();

#ifdef USE_V767
  /*****************
   *  V767 SETUP
   *****************/
/*vmeBusLock();*/
  v767Init(V767_ADDR1,V767_OFF,1,0);
  // turn off test mode
  v767WriteMicro(0, 0x0200);
  /* select stop trigger matching, substraction of trigger time,
     all channels on, autoload on, and save configuration */
//  v767SetAcqMode(0,0);
//  v767SetDReadyMode(0,0); 
  /*     v767BusErrEnable(0); */
  /*     v767SetBLKEndMode(0, 1);  */
  /*     v767AutoloadDisable(itdc); */
  /*     v767AddrRotary(itdc); */
//  v767SetEdgeDetectionMode(0,1);
  /*     v767OverlapTrigDisable(itdc); */
  v767TriggerConfig(0,2000,1000,0);
  /*     v767ChannelMask(itdc,channelmask);  */
  v767Status(0, 0, 0);
//  v767TriggerConfig(0,0,0,0); /* Print current trigger config */
  printf("v767 8\n");fflush(stdout);
/*vmeBusUnlock();*/
  /*     v767SaveConfig(itdc); */
#endif

#ifdef USE_V1190
vmeBusLock();
    tdc1190Init(V1190_ADDR1, V1190_OFF, 1, 0);
    TDC_READ_CONF_FILE;
vmeBusUnlock();
#endif

#endif /* USE_PRAD */




  sprintf(rcname,"RC%02d",rol->pid);
  printf("rcname >%4.4s<\n",rcname);

#ifdef SSIPC
  sprintf(ssname,"%s_%s",getenv("HOST"),rcname);
  printf("Smartsockets unique name >%s<\n",ssname);
  epics_msg_sender_init(getenv("EXPID"), ssname); /* SECOND ARG MUST BE UNIQUE !!! */
#endif

  logMsg("INFO: User Download Executed\n",1,2,3,4,5,6);
}
t_uint32 PlatformInit(t_uint32 boot_indication, t_uint32 boot_status)
{	
	
	 //volatile char toto;  // for debug
	 
	char pwr_current_state;
	volatile t_Header *p_header;
	volatile t_ReqMb0 *p_ReqMB0;
	volatile t_ShVar1 *p_MB_status;
	volatile t_AckMb4 *p_ackMB4;
	volatile t_DDRInit *p_ddr_mailbox;
	volatile t_AVSData *p_AVSData;
	char     ddr_status;

  unsigned i;
	
	t_uint32 uPass = BOOT_OK;

	logMsg("\r\nMEM_INIT start...\r\n");
	
	p_header         = (t_Header*)(TCDM_BASE+0xFE8);
	p_ReqMB0         = (t_ReqMb0*)(TCDM_BASE+0xFDC);
	p_MB_status      = (t_ShVar1*)(TCDM_BASE+0xFFC);
	p_ackMB4				 = (t_AckMb4*)(TCDM_BASE+0xDF8);
    
  p_AVSData = (t_AVSData *)(TCDM_BASE + 0x2E0);  
	p_ddr_mailbox    = (t_DDRInit *)(TCDM_BASE+0x000);
	
	if ( (boot_status & PWR_MNGT_STARTED) == PWR_MNGT_STARTED)
	{
		logMsg("MEM_INIT PWR_MNGT_STARTED\r\n");

		//***********************
		// All GPIOs reset
		//***********************
		IO(0x80157208) = 0x3FFFF;

		// Clear AckMB interrupt
  	IO(0x8015748C)=0xFF;
	
 		// AB8500 update to config2 to be accessible in HWI2C
 		// => Bank 4 registers will be accessible with APE HWI2C 
 		// => Sim Control registers will be accessible with Modem I2C
		// => other registers will be accessible with APE HWI2C
  	HWI2C_Transfer_write(0x03,0x00,0x02);    // write 0x2 in @0x300 (ReguSerialCtrl1 register)		

		// Enable  body biasing (vbbn + vbbp)
	  HWI2C_Transfer_write(0x04, 0x01, 0x45);
	  	  
		// BUG VI28193
		// Set VRF1Regu[1:0] to '10'
		HWI2C_Transfer_write(0x04,0x0A,0x09);

    //************************************************************
    // Copy AVS structure in xp70 data mem and call FW AVS service
    //************************************************************
    p_AVSData->Voltage[AVS_VBB_RET     ]   = VBB_RET;
    p_AVSData->Voltage[AVS_VBB_MAX_OPP ]   = VBB_MAX_OPP;
    p_AVSData->Voltage[AVS_VBB_100_OPP ]   = VBB_100_OPP;
    p_AVSData->Voltage[AVS_VBB_50_OPP  ]   = VBB_50_OPP;
    p_AVSData->Voltage[AVS_VARM_MAX_OPP]   = (1<<7)+COMP_VARM_MAX_OPP;  //  by default allow MAX opp. This is the aim of MASK_BIT7.
    p_AVSData->Voltage[AVS_VARM_100_OPP]   = COMP_VARM_100_OPP;
    p_AVSData->Voltage[AVS_VARM_50_OPP ]   = COMP_VARM_50_OPP;
    p_AVSData->Voltage[AVS_VARM_RET    ]   = COMP_VARM_RET;
    p_AVSData->Voltage[AVS_VAPE_100_OPP]   = COMP_VAPE_100_OPP;
    p_AVSData->Voltage[AVS_VAPE_50_OPP ]   = COMP_VAPE_50_OPP;
    p_AVSData->Voltage[AVS_VMOD_100_OPP]   = COMP_VMOD_100_OPP;
    p_AVSData->Voltage[AVS_VMOD_50_OPP ]   = COMP_VMOD_50_OPP;
    p_AVSData->Voltage[AVS_VSAFE       ]   = COMP_VSAFE;	

	  // AVS service request
	 	p_header->Req.un.Mb4 = AvsH;
		// MailBox4 => 
	  
		// Send IT16 to XP70 to request AVS service
		IO(0x80157100) |= 0x10; 

		while (p_ackMB4->field.AckMb4Status != (t_AckMb4Status)Avs_Ok);
			
		logMsg("AVS_INIT OK\r\n");

		// Clear AckMB4
		p_ackMB4->field.AckMb4Status = AckMb4Init;

		
		//*********************************
		// Switch xP70 Fw in ApExecute
		//*********************************
		
		// power state transition request (header of MailBox0)
		(p_header->Req).un.Mb0 = PwrStTrH;
		(p_ReqMB0->PwrStTr).un.ApPwrStTr = ApBootToApExecute;
	  
		// Send IT (nb 10) to XP70
		IO(0x80157100) |= 0x1;

		logMsg("MEM_INIT IT sent to XP70\r\n");
		
		pwr_current_state = p_MB_status->pwr_current_state_var;
		// Check mailbox status 
		while (pwr_current_state != (t_ApPwrSt)ApExecute) 
			pwr_current_state = p_MB_status->pwr_current_state_var;
	  
	 	logMsg("MEM_INIT XP70 ApExecute\r\n");

		//*********************************
		// Fill DDR settings into XP70 data area 
		//*********************************
		
		// Copy Mask for DDR controller registers
		p_ddr_mailbox->MaskCfg0[0] = 0x6DFFFFFF; 	// no param into DENALI_CTL_25/28/31 
		p_ddr_mailbox->MaskCfg0[1] = 0x9800F1FF; 	// no param into DENALI_CTL_41/42/43/48to58 /61/62 
		p_ddr_mailbox->MaskCfg0[2] = 0xFFFFF309; 	// no param into DENALI_CTL_65/66/68to71/74/75 
		p_ddr_mailbox->MaskCfg0[3] = 0xFFFFFFFF; 
		p_ddr_mailbox->MaskCfg0[4] = 0x0001E01F; 	// no param into DENALI_CTL_133to140
	
	
		// DDR settings		
		// REG_CONFIG_0 databahn registers
		p_ddr_mailbox->Cfg0[0] = 0x00000101;  //  DENALI_CTL_0
		p_ddr_mailbox->Cfg0[1] = 0x01010100;  //  DENALI_CTL_1
		p_ddr_mailbox->Cfg0[2] = 0x00010001;  //  DENALI_CTL_2
		p_ddr_mailbox->Cfg0[3] = 0x00010100;  //  DENALI_CTL_3
		p_ddr_mailbox->Cfg0[4] = 0x01010100;  //  DENALI_CTL_4
		p_ddr_mailbox->Cfg0[5] = 0x01000100;  //  DENALI_CTL_5
		p_ddr_mailbox->Cfg0[6] = 0x00000000;  //  DENALI_CTL_6
		p_ddr_mailbox->Cfg0[7] = 0x00000001;  //  DENALI_CTL_7
		p_ddr_mailbox->Cfg0[8] = 0x00000101;  //  DENALI_CTL_8
		p_ddr_mailbox->Cfg0[9] = 0x02020303;  //  DENALI_CTL_9
		p_ddr_mailbox->Cfg0[10] = 0x03030303;  //  DENALI_CTL_10
		p_ddr_mailbox->Cfg0[11] = 0x01030303;  //  DENALI_CTL_11
		p_ddr_mailbox->Cfg0[12] = 0x00000301;  //  DENALI_CTL_12
		p_ddr_mailbox->Cfg0[13] = 0x00000000;  //  DENALI_CTL_13
		p_ddr_mailbox->Cfg0[14] = 0x00060207;  //  DENALI_CTL_14
		p_ddr_mailbox->Cfg0[15] = 0x03000000;  //  DENALI_CTL_15
		p_ddr_mailbox->Cfg0[16] = 0x04020202;  //  DENALI_CTL_16
		p_ddr_mailbox->Cfg0[17] = 0x0c000f03;  //  DENALI_CTL_17
		p_ddr_mailbox->Cfg0[18] = 0x00000f0d;  //  DENALI_CTL_18
		p_ddr_mailbox->Cfg0[19] = 0x000e0000;  //  DENALI_CTL_19
		p_ddr_mailbox->Cfg0[20] = 0x0002000a;  //  DENALI_CTL_20
		p_ddr_mailbox->Cfg0[21] = 0x00060803;  //  DENALI_CTL_21
		p_ddr_mailbox->Cfg0[22] = 0x05000909;  //  DENALI_CTL_22
		p_ddr_mailbox->Cfg0[23] = 0x32002e1a;  //  DENALI_CTL_23
		p_ddr_mailbox->Cfg0[24] = 0x23003200;  //  DENALI_CTL_24
		p_ddr_mailbox->Cfg0[25] = 0x08110000;  //  DENALI_CTL_26
		p_ddr_mailbox->Cfg0[26] = 0x00000034;  //  DENALI_CTL_27
		p_ddr_mailbox->Cfg0[27] = 0x06100610;  //  DENALI_CTL_29
		p_ddr_mailbox->Cfg0[28] = 0x06100610;  //  DENALI_CTL_30
		p_ddr_mailbox->Cfg0[29] = 0xffff0000;  //  DENALI_CTL_32
		p_ddr_mailbox->Cfg0[30] = 0xffffffff;  //  DENALI_CTL_33
		p_ddr_mailbox->Cfg0[31] = 0x0000ffff;  //  DENALI_CTL_34
		p_ddr_mailbox->Cfg0[32] = 0x00100100;  //  DENALI_CTL_35
		p_ddr_mailbox->Cfg0[33] = 0x00000000;  //  DENALI_CTL_36
		p_ddr_mailbox->Cfg0[34] = 0x00030000;  //  DENALI_CTL_37
		p_ddr_mailbox->Cfg0[35] = 0x00391b4e;  //  DENALI_CTL_38
		p_ddr_mailbox->Cfg0[36] = 0x0000003a;  //  DENALI_CTL_39
		p_ddr_mailbox->Cfg0[37] = 0x00000028;  //  DENALI_CTL_40
		p_ddr_mailbox->Cfg0[38] = 0x00000000;  //  DENALI_CTL_44
		p_ddr_mailbox->Cfg0[39] = 0x00000000;  //  DENALI_CTL_45
		p_ddr_mailbox->Cfg0[40] = 0x00000000;  //  DENALI_CTL_46
		p_ddr_mailbox->Cfg0[41] = 0x00000000;  //  DENALI_CTL_47
		p_ddr_mailbox->Cfg0[42] = 0x00000000;  //  DENALI_CTL_59
		p_ddr_mailbox->Cfg0[43] = 0x00000000;  //  DENALI_CTL_60
		p_ddr_mailbox->Cfg0[44] = 0x05000003;  //  DENALI_CTL_63
		p_ddr_mailbox->Cfg0[45] = 0x00050006;  //  DENALI_CTL_64
		p_ddr_mailbox->Cfg0[46] = 0x00000000;  //  DENALI_CTL_67
		p_ddr_mailbox->Cfg0[47] = 0x00000000;  //  DENALI_CTL_72
		p_ddr_mailbox->Cfg0[48] = 0x00007c00;  //  DENALI_CTL_73
		p_ddr_mailbox->Cfg0[49] = 0x01000100;  //  DENALI_CTL_76
		p_ddr_mailbox->Cfg0[50] = 0x01000103;  //  DENALI_CTL_77
		p_ddr_mailbox->Cfg0[51] = 0x02020200;  //  DENALI_CTL_78
		p_ddr_mailbox->Cfg0[52] = 0x02000103;  //  DENALI_CTL_79
		p_ddr_mailbox->Cfg0[53] = 0x14000100;  //  DENALI_CTL_80
		p_ddr_mailbox->Cfg0[54] = 0x0001b040;  //  DENALI_CTL_81
		p_ddr_mailbox->Cfg0[55] = 0x00900000;  //  DENALI_CTL_82
		p_ddr_mailbox->Cfg0[56] = 0x01900024;  //  DENALI_CTL_83
		p_ddr_mailbox->Cfg0[57] = 0x00000014;  //  DENALI_CTL_84
		p_ddr_mailbox->Cfg0[58] = 0x00000000;  //  DENALI_CTL_85
		p_ddr_mailbox->Cfg0[59] = 0x00000000;  //  DENALI_CTL_86
		p_ddr_mailbox->Cfg0[60] = 0x00820000;  //  DENALI_CTL_87
		p_ddr_mailbox->Cfg0[61] = 0x00040082;  //  DENALI_CTL_88
		p_ddr_mailbox->Cfg0[62] = 0x00010004;  //  DENALI_CTL_89
		p_ddr_mailbox->Cfg0[63] = 0x00000001;  //  DENALI_CTL_90
		p_ddr_mailbox->Cfg0[64] = 0x00000000;  //  DENALI_CTL_91
		p_ddr_mailbox->Cfg0[65] = 0x00013880;  //  DENALI_CTL_92
		p_ddr_mailbox->Cfg0[66] = 0x00000190;  //  DENALI_CTL_93
		p_ddr_mailbox->Cfg0[67] = 0x00000fa0;  //  DENALI_CTL_94
		p_ddr_mailbox->Cfg0[68] = 0x00010100;  //  DENALI_CTL_95
		p_ddr_mailbox->Cfg0[69] = 0x01000001;  //  DENALI_CTL_96
		p_ddr_mailbox->Cfg0[70] = 0x0a020201;  //  DENALI_CTL_97
		p_ddr_mailbox->Cfg0[71] = 0x0009090a;  //  DENALI_CTL_98
		p_ddr_mailbox->Cfg0[72] = 0x0fff0000;  //  DENALI_CTL_99
		p_ddr_mailbox->Cfg0[73] = 0x00000fff;  //  DENALI_CTL_100
		p_ddr_mailbox->Cfg0[74] = 0x03021000;  //  DENALI_CTL_101
		p_ddr_mailbox->Cfg0[75] = 0x00050604;  //  DENALI_CTL_102
		p_ddr_mailbox->Cfg0[76] = 0x06100610;  //  DENALI_CTL_103
		p_ddr_mailbox->Cfg0[77] = 0x00000610;  //  DENALI_CTL_104
		p_ddr_mailbox->Cfg0[78] = 0x00080403;  //  DENALI_CTL_105
		p_ddr_mailbox->Cfg0[79] = 0x00110905;  //  DENALI_CTL_106
		p_ddr_mailbox->Cfg0[80] = 0x39341a0d;  //  DENALI_CTL_107
		p_ddr_mailbox->Cfg0[81] = 0x0304017e;  //  DENALI_CTL_108
		p_ddr_mailbox->Cfg0[82] = 0x000f0610;  //  DENALI_CTL_109
		p_ddr_mailbox->Cfg0[83] = 0x0039001d;  //  DENALI_CTL_110
		p_ddr_mailbox->Cfg0[84] = 0x001e0010;  //  DENALI_CTL_111
		p_ddr_mailbox->Cfg0[85] = 0x0089003a;  //  DENALI_CTL_112
		p_ddr_mailbox->Cfg0[86] = 0x0030c6c9;  //  DENALI_CTL_113
		p_ddr_mailbox->Cfg0[87] = 0x03494288;  //  DENALI_CTL_114
		p_ddr_mailbox->Cfg0[88] = 0x00012009;  //  DENALI_CTL_115
		p_ddr_mailbox->Cfg0[89] = 0x00048024;  //  DENALI_CTL_116
		p_ddr_mailbox->Cfg0[90] = 0x00090024;  //  DENALI_CTL_117
		p_ddr_mailbox->Cfg0[91] = 0x125224a4;  //  DENALI_CTL_118
		p_ddr_mailbox->Cfg0[92] = 0x00110022;  //  DENALI_CTL_119
		p_ddr_mailbox->Cfg0[93] = 0x00410082;  //  DENALI_CTL_120
		p_ddr_mailbox->Cfg0[94] = 0x00110022;  //  DENALI_CTL_121
		p_ddr_mailbox->Cfg0[95] = 0x00008001;  //  DENALI_CTL_122
		p_ddr_mailbox->Cfg0[96] = 0x00020004;  //  DENALI_CTL_123
		p_ddr_mailbox->Cfg0[97] = 0x00008001;  //  DENALI_CTL_124
		p_ddr_mailbox->Cfg0[98] = 0x02491001;  //  DENALI_CTL_125
		p_ddr_mailbox->Cfg0[99] = 0x02ca1001;  //  DENALI_CTL_126
		p_ddr_mailbox->Cfg0[100] = 0x044b36c9;  //  DENALI_CTL_127
		p_ddr_mailbox->Cfg0[101] = 0x019130c6;  //  DENALI_CTL_128
		p_ddr_mailbox->Cfg0[102] = 0x1c7334c6;  //  DENALI_CTL_129
		p_ddr_mailbox->Cfg0[103] = 0x0c31a906;  //  DENALI_CTL_130
		p_ddr_mailbox->Cfg0[104] = 0x0c31a083;  //  DENALI_CTL_131
		p_ddr_mailbox->Cfg0[105] = 0x0201a347;  //  DENALI_CTL_132
		p_ddr_mailbox->Cfg0[106] = 0x03cb1001;  //  DENALI_CTL_141
		p_ddr_mailbox->Cfg0[107] = 0x00010003;  //  DENALI_CTL_142
		p_ddr_mailbox->Cfg0[108] = 0x00008001;  //  DENALI_CTL_143
		p_ddr_mailbox->Cfg0[109] = 0x00010003;  //  DENALI_CTL_144
                          
	  //Lpddr2 phy
		p_ddr_mailbox->Cfg0[110] = 0x03cb1001;  // DENALI_CTL_72


		IO(0x80157438) = 0x00000000;		         // LpDDR2 start at 400Mhz

		logMsg("MEM_INIT LpDDR2 at 400Mhz settings filled\r\n");
				 
		// DDR init request (header of MailBox4)
		p_header->Req.un.Mb4 = ddrInitH;
		// MailBox4 => no need to fill MB4 structure
	  
		// Send IT16 to XP70 to init DDR 
		IO(0x80157100) |= 0x10;

		logMsg("MEM_INIT IT16 to XP70 to init DDR\r\n");
		
		ddr_status = p_ackMB4->field.AckMb4Status;
		while (ddr_status != (t_AckMb4Status)DDROn_Ok)
			ddr_status = p_ackMB4->field.AckMb4Status;
			
		logMsg("MEM_INIT DDR_ON OK\r\n");

		// Clear AckMB4
		p_ackMB4->field.AckMb4Status = AckMb4Init;
		
		// Clear PRCM_ARM_IT1 IT for ackmb4
 	  while((IO(0x80157494) & 0x10) != 0x10);
 	  // Clear PRCM_ARM_IT1 ackmb4
 	  IO(0x8015748C)=0x10;
  
	}		



	//#######################################
  //#         Modem start-up
  //#######################################
  
  // Needed to send SYSCLK_OK to modem, but should be corrected in fw xP70
  IO(0x80157318) = 0x0;      //PRCM_SYSCLKOK_DELAY (val * 32K) 0 no delay

  IO(0x801571FC) = 0x3;      // Release Modem PURX and SWReset
  IO(0x801574A4) = 0x1;      // Ack SWReset from Modem in case of reboot due to this reason
  IO(0x801574A4) = 0x0;
  
  i = 0;
  while( ((IO(0x801574A0) & 0x1) != 0x1) && (i<10000)) {
  	i++;
  }

  // Request Modem HOST_PORT interface
  IO(0x80157334) = 0x00007;   // PRCM_HOSTACCESS_REQ
                                  // [16] Wake_req = 0
                                  // [2:1] HOSTACCESS_ID = 11 (A9ss)
                                  // [0] mod_host_port_req = 1

  // Waiting for modem HOST_PORT available (other signal name HOST_PORT_OK)
  i = 0;
  while( ((IO(0x80157170) & 0x800) != 0x800) && (i<10000)) {
   	i++;
  } 	


	//####################################################################################
	//####################################################################################
	// Now, MSS is powered, and ready to execute SW.
	// the HOST PORT interface is enabled, so A9SS can access to the MSS mapping
	//####################################################################################
	//####################################################################################


	//#####
	//Configure Modem STM trace
	//#####
	Modem_STM_config();
	logMsg("MEM_INIT Modem_STM_config\r\n");
	
	//#####
	//Configure PRCMU STM trace
	//#####
	//PRCMU_STM_config();
	
	//DDR test
	if (boot_indication == SECOND_BOOT_INDICATION)
	{
	    uPass = Test_Write_Read_DDR();
	}
	logMsg("MEM_INIT end\r\n");
	
	
	return uPass;
}
Esempio n. 4
0
/**finer logs the message at FINER level.
 * The message is appended to the log file if the current level is in the range SEVERE to FINER
 *
 *@param toLog the message text to log
 */
void Logger::finer(string toLog) {
	if (levelSet < FINER) return;
	logMsg(FINER, toLog);
}
Esempio n. 5
0
/**Destructs the Logger object after closing its log file. 
 */
Logger::~Logger(void) {
	logMsg (SEVERE, "logging END");
	if (fileLog != stderr) fclose(fileLog);
}
Esempio n. 6
0
/**severe logs a message at SEVERE level.
 * All SEVERE messages are appended to the log file.
 *
 *@param toLog the message text to log
 */
void Logger::severe(string toLog) {
	logMsg(SEVERE, toLog);
}
Esempio n. 7
0
/** info logs message at INFO level.
 * The message is appended to the log file if the current level is in the range SEVERE to INFO
 *
 *@param toLog the message text to log
 */
void Logger::info (string toLog) {
	if (levelSet < INFO) return;
	logMsg(INFO, toLog);
}
Esempio n. 8
0
void offenseState::executeOffense() // executes box offense
{
	gameState *gameS = gameState::Instance();
    std::vector<teamState> teamInstance = gameS->getTeamInstance();
    std::vector<playerState> playerInstance = teamInstance[gameS->getTeamWithBall()].getPlayerInstance();

	int teamNumber = gameS->getTeamWithBall();
	int playerWithBall = teamInstance[teamNumber].getPlayerWithBall();
	playerSteer *pSteer;

    if (!allStartPositionsReached)	// checks if all players have reached their start positions for the offense being run
	{
    	for (int x=0;x<5;++x)
		{
			if ( x != playerWithBall)
			{
    		    pSteer = playerInstance[x].getSteer();
			    std::vector<bool> positionReached = pSteer->getPositionReached();
			    if (positionReached.size() != 1)
			    {
				    positionReached.push_back(false);
				    pSteer->setPositionReached(positionReached);
			    }

		        if (!startPositionReached[x])  // checks if each player has reached the start position
		        {
				    std::vector<Ogre::Vector3> steerCoords = plays[0].getStartPositions();
				    OpenSteer::Vec3 coords = pSteer->convertToOpenSteerVec3(startPositions[x]);
				    pSteer->setSteerCoords(coords);
					pSteer->setExecute(true);
		        }
		        else	// increments the counter
		        {
//				numStartPositionsReached += 1;
                    pSteer->setExecute(false);
			    }

			    if (numStartPositionsReached == 4)	// FIXME: hard coded for a human player
			    {
//				exit(0);
				    allStartPositionsReached = true;
			    }
		        if (!startPositionReached[x] && pSteer->getDistToPosition() < 3 && pSteer->getDistToPosition() != -1.0f)
			    {

		    	    startPositionReached[x] = true;
				    numStartPositionsReached += 1;
					pSteer->setExecute(false);
			    }
			    logMsg("startPositionsReached = " +Ogre::StringConverter::toString(startPositionReached[x]));
			}
	    }
	}
	else
	{
//		exit(0);
		if (!allExecutePositionsReached)
		{
//			exit(0);
			int allExecutionsReached = 0;
		    for (int ID=0;ID<5;++ID)
		    {
				if (allExecutionsReached < 4)
				{

			        if (ID != playerWithBall)
			        {
						pSteer = playerInstance[ID].getSteer();
                        bool directiveComplete = checkForDirective(pSteer->getDesignation());  // checks if player must follow directive before executing
						if (directiveComplete)
						{	
			                
				            logMsg("Player " +Ogre::StringConverter::toString(ID) +" executePositionReached size = " +Ogre::StringConverter::toString(executePositionReached[ID].size()));
			                for (int x=0;x<executePositionReached[ID].size();++x)
			                {
				                if (executePositionReached[ID][x] == true)
				                {
				    	            logMsg("Player " +Ogre::StringConverter::toString(ID));
//	    		                    exit(0);
				                }
				                else
				                {   
								    int lastPos = executePositionReached[ID].size() - 1;
				                    if (executePositionReached[ID][lastPos])
				    		        {
									    allExecutionsReached += 1;
							        }
					                // checks if previous position was reached
					                else if ( x > 0 && !executePositionReached[ID][x - 1])
					                {
//					    	            exit(0);
//						            break;
					                }
					                else //if (!executePositionReached[ID][x])
					                {
						                logMsg("Team " +Ogre::StringConverter::toString(teamNumber) +" Player " +Ogre::StringConverter::toString(ID) +" Seeking Offense Execute Position!");
					  	                OpenSteer::Vec3 executePosition = pSteer->convertToOpenSteerVec3(executePositions[ID][x]);
						               pSteer->setSteerCoords(executePosition);
						                float distToPosition = OpenSteer::Vec3::distance (pSteer->getSteerCoords(), pSteer->position());
						                pSteer->setDistToPosition(distToPosition);
							            if (pSteer->getDistToPosition() < 3 && pSteer->getDistToPosition() != -1.0f)
							            {
								        //    exit(0);
								            executePositionReached[ID][x] = true;
										    pSteer->setExecute(false);
							            }
									    else
									    {
//										    exit(0);
										    pSteer->setExecute(true);
									    }
					                }
					            }
                            }
				        }
			        }
			    }
				else
				{
					allExecutePositionsReached = true;
				}
		    }
		}
		else
		{
			for (int x=0;x<5;++x)
			{
				pSteer = playerInstance[x].getSteer();
				pSteer->setExecute(false);
				playerInstance[x].setSteer(pSteer);

			}
		}
//			exit(0);
	}

}
/*!
 * Writes an logfile message from type INFO
 */
void TTMessageLogger::infoMsg(QString caller, QString msgString)
{
  logMsg(INFO, caller, msgString);
}
Esempio n. 10
0
// updates the game state
bool gameState::updateState()
{
//    logMsg("Updating gameState Logic");

    boost::shared_ptr<AISystem> ai = AISystem::Instance();
    boost::shared_ptr<conversion> convert = conversion::Instance();
    boost::shared_ptr<gameEngine> gameE = gameEngine::Instance();
    boost::shared_ptr<networkEngine> network = networkEngine::Instance();
    boost::shared_ptr<physicsEngine> physEngine = physicsEngine::Instance();
    timing timer = gameE->getTimer();
    Ogre::Vector3 playerPos;

    basketballInstance[activeBBallInstance].updateState();

    basketballInstance[activeBBallInstance].setPlayer(5);

    if (gameSetupComplete)
    {
    if (network->getPacketReceived())	// checks if a packet was received by network engine
    {
    	processNetworkEvents();	// processes data received from the network
    }
    logMsg("network events processed");

    if (!tipOffComplete)  // calls tip off execution
    {
        if (executeTipOff())
        {
            tipOffComplete = true;
//            exit(0);
        }
    }

	if (teamWithBall != NOTEAM)
	{
//		logMsg("teamWithBall is " +convert->toString(teamWithBall));
//        logMsg("playetWithBall is " +convert->toString(teamInstance[teamWithBall].getPlayerWithBall()));
//		float currentTime = static_cast<float>(gameE->getLoopTime().getMilliseconds()/100);
        long currentTime = timer.getLoopTimeMill().count();
        float oldTime = ai->getOldTime();
        float changeInTime = currentTime - oldTime;
   //     ai->update(currentTime, changeInTime);
        logMsg("CHANGE == " +convert->toString(changeInTime));

        if (changeInTime >= .5f)
		{
            logMsg("ELAPSED == " +convert->toString(changeInTime));
//			exit(0);
//			ai->update(aiTimer.getTotalSimulationTime (), aiTimer.getElapsedSimulationTime ());
			ai->update(currentTime, changeInTime);
			ai->setOldTime(currentTime);
		}

    }

    logMsg("Physics");
    physEngine->updateState();	// updates the state of the physics simulation
    logMsg("stepWorld");
    //    exit(0);
	physEngine->stepWorld();	// steps the physics simulation
/*    logMsg("DirectionsAndMovement");
    updateDirectionsAndMovements();
*/
//	exit(0);

    // updates the basketball(s) state
    logMsg("Updated basketball state!");
//    exit(0);
//    renderBall();
//    SceneNode *bball = basketballInstance[activeBBallInstance].getNode();
//    bball->setPosition(basketballInstance[activeBBallInstance].calculatePositionChange());
//    basketballInstance[activeBBallInstance].setNode(bball);

//    Ogre::Vector3 change = basketballInstance[activeBBallInstance].calculatePositionChange();
//    cout << "Calced Pos change = " << basketballInstance[activeBBallInstance].calculatePositionChange() << endl;
//    basketballInstance[activeBBallInstance].nodeChangePosition(basketballInstance[activeBBallInstance].calculatePositionChange());

//    std::vector<size_t> playerDirection = player->getPlayerDirection(); // stores contents of playerDirectdion from players class in local variable
//    std::vector<size_t> oldPlayerDirection = player->getOldPlayerDirection();   // stores contents of oldPlayerDirection form players in local variable

    // Initiates offense or defense for a team depending on value of teamWithBall
    if (teamWithBall == 0)	// if 0 puts team 0 on offense and team 1 on defense
    {
    	teamInstance[0].setOffense(true);
    	teamInstance[0].setDefense(false);

    	teamInstance[1].setOffense(false);
    	teamInstance[1].setDefense(true);
    }
    else if (teamWithBall == 1)  // if 1 puts team 1 on offense and team 0 on defense
    {
    	teamInstance[0].setOffense(false);
    	teamInstance[0].setDefense(true);

    	teamInstance[1].setOffense(true);
    	teamInstance[1].setDefense(false);
    }
    else
    {
    }

    // updates the state of each team
    if (teamInstancesCreated)
    {
        //FIXME crash in updateState code
    	teamInstance[0].updateState();
    	teamInstance[1].updateState();
//    	exit(0);
    }
    else
    {
    }
    }
//	logMsg("gameState logic updated");
//    exit(0);
    return true;
}
Esempio n. 11
0
void gameState::processNetworkPlayerEvents()  // processes player events from network code
{
    //conversion *convert = conversion::Instance();
    boost::shared_ptr<conversion> convert = conversion::Instance();
    //networkEngine *network = networkEngine::Instance();
	boost::shared_ptr<networkEngine> network = networkEngine::Instance();

    networkPlayerStateObject netPStateObj;
	std::stringstream strStream;
    std::vector<playerState> activePlayerInstance;
	std::string receivedData = network->getReceivedData();	// stores receivedData value
	size_t playerNumber = -1; // stores which player the data is for
	size_t iterator;	// iterator for match loop

	logMsg("received Data === " +receivedData);
	strStream << receivedData;
	strStream >> netPStateObj;
    logMsg("received teamID = " +convert->toString(netPStateObj.getTeamID()));
    logMsg("received playerID = " +convert->toString(netPStateObj.getPlayerID()));

    // sets which team's activePlayerInstance to use
	if (network->getIsClient())
	{
	    logMsg("is client");
        activePlayerInstance = teamInstance[1].getActivePlayerInstance();
	}
	else if (network->getIsServer())
	{
	    logMsg("is server");
        activePlayerInstance = teamInstance[0].getActivePlayerInstance();
	}
	else
	{
	}
    logMsg("activePlayerInstance size == " +convert->toString(activePlayerInstance.size()));
/*	for (iterator = 0; iterator < 5; ++iterator)
	{
		std::string searchString;	// stores search String
        std::string searchIterator = convert->toString(iterator); // converts iterator to a string
		searchString = "*" +searchIterator + "*";	// creates search string
		if (Ogre::StringUtil::match(receivedData,searchString))	// checks for a match
		{
			playerNumber = iterator;	// sets playerNumber to value of iterator
		}
	}
    logMsg("alive????");
*/
    playerNumber = netPStateObj.getPlayerID();
    if (activePlayerInstance.size() > 0)
    {
        if (netPStateObj.getMovement())
        {
            switch (netPStateObj.getDirection())
            {
                case 0: // move player up
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(UP);

                    break;
                case 1: // move player down
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(DOWN);
                    break;
                case 2: // move player left
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(LEFT);
                    break;
                case 3: // move player right
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(RIGHT);
                    break;
                case 4: // move player up and left
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(UPLEFT);
                    break;
                case 5: // move player up aned right
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(UPRIGHT);
                    break;
                case 6: // move player down and left
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(DOWNLEFT);
                    break;
                case 7: // move player down and right
                    activePlayerInstance[playerNumber].setMovement(true);
                    activePlayerInstance[playerNumber].setDirection(DOWNRIGHT);
                    break;
                default:
                    activePlayerInstance[playerNumber].setMovement(false);
                    break;
            }
            if (network->getIsClient())
            {
                teamInstance[1].setActivePlayerInstance(activePlayerInstance);
            }
            else if (network->getIsServer())
            {
                teamInstance[0].setActivePlayerInstance(activePlayerInstance);
            }
        }
        else if (netPStateObj.getShootBlock())
        {

        }
        else if (netPStateObj.getPassSteal())
        {

        }
        else
        {
        }
    }

	logMsg("Survived!");
	network->setReceivedData("");
}
Esempio n. 12
0
// sets up the game condition
bool gameState::setupState()
{
	//AISystem *ai = AISystem::Instance();
    boost::shared_ptr<AISystem> ai = AISystem::Instance();
    boost::shared_ptr<renderEngine> render = renderEngine::Instance();
    boost::shared_ptr<loader> load = loader::Instance();
    boost::shared_ptr<physicsEngine> physEngine = physicsEngine::Instance();
    boost::shared_ptr<conversion> convert = conversion::Instance();

    logMsg("Setting up state!");

    if (!courtModelLoaded)
    {
        logMsg("creating court instances!");
        if (createCourtInstances())  // creates the court instances
        {
            courtModelLoaded = true;
            courtInstanceCreated = true;
        }
    }

    if (!basketballInstancesCreated)	// checks if court model has been loaded
    {
        logMsg("creating basketball instances!");
    	if (createBasketballInstances()) // creates the basketball instances
    	{
    		basketballInstancesCreated = true;
    	}

        // FIXEME! this should not be hard coded
        activeBBallInstance = 0;  // sets the active basketball instance
    }

    if (!hoopModelLoaded)
    {
        logMsg("creating hoop instances!");
        if (createHoopInstances())  // creates the hoop instances
        {
        	hoopModelLoaded = true;
        }
    }

    setBasketballStartPositions();	// sets starting positions for all basketballs that are instantiated
    setCourtStartPositions();	// sets starting positions for all courts that are instantiated
    setHoopStartPositions();	// sets starting positions for all hoops that are instantiated

    logMsg("court y == " +convert->toString(courtInstance[0].getNode()->getPosition().y));
//    exit(0);
    if (!teamInstancesCreated)  // checks if teamInstances have been created
    {
        if(createTeamInstances())   // creates the team instances
        {
            logMsg("TIC!");
            teamInstancesCreated = true;
            assignHoopToTeams();  // assigns proper hoop to the teams that were created.
        }
    }

    // sets the quarter being played to the first one.
    quarter = FIRST;
//    basketballInstance[activeBBallInstance].getNode()->setPosition(1.4f,5.0f,366.0f);


    physEngine->setupState();  // sets up the Physics Engine state
//    exit(0);
	ai->setup();

//        Ogre::Entity *ent;
//        ent = player->getModel(0);
//        player->mAnimationState2 = ent->getAnimationState("Walk");
//        std::vector<Ogre::Entity*> playerModels = player->getModel();
//        std::vector<Ogre::SceneNode*> playerNodes = player->getNode();
//    std::vector<playerState> pInstance = getPlayerInstance();
//        player->setModel(playerModels);
//    Ogre::Vector3 playerPos = playerNodes.at(0)->getPosition();
//    Ogre::Vector3 offset;
//    offset[0] = 2.0f;
//    offset[1] = 2.0f;
//    offset[2] = 2.0f;
//	bball->setAutoTracking(true,playerNode[0],playerNode[0]->getPosition(),offset);
//	bball->setPosition(playerPos[0] +2.0f, playerPos[1] + 4.0f, playerPos[2] - 1.0f);
//    exit(0);

    if (!setupEnvironmentCompleted)	// checks if environment has been setup
    {
    	if(setupEnvironment())	// sets up environment
    	{
    		setupEnvironmentCompleted = true;
    	}
    }
//	loads("../../data/players/players.xml");

    if (!tipOffSetupComplete)
    {
        tipOffSetupComplete = setupTipOff();	// sets up tip off conditions
    }

    return true;

//#endif
}
Esempio n. 13
0
//------------------------------------------------------------------------------
// Main entry point to this program
//------------------------------------------------------------------------------
int main(int argc, char** argv)
{
	int c;
	bool clearLockOnly = false;
	bool rollbackOnly  = false;
	uint32_t tableOID  = 0;

	while ((c = getopt(argc, argv, "hlr:")) != EOF)
	{
		switch (c)
		{
			case 'l':
				clearLockOnly = true;
				break;
//Only allow '-r' option for development/debugging
#if 1
			case 'r': // hidden option to rollback specified table w/o a lock
				rollbackOnly  = true;
				tableOID      = ::strtoull(optarg, 0, 10);
				break;
#endif
			case 'h':
			case '?':
			default:
				usage();
				return (c == 'h' ? 0 : 1);
				break;
		}
	}

	if ((argc - optind) != 1 )
	{
		usage();
		return 1;
	}

	// Get the table lock ID specified by the user
	uint64_t lockID = ::strtoull(argv[optind], 0, 10);

	// If user specified both clearlock and rollback then we need to do both
	if (clearLockOnly && rollbackOnly)
	{
		clearLockOnly = false;
		rollbackOnly  = false;
	}

	//--------------------------------------------------------------------------
	// Verify that BRM is up and in a read/write state
	//--------------------------------------------------------------------------
	BRM::DBRM brm;
	int brmRc = brm.isReadWrite();
	if (brmRc != BRM::ERR_OK)
	{
		std::string brmErrMsg;
		BRM::errString(brmRc, brmErrMsg);
		std::cout << "BRM error: " << brmErrMsg << std::endl;
		std::cout << "Table lock " << lockID << " is not cleared." << std::endl;
		return 1;
	}

	if (brm.getSystemReady() < 1)
	{
		std::cout << "System is not ready.  Verify that EryDB "
			"is up and ready before running this program" << std::endl;
		return 1;
	}

	//--------------------------------------------------------------------------
	//@Bug 3711 Check whether the table is locked; does the table lock exist.
	//--------------------------------------------------------------------------
	execplan::erydbSystemCatalog::TableName tblName;
	BRM::TableLockInfo tInfo;
	std::string task;
	std::vector<uint32_t> pmList;
	int rc;
	const std::string taskSysCat("getting system catalog information");
	try {
		if (rollbackOnly)
		{
			tInfo.id             = lockID;
			tInfo.tableOID       = tableOID;
			tInfo.ownerPID       = 0;
			tInfo.ownerSessionID = 1;
			tInfo.state          = BRM::LOADING;

			// Construct PM list using all PMs, since we don't have a table
			// lock with the list of applicable DBRoots.
			task = "constructing total PM list";
			rc = constructPMList( pmList );
			if (rc != 0)
			{
				return 1;
			}
		}
		else
		{
			task = "getting table lock";
   			bool lockExists = brm.getTableLockInfo( lockID, &tInfo );
   			if (!lockExists)
			{
				std::cout << "Table lock " << lockID << " does not exist." <<
					std::endl;
				return 1;
			}

			// Construct PM list based on list of affected DBRoots
			task = "mapping DBRoots to PMs";
			rc = constructPMList( tInfo.dbrootList, pmList );
			if (rc != 0)
			{
				return 1;
			}
		}

		uint32_t sessionID = 1;
		task = taskSysCat;
		boost::shared_ptr<execplan::erydbSystemCatalog> systemCatalogPtr =
			execplan::erydbSystemCatalog::makeerydbSystemCatalog(
				sessionID );
		systemCatalogPtr->identity(execplan::erydbSystemCatalog::EC);
		tblName = systemCatalogPtr->tableName( tInfo.tableOID );
	}
	catch (std::exception& ex)
	{
		std::cout << "Error " << task << ".  " << ex.what() << std::endl;
		if (clearLockOnly && (task == taskSysCat))
		{
			tblName.schema= "[unknown name]";
			tblName.table.clear();
			std::cout << "Will still try to clear table lock." << std::endl;
		}
		else
		{
			std::cout << "Table lock " << lockID << " is not cleared." <<
				std::endl;
			return 1;
		}
	}
	catch (...)
	{
		std::cout << "Error " << task << ".  " << std::endl;
		if (clearLockOnly && (task == taskSysCat))
		{
			tblName.schema= "[unknown name]";
			tblName.table.clear();
			std::cout << "Will still try to clear table lock." << std::endl;
		}
		else
		{
			std::cout << "Table lock " << lockID << " is not cleared." <<
				std::endl;
			return 1;
		}
	}

	logInitStatus( tblName.toString(), lockID );
	if (rollbackOnly)
	{
		std::cout << "Rolling back table " << tblName.toString() <<
			std::endl << std::endl;
	}
	else if (clearLockOnly)
	{
		std::cout << "Clearing table lock " << lockID <<
			" for table " << tblName.toString() << std::endl << std::endl;
	}
	else
	{
		std::cout << "Rolling back and clearing table lock for table " <<
			tblName.toString() << "; table lock " << lockID <<
			std::endl << std::endl;
	}

	//--------------------------------------------------------------------------
	// Perform bulk rollback
	//--------------------------------------------------------------------------
	std::string errMsg;
	if (!clearLockOnly)
	{
		std::vector<boost::shared_ptr<messageqcpp::MessageQueueClient> >
			msgQueClts;
		rc = createMsgQueClts(pmList, msgQueClts, errMsg);
		if (rc != 0)
		{
			logFinalStatus( tblName.toString(), lockID, errMsg );
			std::cout << errMsg << std::endl;
			std::cout << "Table lock " << lockID << " for table " <<
				tblName.toString() << " is not cleared." << std::endl;
			return rc;
		}

		rc = execBulkRollbackReq( msgQueClts, pmList,
			&brm, tInfo, tblName.toString(), rollbackOnly, errMsg );
		if (rc != 0)
		{
			logFinalStatus( tblName.toString(), lockID, errMsg );
			std::cout << "Rollback error: " << errMsg << std::endl;
			std::cout << "Table lock " << lockID << " for table " <<
				tblName.toString() << " is not cleared." << std::endl;
			return rc;
		}

		//----------------------------------------------------------------------
		// Change the state of the table lock to cleanup state.
		// We ignore the return stateChange flag.
		//----------------------------------------------------------------------
		if (!rollbackOnly)
		{
			try {
				brm.changeState( tInfo.id, BRM::CLEANUP );
			}
			catch (std::exception& ex)
			{
				std::ostringstream oss;
				oss << "Error changing state.  " << ex.what();
				logFinalStatus( tblName.toString(), lockID, oss.str() );
				std::cout << oss.str() << std::endl;
				std::cout << "Table lock " << lockID << " is not cleared." <<
					std::endl;
				return 1;
			}
			catch (...)
			{
				std::ostringstream oss;
				oss << "Error changing state.  " << std::endl;
				logFinalStatus( tblName.toString(), lockID, oss.str() );
				std::cout << oss.str() << std::endl;
				std::cout << "Table lock " << lockID << " is not cleared." <<
					std::endl;
				return 1;
			}
		}

		//----------------------------------------------------------------------
		// Delete the meta data files
		//----------------------------------------------------------------------
		rc = execFileCleanupReq( msgQueClts, pmList,
			&brm, tInfo, tblName.toString(), errMsg );
		if (rc != 0)
		{
			//@Bug 4517. Release tablelock if remove meta files failed
			const std::string APPLNAME("cleartablelock command");
			const int SUBSYSTEM_ID = 19; // writeengine?
			const int COMP_MSG_NUM = logging::M0089;
			logging::Message::Args msgArgs;
			logging::Message logMsg( COMP_MSG_NUM );
			msgArgs.add( APPLNAME );
			msgArgs.add( tblName.toString() );
			msgArgs.add( lockID );
			msgArgs.add( errMsg );
			logMsg.format( msgArgs );
			logging::LoggingID  lid( SUBSYSTEM_ID );
			logging::MessageLog ml( lid );
			ml.logWarningMessage( logMsg );
			
			std::cout << "File cleanup error: " << errMsg << std::endl;
		}
	} // end of: if (!clearLockOnly)

	//--------------------------------------------------------------------------
	// Finally, release the actual table lock
	//--------------------------------------------------------------------------
	std::cout << std::endl;
	if (rollbackOnly)
	{
		logFinalStatus( tblName.toString(), lockID, std::string() );
		std::cout << "Bulk Rollback Only for table " << tblName.toString() <<
			" completed successfully." << std::endl;
	}
	else
	{
		try {
			brm.releaseTableLock( lockID ); // ignore boolean return value
		}
		catch (std::exception& ex)
		{
			logFinalStatus( tblName.toString(), lockID, ex.what() );
			std::cout << "Error releasing table lock " << lockID <<
				" for table " << tblName.toString() << std::endl;
			std::cout << ex.what() << std::endl;
			return 1;
		}
		catch (...)
		{
			std::string unknownErr("Unknown exception");
			logFinalStatus( tblName.toString(), lockID, unknownErr );
			std::cout << "Error releasing table lock " << lockID <<
				" for table " << tblName.toString() << std::endl;
			std::cout << unknownErr << std::endl;
			return 1;
		}

		logFinalStatus( tblName.toString(), lockID, std::string() );
		std::cout << "Table lock " << lockID << " for table " <<
			tblName.toString() << " is cleared." << std::endl;
	}
	
	return 0;
}
Esempio n. 14
0
void EventLogControl::logAction(const wxString& action)
{
    wxString now(wxDateTime::Now().Format("%H:%M:%S  "));
    addStyledText(now, logStyleImportant);
    logMsg(action + "\n");
}
Esempio n. 15
0
ROUTE_ENTRY * routeLookup
    (
    struct sockaddr * pDest, 	/* IP address reachable with matching route */
    ULONG * pMask, 		/* netmask value, in network byte order */
    int	protoId 		/* route source from m2Lib.h, or 0 for any. */
    )
    {
    struct radix_node_head * pHead = rt_tables[pDest->sa_family];

    struct radix_node * pNode;        /* radix tree entry for route */
    struct rtentry * pRoute = NULL;   /* candidate for matching route */
    ROUTE_ENTRY * pMatch = NULL;      /* matching route entry */

    struct sockaddr_in netmask;       /* netmask value, internal format */
    char * pNetmask = NULL;           /* target netmask value from tree */

    struct rtentry * pNextRoute;

    STATUS result = ERROR;            /* OK indicates a successful search */
    int  s;

    if (pHead == NULL)
        {
        /* No route table exists for the given address family. */

        return (NULL);
        }

    bzero ( (char *)&netmask, sizeof (struct sockaddr_in));

    s = splnet ();

    /*
     * If a specific netmask match is required, find the target value
     * (a pointer to the stored netmask entry) which will determine
     * whether the match exists. A mask value of zero indicates a
     * host-specific route, which does not contain a netmask entry.
     */

    if (pMask && *pMask)
        {
        /* Setup data structure to search mask's tree for given value. */

        netmask.sin_family = AF_INET;
        netmask.sin_len = sizeof (struct sockaddr_in);
        netmask.sin_addr.s_addr = *pMask;

        TOS_SET (&netmask, 0x1f);

        in_socktrim (&netmask);    /* Adjust length field for tree search. */

        /* Search for netmask from corresponding tree. */

        pNode = rn_addmask (&netmask, 1, pHead->rnh_treetop->rn_off);
        if (pNode == 0)
            {
            /* No route currently uses the specified netmask. */

#ifdef DEBUG
            logMsg ("routeLookup: requested mask does not exist.\n",
                    0, 0, 0, 0, 0, 0);
#endif
            splx(s);
            return (NULL);
            }

        pNetmask = pNode->rn_key;
        }

    pNode = pHead->rnh_matchaddr ((caddr_t)pDest, pHead);
    if (pNode && ((pNode->rn_flags & RNF_ROOT) == 0))
        {
        /* Possible match found. Save for later use. */

        pRoute = (struct rtentry *)pNode;
        }
    else
        {
        /* No route matches the given key. */

        splx (s);
        return (NULL);
        }

#ifdef DEBUG
    logMsg ("routeLookup: candidate for match at %p.\n", pNode,
            0, 0, 0, 0, 0);
#endif

    /*
     * Compare the set of routes available with the initial key
     * against the desired values. Each entry in the chain of
     * routes with duplicate keys uses a different netmask value.
     *
     * NOTE: The pNode value is not necessarily the start of the
     * chain. It is the first entry in the chain with a short
     * enough netmask to produce a match against the destination.
     */

    for ( ; pRoute != NULL; pRoute = pNextRoute)
        {
        /* Select the next route candidate in case a test fails. */

        pNextRoute = (struct rtentry *)
                           ((struct radix_node *)pRoute)->rn_dupedkey;

        if (pMask)
            {
            /*
             * Check mask of route against corresponding entry from
             * the stored netmasks (derived from the given value).
             */

#ifdef DEBUG
            logMsg ("routeLookup: checking against specific mask.\n",
                    0, 0, 0, 0, 0, 0);
#endif

            if (*pMask)
                {
                if ( ((struct radix_node *)pRoute)->rn_mask != pNetmask)
                    continue;   /* Mask values do not match. */
                }
            else if ( ( (struct sockaddr_in *)pDest)->sin_addr.s_addr)
                {
                /* Searching for a host-specific route (no netmask entry). */

                if ( ((struct radix_node *)pRoute)->rn_mask != 0)
                    continue;   /* Entry is not a host route. */
                }
            }

        /*
         * Candidate passed any mask requirements. Search for entries
         * which match the specified route source.
         */

#ifdef DEBUG
        logMsg ("routeLookup: Current mask is OK.\n", 0, 0, 0, 0, 0, 0);
#endif

        if (protoId)
            {
            /* Check source of route against specified value. */

#ifdef DEBUG
            logMsg ("routeLookup: testing protocol ID.\n",
                    0, 0, 0, 0, 0, 0);
#endif

            for (pMatch = (ROUTE_ENTRY *)pRoute; pMatch != NULL;
                   pMatch = pMatch->diffNode.pFrwd)
                {
                if (RT_PROTO_GET(ROUTE_ENTRY_KEY(pMatch)) == protoId)
                    break;
                }

            if (pMatch == NULL)   /* Route protocol values do not match. */
                continue;

#ifdef DEBUG
            logMsg ("routeLookup: Current protocol ID is OK.\n",
                    0, 0, 0, 0, 0, 0);
#endif
            }
        else
            {
            /*
             * No route source is specified. Accept the entry
             * which met any mask criteria.
             */

            pMatch = (ROUTE_ENTRY *)pRoute;
            }
 
        /* The candidate route entry met all criteria. Stop the search. */

        result = OK;
        break;
        }

    if (result == OK)
        {
        /* Increase the reference count before returning the matching entry. */

        pMatch->rtEntry.rt_refcnt++;
        }
    else
        pMatch = NULL;

    splx (s);

    return (pMatch);
    }
/*!
 * Writes an logfile message from type WARNING
 */
void TTMessageLogger::warningMsg(QString caller, QString msgString)
{
logMsg(WARNING, caller, msgString);
}
Esempio n. 17
0
bool StyleContext::parseStyleResult(StyleParamKey _key, StyleParam::Value& _val) const {
    _val = none_type{};

    if (duk_is_string(m_ctx, -1)) {
        std::string value(duk_get_string(m_ctx, -1));
        _val = StyleParam::parseString(_key, value);

    } else if (duk_is_boolean(m_ctx, -1)) {
        bool value = duk_get_boolean(m_ctx, -1);

        switch (_key) {
        case StyleParamKey::visible:
            _val = value;
            break;
        case StyleParamKey::extrude:
            _val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f);
            break;
        default:
            break;
        }

    } else if (duk_is_array(m_ctx, -1)) {
        duk_get_prop_string(m_ctx, -1, "length");
        int len = duk_get_int(m_ctx, -1);
        duk_pop(m_ctx);

        switch (_key) {
        case StyleParamKey::extrude: {
            if (len != 2) {
                logMsg("Warning: Wrong array size for extrusion: '%d'.\n", len);
                break;
            }

            duk_get_prop_index(m_ctx, -1, 0);
            double v1 = duk_get_number(m_ctx, -1);
            duk_pop(m_ctx);

            duk_get_prop_index(m_ctx, -1, 1);
            double v2 = duk_get_number(m_ctx, -1);
            duk_pop(m_ctx);

            _val = glm::vec2(v1, v2);
            break;
        }
        case StyleParamKey::color:
        case StyleParamKey::outline_color:
        case StyleParamKey::font_fill:
        case StyleParamKey::font_stroke:
        case StyleParamKey::font_stroke_color: {
            if (len < 3 || len > 4) {
                logMsg("Warning: Wrong array size for color: '%d'.\n", len);
                break;
            }
            duk_get_prop_index(m_ctx, -1, 0);
            double r = duk_get_number(m_ctx, -1);
            duk_pop(m_ctx);

            duk_get_prop_index(m_ctx, -1, 1);
            double g = duk_get_number(m_ctx, -1);
            duk_pop(m_ctx);

            duk_get_prop_index(m_ctx, -1, 2);
            double b = duk_get_number(m_ctx, -1);
            duk_pop(m_ctx);

            double a = 1.0;
            if (len == 4) {
                duk_get_prop_index(m_ctx, -1, 3);
                a = duk_get_number(m_ctx, -1);
                duk_pop(m_ctx);
            }

            _val = (((uint32_t)(255.0 * a) & 0xff) << 24) |
                   (((uint32_t)(255.0 * r) & 0xff)<< 16) |
                   (((uint32_t)(255.0 * g) & 0xff)<< 8) |
                   (((uint32_t)(255.0 * b) & 0xff));
            break;
        }
        default:
            break;
        }

    } else if (duk_is_number(m_ctx, -1)) {

        switch (_key) {
        case StyleParamKey::width:
        case StyleParamKey::outline_width:
        case StyleParamKey::font_stroke_width: {
            double v = duk_get_number(m_ctx, -1);
            _val = static_cast<float>(v);
            break;
        }
        case StyleParamKey::order:
        case StyleParamKey::priority:
        case StyleParamKey::color:
        case StyleParamKey::outline_color:
        case StyleParamKey::font_fill:
        case StyleParamKey::font_stroke:
        case StyleParamKey::font_stroke_color: {
            _val = static_cast<uint32_t>(duk_get_uint(m_ctx, -1));
            break;
        }
        default:
            break;
        }
    } else {
        logMsg("Warning: Unhandled return type from Javascript function.\n");
    }

    duk_pop(m_ctx);

    DUMP("parseStyleResult\n");
    return !_val.is<none_type>();
}
/*!
 * Writes an logfile messages from type ERROR
 */
void TTMessageLogger::errorMsg(QString caller, QString msgString)
{
logMsg(ERROR, caller, msgString);
}
Esempio n. 19
0
/**warning logs a message at WARNING level.
 * The message is appended to the log file if the current level is in the range SEVERE to WARNING
 *
 *@param toLog the message text to log
 */
void Logger::warning(string toLog) {
	if (levelSet < WARNING) return;
	logMsg(WARNING, toLog);
}
/*!
 * Writes an logfile messages from type DEBUG
 */
void TTMessageLogger::debugMsg(QString caller, QString msgString)
{
logMsg(DEBUG, caller, msgString); 
}
Esempio n. 21
0
/**config logs the message at CONFIG level.
 * The message is appended to the log file if the current level is in the range SEVERE to CONFIG
 *
 *@param toLog the message text to log
 */
void Logger::config(string toLog) {
	if (levelSet < CONFIG) return;
	logMsg(CONFIG, toLog);
}
Esempio n. 22
0
// Responsible to read the tileData from the service
// takes a vector of tileCoordinates to be read from the service.
bool MapzenVectorTileJson::LoadTile(std::vector<glm::ivec3> _tileCoords) {
    std::vector<std::unique_ptr<std::string>> urls;

    if(_tileCoords.size() == 0) {
        logMsg("No tiles to fetch.");
    }

    //construct tileID and url for every tileCoord
    for(auto& tileCoord : _tileCoords) {
        urls.push_back(constructURL(tileCoord));
    }

    CURLM *multiHandle;
    CURLMsg *handleMsg;
    // file descriptors to be used with curl_multi_fdset and select()
    fd_set fdRead;
    fd_set fdWrite;
    fd_set fdExcep;
    int fdMax;
    struct timeval timeout;
    int rc; //return value for select() call
    CURLMcode cres;

    int queuedHandles, numHandles = urls.size();
    int prevHandle;
    int fetchTry = 0; //Counter to check for curl/select timeOuts.. maxed by static count MAX_FETCH_TRY
    int fdsetTimeoutCount = 0;

    // out will store the stringStream contents from libCurl
    std::stringstream *out[urls.size()];

    curl_global_init(CURL_GLOBAL_DEFAULT);

    multiHandle = curl_multi_init();
    int count = 0;

    // initialize curl simple interface for every url
    for(auto& url : urls) {
        out[count] = new std::stringstream;
        curlInit(multiHandle, *url.get(), out[count]);
        count++;
    }

    //do curl stuff
    if(multiHandle) {
        //start fetching
        cres = curl_multi_perform(multiHandle, &numHandles);
        if(cres != CURLM_OK) {
            logMsg("curl_multi_perform failed %d\n", cres);
            for(auto i = 0; i < urls.size(); i++) {
                delete out[i];
            }
            urls.clear();
            return false;
        }

        //if numHandles is 0, then multi_perform has no easy handles to perform fetching
        if(!numHandles) {
            logMsg("Number of easy handles returned by curl_multi_perform is 0, should not be.");
            for(auto i = 0; i < urls.size(); i++) {
                delete out[i];
            }
            urls.clear();
            return true;
        }
        
        //Start fetching info until no easy handle left to fetch data
        do {
            //set all file descriptors to 0
            FD_ZERO(&fdRead);
            FD_ZERO(&fdWrite);
            FD_ZERO(&fdExcep);

            //timeout specification for select() call
            //select() will unblock either when a fd is ready or tileout is reached
            timeout.tv_sec = 1; //enough time for fd to be ready reading data... could be optimized.
            timeout.tv_usec = 0;

            //get file descriptors from the transfer
            cres = curl_multi_fdset(multiHandle, &fdRead, &fdWrite, &fdExcep, &fdMax);

            if(cres != CURLM_OK) {
                logMsg("curl_multi_fdset failed: %d\n", cres);
                for(auto i = 0; i < urls.size(); i++) {
                    delete out[i];
                }
                urls.clear();
                return false;
            }
            
            //wait and repeat until curl has something to report to the kernel wrt file descriptors
            // TODO: if no internet, then this gets stuck... put a timeout here.
            while(fdMax < 0 && fdsetTimeoutCount < 20) {
                //TODO: Get a better heuristic on the sleep milliseconds

                //sleeps for 100 msec and calls perform and fdset to see if multi perform has started its job
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
                cres = curl_multi_perform(multiHandle, &numHandles);
                prevHandle = numHandles;
                curl_multi_fdset(multiHandle, &fdRead, &fdWrite, &fdExcep, &fdMax);
                std::cout<<"Here\n"; //TODO: Remove this. Its here to test how many times this loop runs till
                                     //multi_perform starts doing stuff
                fdsetTimeoutCount++;
            }

            if(fdMax < 0) {
                logMsg("fdMax set timeout: fdmax still not set by curl_multi_fdset. Internet connection??");
                for(auto i = 0; i < urls.size(); i++) {
                    delete out[i];
                }
                urls.clear();
                return false;
            }

            //select blocks the thread until the fd set by curl is ready with data.
            rc = select(fdMax+1, &fdRead, &fdWrite, &fdExcep, &timeout);

            // helper variables to convert extracted data to Json on the spot instead of waiting for all urls to be
            // fetched and then converting the extracted data to json
            char *url;
            char *tmpOutData; //to read the CURLINFO_PRIVATE data which is type casted to char* from stringstream*
            std::string tmpJsonData;
            int length;
            std::shared_ptr<Json::Value> jsonVal(new Json::Value);
            Json::Reader jsonReader;

            // see what select returned
            switch(rc) {
                case -1:
                    //select call ERRORed
                    break;
                case 0:
                    std::cout<<"Here timeout\n"; //TODO: Remove this. Its here to test how many times select times out.
                                                 // So far never with 1 sec of timeout.
                    //select call Timed out. No fd ready to read anything.
                    fetchTry++;
                    if(fetchTry == MAX_FETCH_TRY) {
                        curl_multi_cleanup(multiHandle);
                        curl_global_cleanup();
                        for(auto i = 0; i < urls.size(); i++) {
                            delete out[i];
                        }
                        urls.clear();
                        return false;
                    }
                    break;
                default:
                    // sleep for 5 msec to give enough time for curl to read data for any of the file descriptors.
                    std::this_thread::sleep_for(std::chrono::milliseconds(5));
                    std::cout<<"Possible Change\n"; //TODO: Remove this. Its here to test how many times fd is ready and
                                                    // will result in a complete data read
                    //Perform again to see what happened with individual easy handles
                    curl_multi_perform(multiHandle,&numHandles);
                    // if easy  handle status changed some urls are done.
                    if(prevHandle != numHandles) {
                        std::cout<<"Change happened\n";//TODO: Remove this. Only here for testing
                        prevHandle = numHandles;
                        handleMsg = curl_multi_info_read(multiHandle, &queuedHandles);
                        // for every url done fill the jsonValue
                        for(auto qHandItr = 0; qHandItr <= queuedHandles; qHandItr++) {
                            if(handleMsg->msg == CURLMSG_DONE) {
                                //get the url from the easyHandle
                                curl_easy_getinfo(handleMsg->easy_handle, CURLINFO_EFFECTIVE_URL , &url);
                                //get the tmpOutData which is holding the extracted info from the url
                                curl_easy_getinfo(handleMsg->easy_handle, CURLINFO_PRIVATE , &tmpOutData);
                                // typecast back from char* to std::stringstream
                                tmpJsonData = ((std::stringstream *)tmpOutData)->str();
                                length = tmpJsonData.size();
                                jsonReader.parse(tmpJsonData.c_str(), tmpJsonData.c_str() + length, *(jsonVal.get()));
                                // no way to get what ID this url was for so have to extract ID from url
                                m_JsonRoots[extractIDFromUrl(std::string(url))] = jsonVal;
                                logMsg("R: %d - %s <%s>\n", handleMsg->data.result, curl_easy_strerror(handleMsg->data.result), url);
                                curl_multi_remove_handle(multiHandle, handleMsg->easy_handle);
                                curl_easy_cleanup(handleMsg->easy_handle);
                            }
                        }
                    }
                    break;
            }
        }while(numHandles);
        
        curl_multi_cleanup(multiHandle);
        curl_global_cleanup();
    }

    for(auto i = 0; i < urls.size(); i++) {
        delete out[i];
    }
    urls.clear();
    return true;
}
Esempio n. 23
0
/**finest log the message at FINEST level.
 * The message is appended to the log file if the current level is in the range SEVERE to FINEST
 *
 *@param toLog the message text to log
 */
void Logger::finest(string toLog) {
	if (levelSet < FINEST) return;
	logMsg(FINEST, toLog);
}
Esempio n. 24
0
int main(int argc, char **argv)
{

	char *szTpmPasswd = NULL;
	int pswd_len;
	TSS_HTPM hTpm;
	TSS_HPOLICY hTpmPolicy;
	int iRc = -1;
	struct option opts[] = {
			{"force", no_argument, NULL, 'f'},
			{"well-known", no_argument, NULL, 'z'},
	};
	BYTE well_known[] = TSS_WELL_KNOWN_SECRET;

        initIntlSys();

	if (genericOptHandler
	    (argc, argv, "fz", opts, sizeof(opts) / sizeof(struct option),
	     parse, help) != 0)
		goto out;

	if (contextCreate(&hContext) != TSS_SUCCESS)
		goto out;

	if (contextConnect(hContext) != TSS_SUCCESS)
		goto out_close;

	if (contextGetTpm(hContext, &hTpm) != TSS_SUCCESS)
		goto out_close;

	if (!bValue) {
		if (isWellKnown){
			szTpmPasswd = (char *)well_known;
			pswd_len = sizeof(well_known);
		}else{
			szTpmPasswd = GETPASSWD(_("Enter owner password: "******"Failed to get password\n"));
				goto out_close;
			}
		}

		if (policyGet(hTpm, &hTpmPolicy) != TSS_SUCCESS)
			goto out_close;

		if (policySetSecret(hTpmPolicy, pswd_len,
				    (BYTE *)szTpmPasswd) != TSS_SUCCESS)
			goto out_close;
	}
	//Setup complete attempt command
	if (tpmClearOwner(hTpm, bValue) != TSS_SUCCESS)
		goto out_close;

	//Command successful
	iRc = 0;
	logSuccess(argv[0]);

	logMsg( _("TPM Successfuly Cleared.  You need to reboot to complete this operation.  After reboot the TPM will be in the default state: unowned, disabled and inactive.\n") );

	//Cleanup
      out_close:
	if (szTpmPasswd && !isWellKnown)
		shredPasswd(szTpmPasswd);

	contextClose(hContext);

      out:
	return iRc;
}
Esempio n. 25
0
void
fssrGainScan(int id, char *filename, \
              int beg_chip, int end_chip, \
              int beg_chan, int end_chan,
              int start_thr, int chan_mult)
{
  FILE *fd;
  char fname[256], reg27[20];
  int thr, ichip, ich;
  int i, j;
  int zero_count, amp, min_hits;
  int base_thr = start_thr;
  int temp_start_thr, zero_status, a;

  uint32_t pulser_rate = vscmGetPulserRate(id);
  uint32_t scaler[128];

  /* Pulser Settings */
  const int start_amp = 75;
  const int end_amp = 125;
  const int step_amp = 25;
  int steps = ((end_amp - start_amp) / step_amp) + 1;

  /* Get current time for file saving */
  time_t now;
  time(&now);

  threshold_scan *data;

#ifdef VXWORKS
  int ticks = 1;
#else
  struct timespec ts; 
  ts.tv_sec = 0;
  ts.tv_nsec = 16666667; /* ~16.6 ms (similar to 1 tick on VxWorks) */
#endif

  if (vscmIsNotInit(&id, __func__))
    return;
/*
  if ((end_chip - beg_chip) > 3) {
    logMsg("ERROR: %s: Chip range must be 4 chips or less\n", __func__);
    logMsg("ERROR: %s: Output files will be overwritten if >4\n", __func__);
    return;
  }
*/
  if ((chan_mult < 1) || ((chan_mult & (chan_mult - 1)) != 0)) {
    logMsg("ERROR: %s: Channel multiplier (%d) ", __func__, chan_mult);
    logMsg("must be a power of 2\n");
    return;
  }

  data = malloc(steps * chan_mult * sizeof(threshold_scan));

  /* Temporarily disable both pulser outputs */
  vscmPulser(id, 0, 0, 1);

#ifdef VXWORKS
  min_hits = (int)(pulser_rate * (ticks / (float)sysClkRateGet()) * 0.99);
#else
  min_hits = (int)(pulser_rate * (float)(ts.tv_nsec * 1.0e-9) * 0.99);
#endif
  logMsg("INFO: %s: Min Hits = %d\n", __func__, min_hits);

  for (ichip = beg_chip; ichip <= end_chip; ichip++) {
#ifdef DEBUG
    fssrStatus(id, ichip);
#endif

    if(filename)
    {
      logMsg("%s\n", filename);
      logMsg("cd %d\n", chdir(filename));
      logMsg("%s\n", getcwd());
      char datetime[] = "YYYYMMDD_HHMM";
      strftime(datetime, sizeof(datetime), "%Y%m%d_%H%M", localtime(&now));
      struct stat sb;
      if (stat(datetime, &sb) != 0)
        mkdir(datetime, S_IRWXU | S_IRWXG | S_IROTH);
      char host[255];
      gethostname(host, 255);
      sprintf(fname,"%s/%s_s%02d_c%1d_u%1d", datetime, host, id, ((ichip > 3) ? 2 : 1), ((ichip % 4) + 1));
      if( (fd = fopen(fname, "w")) <= NULL )
      {
        logMsg("ERROR: %s: Opening file: %s\n", __func__, fname);
        free(data);
        return;
      }
      else
      {
        logMsg("INFO: %s: Output file: %s\n", __func__, fname);
      }
    }
    else
	{
      logMsg("Chip %d\n", ichip);
	}

    fssrParseControl(id, ichip, reg27);
    if (filename) {
      fprintf(fd, "%s\n", reg27);
    }
    else
      printf("%s\n", reg27);

    /* Set all discriminators  - start of loop*/
    for (i = 0; i < 8; i++) {
      fssrSetThreshold(id, ichip, i, base_thr + (i * 30));
    }

    for (i = 0; i < (128 / chan_mult); i++)
    {
      start_thr = base_thr;
      thr = start_thr;
      temp_start_thr = 1;

      fssrKillMaskDisableAll(id, ichip);
      fssrInjectMaskDisableAll(id, ichip);
	  /*      printf("[%d] Chan: ",id);*/

      for (j = 0; j < chan_mult; j++)
      {
        ich = i + (j * (128 / chan_mult));
		/*        printf("%d ", ich);*/
        fssrKillMaskEnableSingle(id, ichip, ich);
        fssrInjectMaskEnableSingle(id, ichip, ich);
      }
	  /*      printf("\n"); fflush(stdout);*/

      for (a = 0; a < steps; a++)
      {
        amp = start_amp + (a * step_amp);
        thr = start_thr;
        zero_count = 0;
		/*        printf("[%d] Amp: %d Start: %d\n",id, amp, thr); fflush(stdout);*/

        vscmPulser(id, ((ichip > 3) ? 2 : 1), amp, (int)(min_hits / 0.99));

        while(thr < 256 && zero_count < 2)
        {
          zero_status = 0;
          temp_start_thr = 0;
          fssrSetThreshold(id, ichip, 0, thr);

          vscmDisableChipScaler(id, ichip);
          vscmClearStripScalers(id, ichip);
          vscmEnableChipScaler(id, ichip);
          vscmDisableChipScaler(id, ichip);
          vscmEnableChipScaler(id, ichip);

          vscmPulserStart(id);
   
          /* Gather data by sleeping */
#ifdef VXWORKS
          taskDelay(ticks);
#else
          nanosleep(&ts, NULL);
#endif

          vscmDisableChipScaler(id, ichip);
          vscmReadStripScalers(id, ichip, scaler);

          for (j = 0; j < chan_mult; j++)
          {
            ich = i + (j * (128 / chan_mult));

            if (thr == start_thr)
            {
              data[(a * chan_mult) + j].amp = amp;
              data[(a * chan_mult) + j].start = start_thr;
            }
            data[(a * chan_mult) + j].hits[thr] = scaler[ich];
   
            if (scaler[ich] > min_hits)
              temp_start_thr++;

            if (scaler[ich] == 0)
              zero_status++;
          }

          if (zero_status == chan_mult)
            zero_count++;
          else
            zero_count = 0;

          if (temp_start_thr == chan_mult)
            start_thr = thr;

          thr++;
        }
      }

      /* Save the data struct to file */
      if (filename)
      {
        for (j = 0; j < chan_mult; j++)
        {
          ich = i + (j * (128 / chan_mult));
          fprintf(fd, "%d\n", ich);
          for (a = 0; a < steps; a++)
          {

            fprintf(fd, "%d, ", data[(a * chan_mult) + j].amp);
            fprintf(fd, "%d ", data[(a * chan_mult) + j].start);
            zero_count = 0;
            thr = data[(a *chan_mult) + j].start;

            while(thr < 256 && zero_count < 2)
            {
              fprintf(fd, ",%d ", data[(a * chan_mult) + j].hits[thr]);

              if (data[(a * chan_mult) + j].hits[thr] == 0)
                zero_count++;
              else
                zero_count = 0;
              thr++;
            }
            fprintf(fd, "\n");
          }
          fprintf(fd, "\n");
        }
        fflush(fd);
      }
    } /* End of Channel loop */
    if (filename)
      fclose(fd);
    else
      printf("\n");

    /* Set all discriminators  - end of loop*/
    for (i = 0; i < 8; i++) {
      fssrSetThreshold(id, ichip, i, base_thr + (i * 30));
    }

  } /* End of Chip loop */

  free(data);
}
Esempio n. 26
0
static retCode debugOption(char *option, logical enable, void *cl) {
  char *c = option;

  while (*c) {
    switch (*c++) {
      case 'd':    /* single step instruction tracing */
#ifdef TRACEEXEC
        insDebugging = True;
        tracing = True;
        interactive = True;
        continue;
#else
      logMsg(logFile, "Instruction-level debugging not enabled\n");
      return Error;
#endif

      case 'D':    /*  instruction tracing */
#ifdef TRACEEXEC
        insDebugging = True;
        tracing = True;
        interactive = False;
        continue;
#else
      logMsg(logFile, "Instruction-level tracing not enabled\n");
      return Error;
#endif

      case 'u':    /*  debug the debugger */
#ifdef TRACE_DBG
        debugDebugging = True;
        continue;
#else
      logMsg(logFile, "Debugging tracing not enabled\n");
      return Error;
#endif

      case 'v':    /* turn on verify tracing */
#ifdef TRACEVERIFY
        traceVerify = True;
        continue;
#else
      logMsg(logFile, "code verification not enabled\n");
      return Error;
#endif

      case 'm':    /* trace memory allocations  */
#ifdef TRACEMEM
        traceMemory = True;

        atexit(dumpGcStats);
        continue;
#else
      logMsg(logFile,"memory tracing not enabled");
            return -1;
#endif

      case 'H':    /* validate heap after allocations  */
#ifdef TRACEMEM
        validateMemory = True;
        continue;
#else
      logMsg(logFile,"memory validation not enabled");
      return -1;
#endif

      case 'l':    /* trace synch locks */
#ifdef LOCKTRACE
        traceLock = True;
        continue;
#else
        logMsg(logFile, "sync tracing not enabled");
        return Error;
#endif

      case 'G':    /* Internal symbolic tracing */
#ifdef TRACEEXEC
        lineDebugging = True;
        interactive = False;
        tracing = True;
        continue;
#else
      logMsg(logFile, "tracing not enabled");
      return Error;
#endif

      case 'g':    /* Internal symbolic debugging */
        lineDebugging = True;
        interactive = True;
        tracing = True;
        continue;

      case 's':
#ifdef TRACESTATS
        if (runStats) {
          atexit(dumpInsStats);
        } else {
          atexit(dumpInsCount);
        }
        runStats = True;
        break;
#else
      logMsg(logFile, "instruction counting not enabled");
      return Error;
#endif

      case 'M':     /* Trace manifest mgt */
#ifdef TRACEMANIFEST
        traceManifest = True;
#else
      logMsg(logFile, "Resource tracing not enabled\n");
      return Error;
#endif

      case 'P':    /* trace package operations  */
#ifdef TRACEPKG
        tracePkg = True;
        continue;
#else
      logMsg(logFile,"package tracing not enabled");
      return -1;
#endif
      case 'F':   // Show file name instead of package
        showPkgFile = True;
        continue;

      case 'C': // Toggle showing colors
        showColors = !showColors;
        continue;

      default:;
    }
  }

  return Ok;
}
//+CAP_2353_001		
///////////////////////////////////////
// Test_Write_Read_DDR
///////////////////////////////////////
t_uint32 Test_Write_Read_DDR()
{
	t_uint32 address;
	t_uint32 i;
	t_uint32 data;
	t_uint32 data_written[33];
	t_uint8 byte1, byte2;

	logMsg("LpDDR test...\r\n");
	//write in RAM to test address wires [0:12] and data wires [0:27]
	//adress (0x1) to (0x8000000) (=> some address wires will be tested twice, doesn't matter)
	//data   0x1 to 0x8000000 
	address = 1;
	data = 1;	
	for (i=0; i<2; i++ )
	{
		data_written[i] = data;
		*((t_uint8*)(address)) = (t_uint8)(data);

		address = 1<<(i+1);
		data = data<<1;
	}

	/*write in RAM DDR 32bit data*/
	/*adress 0x4 to 0x8000000*/
	/*data   0x4 to 0x8000000*/ 
	for (i=2; i<28; i++ )
	{
		data_written[i] = data;
		*((t_uint32*)(address)) = (t_uint32)(data);

		address = 1<<(i+1);
		data = data<<1;
	}

	//write in RAM to test data wires [28:31]
	//address 0x800 + 4*n*(1 word)
	//data: 0x10000000 to 0x80000000 => all 32 data wires will be then tested!!!

	address = 0x800;
	for (i=1; i<=4; i++)
	{
		//write in address 0x804 data 0x10000000
		//then write in address 0x808 data 0x20000000
		//then write in address 0x80C data 0x40000000
		//then write in address 0x810 data 0x80000000
		data_written[i+27] = 1<<(i+27);
		*((t_uint32*)(address+(4*i))) = 1<<(i+27);
	}

	/*write in RAM DDR - to check bit 0 and 1 of data bus*/
	/*address 0x814*/
	/*data 0x3*/
	address = 0x814;
	data = 0x3;
	data_written[32] = data;
	*((t_uint32*)(address)) = data;

	//////////////////
	//now check the written data by the way of a readback
	//same loops as the both above...
	/////////////////

	/* test bit 0 and bit 1 of address bus */
	address = 0;

	byte1 = ((*(t_uint32*)(address)) & (0x00FF00)) >> 8;
	if (byte1 != (t_uint8)(data_written[0]))
	{
		return BOOT_INTERNAL_ERROR;
	}

	byte2 = ((*(t_uint32*)(address)) & (0xFF0000)) >> 16;
	if (byte2 != (t_uint8)(data_written[1]))
	{
		return BOOT_INTERNAL_ERROR;
	}

	/*set address for next reading back*/
	address = 0x4;

	for (i=2; i<28; i++ )
	{
		if (*((t_uint32*)(address)) != (t_uint32)(data_written[i]))
		{
			return BOOT_INTERNAL_ERROR;
		}
		address = 1<<(i+1);
	}

	address = 0x800;
	for (i=1; i<=4; i++)
	{
		if (*((t_uint32*)(address+(4*i))) != data_written[i+27])
		{
			return BOOT_INTERNAL_ERROR;
		}
	}
	/* test bit 0 and bit 1 of data bus */
	address = 0x814;
	if (*((t_uint32*)address) != data_written[32])
	{
		return BOOT_INTERNAL_ERROR;
	}

	logMsg("OK\r\n");
	return BOOT_OK;
}
Esempio n. 28
0
ROUTE_ENTRY * routeEntryFind
    (
    ROUTE_ENTRY * pRoute, 	/* primary route for destination/netmask */
    short protoId, 		/* protocol identifer for route */
    struct sockaddr * pGateway,	/* next hop gateway for route */
    ROUTE_ENTRY ** ppGroup, 	/* initial entry (head) of existing group */
    ROUTE_ENTRY ** ppLastGroup,	/* predecessor if head of group changes */
    ROUTE_ENTRY ** ppNextGroup, /* successor if head of group changes */
    ROUTE_ENTRY ** ppLast, 	/* previous entry in matching group */
    ROUTE_ENTRY ** ppNext, 	/* next entry in matching group */
    UCHAR weight 		/* weight value for route, 0 for delete */
    )
    {
    ROUTE_ENTRY * pGroup;    /* initial route entry with matching protocol */
    ROUTE_ENTRY * pMatch = NULL;  /* duplicate route entry, if any. */

    ROUTE_ENTRY * pNextGroup = NULL;  /* Group with higher minimum weight. */
    ROUTE_ENTRY * pLastGroup = NULL;  /* Previous group entry in list. */
    ROUTE_ENTRY * pBack = NULL;   /* Preceding route entry in group. */
    ROUTE_ENTRY * pNext = NULL;   /* Next route entry in group. */

    ROUTE_ENTRY * pTemp;          /* Loop index. */

    BOOL gatewayFlag;    /* Gateway value specified? */

    UCHAR nextWeight;    /* Weight for initial group entry after increase. */

    if (pGateway == NULL || SOCKADDR_IN (pGateway) == 0)
        gatewayFlag = FALSE;
    else
        gatewayFlag = TRUE;
 
    /*
     * Find the group which matches the protocol for the targeted route,
     * if any. Use the first group if no value is specified. This search
     * also finds an adjacent group if no match occurs or if the protocol
     * does not match the first group and the provided weight value is less
     * than the initial entry in the matching group.
     */

    for (pGroup = pRoute; pGroup != NULL; pGroup = pGroup->diffNode.pFrwd)
        {
        if (protoId == 0)    /* No protocol specified - use initial group. */
            break;

        if (RT_PROTO_GET(ROUTE_ENTRY_KEY(pGroup)) == protoId)
            break;

        /*
         * If the weight value for the targeted route is less than
         * the current minimum in an earlier group (which therefore
         * uses a lower weight than the matching group), save the
         * new successor for the matching group. Ignore this test
         * for the delete operation, which selects a new adjacent
         * group separately, if needed.
         */

        if (weight && pNextGroup == NULL &&
                weight < pGroup->rtEntry.rt_rmx.weight)
            {
            pNextGroup = pGroup;

#ifdef DEBUG
            logMsg ("routeEntryFind: inserting ahead of group at %x.\n",
                    pNextGroup, 0, 0, 0, 0, 0);
#endif
            }

        /*
         * Save the current group entry, which will eventually equal the
         * tail of the list if no matching group exists. That final entry
         * is required when creating a new group with a larger minimum
         * weight than all existing groups.
         */

        pLastGroup = pGroup;
        }

    /*
     * Assign the preceding group if the weight value inserts a new group
     * into the list or promotes an existing group to an earlier position.
     */

    if (pNextGroup)
        {
        pLastGroup = pNextGroup->diffNode.pBack;
        }

    /*
     * Find the specific route entry which matches the supplied gateway
     * address within the selected group. Use the initial entry if no
     * value is specified. The delete and change operations require a
     * match, but the add operation fails in that case.
     *
     * This search also finds the neighboring routes within the matching
     * group based on any specified weight value.
     */

    for (pTemp = pGroup; pTemp != NULL; pTemp = pTemp->sameNode.pFrwd)
        {
        /*
         * Save the first entry which matches the specified gateway.
         * The second condition is not strictly necessary, since each
         * gateway value is unique, but bypasses needless tests once
         * a match is found.
         */

        if (gatewayFlag && pMatch == NULL)
            {
            if (ROUTE_ENTRY_GATEWAY (pTemp)->sa_family == AF_LINK)
                {
                /*
                 * The gateway field contains an ARP template. The entry
                 * only matches for a search using the interface's assigned
                 * IP address as the gateway.
                 */

                if (SOCKADDR_IN (pTemp->rtEntry.rt_ifa->ifa_addr)
                                        == SOCKADDR_IN (pGateway))
                    {
                    /* Specified route entry exists - save the match. */

                    pMatch = pTemp;
                    }
                }
            else if (SOCKADDR_IN (ROUTE_ENTRY_GATEWAY (pTemp))
                                        == SOCKADDR_IN (pGateway))
                {
                /* Specified route entry exists - save the match. */

                pMatch = pTemp;
                }
            }

        if (gatewayFlag == FALSE && pMatch == NULL) 
            {
            /* Use the initial entry if no gateway is specified. */

            pMatch = pGroup;
            }

        /*
         * The delete operation does not provide a weight value. Save
         * the neighboring route for the add and change operations.
         */

        if (weight && pNext == NULL &&
                weight < pTemp->rtEntry.rt_rmx.weight)
            {
            pNext = pTemp;
            }

        /* Halt the search after finding the matching entry and location. */

        if (pMatch && pNext)
            break;

        /*
         * Save the current route, which eventually stores the last
         * entry in the list. That value is only needed if the weight
         * is larger than all existing entries in the group.
         */

        pBack = pTemp;
        }

    /*
     * Save the correct predecessor if the weight does not place the
     * corresponding route at the end of the list. That value will
     * equal NULL if the new position is the head of the list.
     *
     * Otherwise, the preceding entry already equals the last item in the
     * list (which occurs when appending a new route with the maximum weight
     * to an existing group) or remains NULL (if the group does not exist).
     * No correction is needed in either case.
     */

    if (pNext)
        {
        pBack = pNext->sameNode.pBack;
        }

    /*
     * Update the chosen adjacent group, if needed. The results of the
     * previous search are only valid if the weight value corresponds
     * to the initial entry in a group, the selected route is not part
     * of the first group, and the weight is reduced enough to alter
     * the relative position of the selected group.
     */

    if (pNext == pGroup)
        {
        /*
         * The specified weight corresponds to the initial entry in
         * a group, so either the weight of the group is reduced or it
         * corresponds to the first entry in a new group. Update the
         * neighboring groups selected with the earlier search if needed.
         */

        if (pGroup && pNextGroup == NULL)
            {
            /*
             * The group exists and no successor is assigned, so the
             * earlier search found a matching group before detecting
             * a different group with a higher weight than the specified
             * value. This condition indicates that the reduced weight does
             * not change the relative location of the matching group.
             */

            pNextGroup = pGroup->diffNode.pFrwd;
            pLastGroup = pGroup->diffNode.pBack;
            }
        }

    /*
     * Finish assigning the adjacent group, if needed. The earlier search
     * only selects an adjacent group when the specified weight value is
     * less than the weight of the initial entry in the matching group or
     * is the first entry in a new group.
     */

    if (pNext != pGroup && weight)
        {
        /*
         * Find the correct adjacent group for an unchanged weight or an
         * increase in the weight value of an entry in an existing group.
         */

        if (pMatch == NULL || pMatch != pGroup)
            {
            /*
             * If the selected route is not the initial entry, it is
             * not connected to any adjacent groups.
             */

            pLastGroup = pNextGroup = NULL;
            }
        else if (weight == pMatch->rtEntry.rt_rmx.weight)
            {
            /*
             * The earlier search only finds an adjacent group when the
             * weight of the group is reduced. Set the correct adjacent
             * groups since the location in the group list is unchanged.
             */

            pNextGroup = pGroup->diffNode.pFrwd;
            pLastGroup = pGroup->diffNode.pBack;
            }
        else
            {
            /*
             * The initial entry in the group list uses an increased
             * weight. Set the correct weight value and find the new
             * adjacent group.
             */

            pTemp = pMatch->sameNode.pFrwd;
            nextWeight = weight;

            /*
             * Use the weight value of the next initial group entry if 
             * the new weight will change the location of the current
             * initial entry in the group.  
             */

            if (pTemp && weight > pTemp->rtEntry.rt_rmx.weight)
                nextWeight = pTemp->rtEntry.rt_rmx.weight;

            if (pMatch->rtEntry.rt_rmx.weight == nextWeight)
                {
                /*
                 * The next entry in the list used the same weight
                 * as the initial entry, so the position is unchanged.
                 */

                pNextGroup = pGroup->diffNode.pFrwd;
                pLastGroup = pGroup->diffNode.pBack;
                }
            else
                {
                /*
                 * The minimum weight of the group increased. Find the
                 * new location.
                 */

                for (pTemp = pGroup; pTemp != NULL;
                         pTemp = pTemp->diffNode.pFrwd)
                    {
                    if (nextWeight < pTemp->rtEntry.rt_rmx.weight)
                        {
                        pNextGroup = pTemp;
                        break;
                        }

                    /*
                     * Save the current entry in case the next entry
                     * is the correct successor.
                     */

                    pLastGroup = pTemp;
                    }

                /*
                 * Set the preceding group to the correct value if the
                 * increased weight does not change the relative location
                 * of the group.
                 */

                if (pLastGroup == pGroup)
                    pLastGroup = pGroup->diffNode.pBack;
                }
            }
        }

    /*
     * Correct the adjacent route within the matching group, if needed.
     * That search places a route after any other entries with the same
     * weight. This behavior is not correct when the weight of an existing
     * entry does not change.
     */

    if (pMatch && weight == pMatch->rtEntry.rt_rmx.weight)
        {
        pNext = pMatch->sameNode.pFrwd;
        pBack = pMatch->sameNode.pBack;
        }

    /*
     * Save the initial entry in the group and any adjacent entries in
     * the supplied parameters. The delete operation does not retrieve
     * any neighboring routes or specify the weight needed to assign
     * those values.
     */

    if (ppGroup)
        *ppGroup = pGroup;

    if (ppLastGroup)
        *ppLastGroup = pLastGroup;

    if (ppNextGroup)
        *ppNextGroup = pNextGroup;

    if (ppLast)
        *ppLast = pBack;

    if (ppNext)
        *ppNext = pNext;

    return (pMatch);
    }
 UnbufferedRsStmtTest::UnbufferedRsStmtTest( const String & name ) : StatementTest( name )
 {
   logMsg( "UnbufferedRsStmtTest ctor called" );
 }
Esempio n. 30
0
bool Contest::initTimers() {

  int arg = ID_SOC;
	SOC = TimeStamp(2003, 7, 1);
	ACE_Reactor::instance()->schedule_timer(this,
									(const void *) arg,
									SOC.getTimeStamp() - time(0));

  arg = ID_EOC;
	EOC = TimeStamp(2004, 1, 1, 1);
	ACE_Reactor::instance()->schedule_timer(this,
									(const void *) arg,
									EOC.getTimeStamp() - time(0));

	TimeStamp start(SOC), end(EOC), current(start);

  arg = ID_EOW;
	EOW.push_back(current);
	current.setTimeStamp(current.nextWeek());
	while (current < end) {
		EOW.push_back(current);
 		ACE_Reactor::instance()->schedule_timer(this,
  								(const void *) arg,
	  							current.getTimeStamp() - time(0));
		current.setTimeStamp(current.nextWeek());

  } 	

	vector<TimeStamp>::iterator i;
	i = EOW.begin();
  stringstream debug;
  debug << "Weekly timers: (arg = " << arg << ")" << endl;
	logMsg(debug.str());
	while (i != EOW.end()) {
		logMsg(i->toString());
		i++;
	}

  arg = ID_EOM;
  debug.str("");
 	debug << "Monthly timers: (arg = " << arg << ")" << endl;
  logMsg(debug.str());
	EOM.push_back(TimeStamp(2003, 7, 1));
	EOM.push_back(TimeStamp(2003, 8, 1));
  EOM.push_back(TimeStamp(2003, 9, 1));
  EOM.push_back(TimeStamp(2003, 10, 1));
  EOM.push_back(TimeStamp(2003, 11, 1));
  EOM.push_back(TimeStamp(2003, 12, 1));
  EOM.push_back(TimeStamp(2004, 1, 1));
	i = EOM.begin();
	i++;
	while (i != EOM.end()) {
		ACE_Reactor::instance()->schedule_timer(this,
									(const void *) arg,
									i->getTimeStamp() - time(0));
		logMsg(i->toString());
		i++;
	}	

  arg = ID_EOD;
	end = EOC;
	current = SOC;
	EOD.push_back(current);
	current++;
	while (current < end) {
 		EOD.push_back(current);
    if ((find(EOW.begin(), EOW.end(), current) == EOW.end()) &&
         find(EOM.begin(), EOM.end(), current) == EOM.end()) {
    		ACE_Reactor::instance()->schedule_timer(this,
	    								(const void *) arg,
		    							current.getTimeStamp() - time(0));
    }
		current++;
	}

	i = EOD.begin();
  debug.str("");
	debug << "Daily timers: (arg = " << arg << ")" << endl;
  logMsg(debug.str());
	while (i != EOD.end()) {
		logMsg(i->toString());
		i++;
	}

	logMsg("Start of Contest timer: ");
	logMsg(SOC.toString());

	logMsg("End of Contest timer: ");
	logMsg(EOC.toString());

	return true;
}