void SimpleSendRecvImpl::SendThread::run()
      {
        Group *g = this->group;

        while (1) {
          Action *action = g->sendQueue.get();
          double t0 = getSysTime();
          MPI_CALL(Send(action->data,action->size,MPI_BYTE,
                        action->addr.rank,g->tag,action->addr.group->comm));
          double t1 = getSysTime();
#if PROFILE_MPI
          if (logIt) {
            t_send += (t1-t0);
            b_sent += action->size;

            MsgLog log;
            log.to = action->addr.rank;
            log.size = action->size;
            log.begin = t0;
            log.end = t1;
            sendLog.push_back(log);
          }
#endif
          free(action->data);
          delete action;
        }
      }
      void SimpleSendRecvImpl::RecvThread::run()
      {
        Group *g = (Group *)this->group;

        while (1) {
          MPI_Status status;
          // PING;fflush(0);
          MPI_CALL(Probe(MPI_ANY_SOURCE,g->tag,g->comm,&status));
          Action *action = new Action;
          action->addr = Address(g,status.MPI_SOURCE);

          MPI_CALL(Get_count(&status,MPI_BYTE,&action->size));

          action->data = malloc(action->size);
          double t0 = getSysTime();
          MPI_CALL(Recv(action->data,action->size,MPI_BYTE,status.MPI_SOURCE,status.MPI_TAG,
                        g->comm,MPI_STATUS_IGNORE));
          double t1 = getSysTime();
#if PROFILE_MPI
          if (logIt) {
            t_recv += (t1-t0);
            b_recv += action->size;

            MsgLog log;
            log.to = action->addr.rank;
            log.size = action->size;
            log.begin = t0;
            log.end = t1;
            recvLog.push_back(log);
          }
#endif
          g->procQueue.put(action);
        }
      }
Exemplo n.º 3
0
void ds2_main(void)
{
    int err;
    ds2_setCPUclocklevel(11);

    //Initial video and audio and other input and output
    err = ds2io_init(1024);
    if(err) goto _failure;

    ConsoleInit(RGB15(31, 31, 31), RGB15(0, 0, 0), DOWN_SCREEN, 2);

    unsigned int Time = getSysTime();

    //go to user main funtion
    main (0, 0);

    Time = getSysTime() - Time;

    printf("%u units\n\nof 42.667 us", Time);

    ds2_setCPUclocklevel(0);

    struct key_buf inputdata;

    do
        ds2_getrawInput(&inputdata);
    while (inputdata.key == 0);
    ds2_setBacklight(3);
    ds2_plug_exit();
    while (1);

_failure:
    ds2_plug_exit();
}
Exemplo n.º 4
0
  void mpiCommTest(int &ac, char **av)
  {
    mpi::init(&ac,(const char**)av);
    if (ac == 2) {
      printf("now doing checksumming...\n");
      checkSum = true;
    }

    CheckSumAndBounceNewRandomMessage consumer;

    mpi::async::Group *world = mpi::async::createGroup("world",MPI_COMM_WORLD,
                                                       &consumer,ASYNC_TAG);
    srand(world->rank*13*17*23+2342556);
    
    mpi::world.barrier();
    char hostname[1000];
    gethostname(hostname,1000);
    printf("#osp:mpi: async comm test %i/%i on %s\n",mpi::world.rank,mpi::world.size,hostname); fflush(0);
    mpi::world.barrier();
    double t0 = getSysTime();

    for (int i=0;i<NUM_START_MESSAGES;i++) {
      // int tgt = (world->rank+i) % world->size;
      int tgt = rand() % world->size;
      sendRandomMessage(mpi::Address(world,tgt));
    }

    sleep(NUM_SECONDS);

    shutDown = true;
    mutex.lock();
    for (int i=0;i<world->size;i++) {
      int *msg = (int*)malloc(sizeof(int));
      *msg = -1;
      mpi::async::send(mpi::Address(world,i),msg,sizeof(int));
    }
    
    while (numTerminated < mpi::world.size)
      cond.wait(mutex);
    mutex.unlock();
    double t1 = getSysTime();
    double MBs = numBytesReceived / (1024*1024.f);
    double secs = t1-t0;
    printf("#osp:mpi(%2i): received %li msgs of %5.3lfMB in %2.1lfsecs, that's %5.3lfMB/sec\n",
           mpi::world.rank,numMessagesReceived,MBs,secs,MBs/secs); fflush(0);
           
    mpi::world.barrier();
    usleep(1000);
    mpi::async::shutdown();
  }
Exemplo n.º 5
0
void serial_timestamp_printf(const char* fmt, ...)
{
	{
		char timestamp[14];
		unsigned int Now = getSysTime();
		sprintf(timestamp, "%6u.%03u", Now / 23437, (Now % 23437) * 16 / 375);
		serial_puts(timestamp);
	}
	serial_putc(':');
	serial_putc(' ');

	char* line = malloc(82);
	va_list args;
	int linelen;

	va_start(args, fmt);
	if ((linelen = vsnprintf(line, 82, fmt, args)) >= 82)
	{
		va_end(args);
		va_start(args, fmt);
		free(line);
		line = malloc(linelen + 1);
		vsnprintf(line, linelen + 1, fmt, args);
	}
	serial_puts(line);
	va_end(args);
	free(line);
	serial_putc('\r');
	serial_putc('\n');
}
Exemplo n.º 6
0
int getErrState(enumPtr ePtr,char *recv,int len,char *result) {
	int i;
	char *errtext;
	char systime[35];
	char string[300];
	char *ptr;


	if (len%9) {
			sprintf(result,"Anzahl Bytes nicht mod 9");
			return(0);
	}

	for(i=0;i<len;i+=9) {
		ptr=recv+i;
		bzero(string,sizeof(string));
		bzero(systime,sizeof(systime));
		/* Fehlercode: Byte 0 */
		if (bytes2Enum(ePtr,ptr,&errtext,1))
			/* Rest SysTime */
			if(getSysTime(ptr+1,8,systime)) {
				snprintf(string, sizeof(string),"%s %s (%02X)\n",systime,errtext,(unsigned char)*ptr);
				strcat(result,string);
				continue;
			}
		/* Formatfehler */
		sprintf(result,"%s %s",errtext,systime);
		return(0);
	}
	result[strlen(result)-1]='\0'; /* \n verdampfen */
	return(1);
}
Exemplo n.º 7
0
//---------------------------------------------------------------------------------
int __libctru_gtod(struct _reent *ptr, struct timeval *tp, struct timezone *tz) {
//---------------------------------------------------------------------------------
	if (tp != NULL) {

		datetime_t dt = getSysTime();

		u64 delta = svcGetSystemTick() - dt.update_tick;

		u32 offset =  (u32)(u64_to_double(delta)/TICKS_PER_USEC);

		// adjust from 1900 to 1970
		u64 now = ((dt.date_time - 2208988800000ULL) * 1000) + offset;

		tp->tv_sec =  u64_to_double(now)/1000000.0;
		tp->tv_usec = now - ((tp->tv_sec) * 1000000);

	}

	if (tz != NULL) {
		tz->tz_minuteswest = 0;
		tz->tz_dsttime = 0;
	}

	return 0;

}
Exemplo n.º 8
0
// Returns number of milliseconds since 1st Jan 1900 00:00.
//---------------------------------------------------------------------------------
u64 osGetTime(void) {
//---------------------------------------------------------------------------------
	datetime_t dt = getSysTime();

	u64 delta = svcGetSystemTick() - dt.update_tick;

	return dt.date_time + (u32)(u64_to_double(delta)/TICKS_PER_MSEC);
}
qboolean OnClientConnectPost( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] )
{
    if( Initialized && sv_allowdownload->value > 0 )
    {
        if( cvar_enable_debug->value > 0 )
        {
            ModuleDebug.append( UTIL_VarArgs( "\n\"%s\" (index = %d, address = %s) is connecting.\n", pszName, ENTINDEX( pEntity ), pszAddress ) );
        }

        if( rm_enable_downloadfix.value <= 0 )
        {
            NotifyClientDisconnectHook->Restore();
            RETURN_META_VALUE( MRES_IGNORED, TRUE );
        }
        else
        {
            NotifyClientDisconnectHook->Patch();
        }

        char	ip[ 16 ];
        uint32	player				= ENTINDEX( pEntity );
        time_t	timeSystem			= getSysTime();
        time_t*	nextReconnectTime	= &PlayerNextReconnectTime[ player ];
        String*	currentPlayerIp		= &PlayerCurrentIp[ player ];

        // Retrieve server IP one time from there because
        // we need to let server.cfg be executed in case
        // a specific ip is provided and because I have not
        // found forward to use to put this call at this time.
        retrieveServerIp( &ServerInternetIp );

        // Retrieve the current client's IP without the port.
        retrieveClientIp( ip, pszAddress );

        // Sanity IP address check to make sure the index
        // is our expected player. If not, we consider it
        // as a new player and we reset variables to the default.
        if( currentPlayerIp->compare( ip ) )
        {
            *nextReconnectTime = 0;

            currentPlayerIp->clear();
            currentPlayerIp->assign( ip );
        }

        // We are allowed to reconnect the player.
        // We put a cool down of 3 seconds minimum to avoid possible
        // infinite loop since depending where it will download resources,
        // it can connect/disconnect several times.
        if( *nextReconnectTime < timeSystem )
        {
            *nextReconnectTime = timeSystem + 3;
            CLIENT_COMMAND( pEntity, "Connect %s %d\n", isLocalIp( ip ) ? ServerLocalIp.c_str() : ServerInternetIp.c_str(), RANDOM_LONG( 1, 9999 ) );
        }
    }

    RETURN_META_VALUE( MRES_IGNORED, TRUE );
}
Exemplo n.º 10
0
CBoardChange::CBoardChange(CPacket& pTiles, int pX, int pY, int pWidth, int pHeight)
{
	x = pX;
	y = pY;
	width = pWidth;
	height = pHeight;
	counter = tileRespawn;
	tileData << pTiles;
	modifyTime = getSysTime();
}
Exemplo n.º 11
0
CNpc::CNpc(CString& pImage, CString& pCode, float pX, float pY, CLevel* pLevel, bool levelNPC)
: x(pX), y(pY), hurtX(0), hurtY(0), level(pLevel), image(pImage),
levelNPC(levelNPC), clientCode(pCode),
rupees(0), darts(0), bombs(0), glovePower(0), blockFlags(0), bombPower(0),
power(0), sprite(2), shieldPower(0), swordPower(0),
visFlags(1)
{
	removeComments();
	weaponName = getFunctionParameter("toweapons ");
	if ( clientCode.length() < 20 )
	{
		if ( level->sparZone == false && clientCode.find("sparringzone") >= 0 )
			level->sparZone = true;
	}

	id = createNpcId(this);
	npcList.add(this);
	memset(saves, 0, sizeof(saves));
	memset(colors, 0, sizeof(colors));
	memset(modTime, 0, sizeof(modTime));
	gAni = "idle";
	for (int i = 0; i < 6; i++)
		imagePart.writeByte(32);

	modTime[NPCGIF] = getSysTime();
	modTime[ACTIONSCRIPT] = getSysTime();
	modTime[NPCX] = getSysTime();
	modTime[NPCY] = getSysTime();
	modTime[VISFLAGS] = getSysTime();
	modTime[NPCSPRITE] = getSysTime();
}
Exemplo n.º 12
0
      extern "C" void async_beginFrame() 
      {
        ++ frameID;
        if (frameID > 20) logIt = true;

        if (logIt) {
          T0 = getSysTime();
          t_send = 0;
          t_recv = 0;
          b_recv = 0;
          b_sent = 0;
          sendLog.clear();
          recvLog.clear();
        }
      }
Exemplo n.º 13
0
int getEncodeTime(int identifier,int fd, int cmd, char *data, int vallen)
{
#if 1
	unsigned char sdata[256] = {0};
	int totallen = 0;
	int cmdlen = sizeof(int);
	int retlen = sizeof(int);
	int ret = 0;
	DATE_TIME_INFO dtinfo;
	getSysTime(&dtinfo);
	totallen = MSGINFOHEAD + cmdlen + vallen + retlen;
	msgPacket(identifier,sdata, STRUCT_TYPE, totallen, cmd, ret);
	memcpy(sdata + totallen - vallen, &dtinfo, vallen);
	//DEBUG(DL_DEBUG, "getStreamParam...cmd =%d sdata=%s\n", cmd, sdata);
	send(fd, sdata, totallen, 0);
#endif
	return 0;
}
Exemplo n.º 14
0
float calculateLeadVehicleVelocity(S32 distanceToVehicle)
{
    float velocityOfLeadVehicle = 0;
    S32 currentTime = getSysTime();

    if(acc.lastTimeRead == 0)
    {
        acc.firstDistanceMeasurement = distanceToVehicle;
        acc.lastTimeRead = currentTime;
    }
    else
    {
        acc.secondDistanceMeasurement = distanceToVehicle;

        velocityOfLeadVehicle = ((float)(acc.secondDistanceMeasurement - acc.firstDistanceMeasurement) / 
                                 (float)(currentTime - acc.lastTimeRead) * (float)MS_PER_SEC / (float)CM_PER_M) + vehicle.vFront;
    }

    acc.lastTimeRead = currentTime;

    return velocityOfLeadVehicle;
}
Exemplo n.º 15
0
void CNpc::setProps(CPacket& pProps)
{
	int len;
	int previousMessage = 0;
	while(pProps.bytesLeft())
	{
		int index = pProps.readByte1();
		CPacket oldProp = getProperty(index);
		switch(index)
		{
			case NPCGIF:
				len = (unsigned char)pProps.readByte1();
				image = pProps.readChars(len);
			break;

			case ACTIONSCRIPT:
				len = (unsigned int)pProps.readByte2();
				clientCode = pProps.readChars(len);
			break;

			case NPCX:
				x = (float)(pProps.readByte1())/2;
			break;

			case NPCY:
				y = (float)(pProps.readByte1())/2;
			break;

			case NPCPOWER:
				power = (unsigned char)pProps.readByte1();
			break;

			case NPCRUPEES:
				rupees = (unsigned int)pProps.readByte3();
			break;

			case NPCARROWS:
				darts = (unsigned char)pProps.readByte1();
			break;

			case NPCBOMBS:
				bombs = (unsigned char)pProps.readByte1();
			break;

			case NGLOVEPOWER:
				glovePower = (unsigned char)pProps.readByte1();
			break;

			case NBOMBPOWER:
				bombPower = (unsigned char)pProps.readByte1();
			break;

			case NSWORDGIF:
			{
				int sp = (unsigned char)pProps.readByte1();
				if ( sp >= 30 )
				{
					sp -= 30;
					len = (unsigned char)pProps.readByte1();
					if ( len >= 0 )
						swordImage = pProps.readChars(len);
				}
				else
				{
					if ( sp >= 1 && sp <= 4 )
						swordImage = CString() << "sword" << toString(sp) << ".png";
					else
						swordImage = "";
				}
				swordPower = (sp >= 30) ? (sp - 30) : sp;
			}

			break;

			case NSHIELDGIF:
			{
				int sp = (unsigned char)pProps.readByte1();
				if(sp >= 10)
				{
					len = (unsigned char)pProps.readByte1();
					if(len >= 0)
						shieldImage = pProps.readChars(len);
				} else
				{
					if(sp >= 1 && sp <= 3)
						shieldImage = CString() << "shield" << toString(sp) << ".png";
					else shieldImage = "";
				}
				shieldPower = (sp >= 10) ? (sp - 10) : sp;
			}
			break;

			case NPCANI:
				len = (unsigned char)pProps.readByte1();
				gAni = pProps.readChars(len);
			break;

			case VISFLAGS:
				visFlags = (unsigned char)pProps.readByte1();
			break;

			case BLOCKFLAGS:
				blockFlags = (unsigned char)pProps.readByte1();
			break;

			case NPCMESSAGE:
				len = (unsigned char)pProps.readByte1();
				chatMsg = pProps.readChars(len);
			break;

			case NPCHURTDXDY:
				hurtX = ((float)(pProps.readByte1()-32))/32;
				hurtY = ((float)(pProps.readByte1()-32))/32;
			break;

			case NPCID:
				pProps.readByte3();
			break;

			case NPCSPRITE:
				sprite = (unsigned char)pProps.readByte1();
				if ( sprite >= 132 ) sprite = 0;
			break;

			case NPCCOLORS:
				for (int i = 0; i < 5; i++)
					colors[i] = (unsigned char)pProps.readByte1();
			break;

			case NPCNICKNAME:
				len = (unsigned char)pProps.readByte1();
				nickName = pProps.readChars(len);
			break;

			case NPCHORSEGIF:
				len = (unsigned char)pProps.readByte1();
				horseImage = pProps.readChars(len);
			break;

			case NPCHEADGIF:
				len = (unsigned char)pProps.readByte1();
				if (len < 100)
					headImage = CString() << "head" << toString(len) << ".png";
				else
					headImage = pProps.readChars(len-100);
			break;

			case NPCSAVE0:
			case NPCSAVE1:
			case NPCSAVE2:
			case NPCSAVE3:
			case NPCSAVE4:
			case NPCSAVE5:
			case NPCSAVE6:
			case NPCSAVE7:
			case NPCSAVE8:
			case NPCSAVE9:
				saves[index-NPCSAVE0] = (unsigned char)pProps.readByte1();
			break;

			case NALIGNMENT:
				ap = CLIP(pProps.readByte1(), 0, 100);
			break;

			case NPCGIFPART:
				imagePart = pProps.readChars(6);
			break;

			case NPCBODY:
				len = (unsigned char)pProps.readByte1();
				bodyImage = pProps.readChars(len);
			break;

			case NGATTRIB1:
			case NGATTRIB2:
			case NGATTRIB3:
			case NGATTRIB4:
			case NGATTRIB5:
				len = (unsigned char)pProps.readByte1();
				gAttribs[index-NGATTRIB1] = pProps.readChars(len);
			break;

			case NGMAPLEVELX:
				pProps.readByte1();
				break;

			case NGMAPLEVELY:
				pProps.readByte1();
				break;

			case NEMPTY43:
				errorOut( "debuglog.txt", CString() << "CNpc::setProps() tried to set NEMPTY" << toString(index) );
				CPlayer::sendGlobally( CPacket() << (char)SRPGWINDOW << "\"CNpc::setProps tried to set NEMPTY" << toString(index) << "\"" );
				break;

			case NGATTRIB6:
			case NGATTRIB7:
			case NGATTRIB8:
			case NGATTRIB9:
/* Does the client not send gani attribs > 9?
			case NGATTRIB10:
			case NGATTRIB11:
			case NGATTRIB12:
			case NGATTRIB13:
			case NGATTRIB14:
			case NGATTRIB15:
			case NGATTRIB16:
			case NGATTRIB17:
			case NGATTRIB18:
			case NGATTRIB19:
			case NGATTRIB20:
			case NGATTRIB21:
			case NGATTRIB22:
			case NGATTRIB23:
			case NGATTRIB24:
			case NGATTRIB25:
			case NGATTRIB26:
			case NGATTRIB27:
			case NGATTRIB28:
			case NGATTRIB29:
			case NGATTRIB30:
*/
				len = (unsigned char)pProps.readByte1();
				if(len >= 0)
					gAttribs[6+index-NGATTRIB6] = pProps.readChars(len);
			break;

			default:
//				errorOut( "debuglog.txt", CString() << "CNpc::setProps() tried to set unknown " << toString(index) );
//				CPlayer::sendGlobally( CPacket() << (char)SRPGWINDOW << "\"CNpc::setProps tried to set unknown " << toString(index) << "\"" );
				printf("NPC %d (%.2f, %.2f): ", id, x, y);
				printf("Unknown prop: %ud, readPos: %d\n", index, pProps.getRead());
				for (int i = 0; i < pProps.length(); ++i)
					printf("%02x ", (unsigned char)pProps[i]);
				printf("\n");

//				if ( detailedconsole )
//					printf("[%s] UNKNOWN NPC PROP: %i, Prev: %i, Value: %s\n", getTimeStr(1).text(), index, previousMessage, (pProps.text() + pProps.getRead()));
			return;
		}
		previousMessage = index;

		// If a prop changed, adjust its mod time.
		if ( index >= 0 && index < npcpropcount )
		{
			if ( oldProp != getProperty(index) )
				modTime[index] = getSysTime();
		}
	}
}
Exemplo n.º 16
0
mainWindow::mainWindow() : QMainWindow(),
    ui(new Ui::MainWindow)
{
    this->setMinimumSize(1000,500);
    // Creating the general UI
    ui->setupUi(this);

    // Making last minute adjustments and
    // initializing some parts of the UI
    ui->tabWidget->setCurrentIndex(0);
    ui->fileName->setText("log_file");
    ui->actionDisconnect->setEnabled(false);

    // Creating the logger file instance
    log = new QFile();

    // Creating the session file instance
    session = new QFile("session.dat");


    // Creating the QVector of double needed to store the graphs
    // points
    y[0] = new QVector<double>(2);
    x[0] = new QVector<double>(2);

    x[1] = new QVector<double>(200);

    y[1] = new QVector<double>(200);
    y[2] = new QVector<double>(200);
    y[3] = new QVector<double>(200);

    y[4] = new QVector<double>(200);
    y[5] = new QVector<double>(200);
    y[6] = new QVector<double>(200);

    y[7] = new QVector<double>(200);

    // The SettingsDialog instance handles the serial port configuration
    // window
    settings = new SettingsDialog();
    file_viewer = new FileViewer();

    // The Protocole instance handles the communication through the selected
    // serial port and parses the data received through a RegEx string
    protocole = new Protocole();


    // Now that everything's ready, try restoring
    // an existing session
    restoreSession();

    // Connecting all the commands button
    QSignalMapper * cmdMap = new QSignalMapper(this);

    connect(ui->cmdFreq,SIGNAL(clicked()),cmdMap,SLOT(map()));
    connect(ui->cmdBurst,SIGNAL(clicked()),cmdMap,SLOT(map()));
    connect(ui->cmdStream,SIGNAL(clicked()),cmdMap,SLOT(map()));
    cmdMap -> setMapping (ui->cmdFreq, "FRQ") ;
    cmdMap -> setMapping (ui->cmdBurst, "BST") ;
    cmdMap -> setMapping (ui->cmdStream, "STR") ;
    connect(cmdMap,SIGNAL(mapped(QString)),this,SLOT(sendCommandBox(QString)));

    // Connecting the buttons for RTC sync
    connect(ui->sendTime,SIGNAL(clicked()),this,SLOT(sendRTCTime()));
    connect(ui->getTime,SIGNAL(clicked()),this,SLOT(getRTCTime()));
    connect(ui->syncSysTime,SIGNAL(clicked()),this,SLOT(getSysTime()));

    // Connecting the button to fetch the last logged frames
    // into the console
    connect(ui->logUpdate,SIGNAL(clicked()),this,SLOT(update_c()));

    // Connecting the buttons used to connect to and configure
    // the serial port
    connect(ui->actionConnect, SIGNAL(clicked()), this, SLOT(openSerialPort()));
    connect(ui->actionDisconnect, SIGNAL(clicked()), this, SLOT(closeSerialPort()));
    connect(ui->actionConfigure, SIGNAL(clicked()), settings, SLOT(show()));
    connect(ui->cmdCustomSend,SIGNAL(clicked()),this,SLOT(sendCustomCommand()));

    connect(ui->applyLog, SIGNAL(clicked()),this,SLOT(applyLog()));


    logMap = new QSignalMapper(this);
    logMap->setMapping(ui->viewLog,logDirectory);
    connect(ui->viewLog,SIGNAL(clicked()),logMap,SLOT(map()));
    connect(logMap,SIGNAL(mapped(QString)),file_viewer,SLOT(show_dialog(QString)));

    // Connectring the button to change the log directory
    connect(ui->changeDirectory,SIGNAL(clicked()),this,SLOT(changeLogDirectory()));

    // Creating graphs instances by linking them to UI elements
    graph[0] = ui->graphXY;
    graph[1] = ui->graphXAxis;
    graph[2] = ui->graphYAxis;
    graph[3] = ui->graphZAxis;
    graph[4] = ui->gyroX;
    graph[5] = ui->gyroY;
    graph[6] = ui->gyroZ;
    graph[7] = ui->weightGraph;

    // The pen is used to draw a dot on XY graphs
    QPen pen;
    pen.setColor(QColor(229,115,115,255));
    pen.setWidth(10);
    pen.setCapStyle(Qt::RoundCap);
    // The line is used to draw classic graphs
    QPen line;
    line.setColor(QColor(25,118,210,255));
    line.setWidth(1);
    QPen line_red;
    line_red.setColor(QColor(210,25,118,255));
    line_red.setWidth(1);
    QPen line_green;
    line_green.setColor(QColor(118,210,25,255));
    line_green.setWidth(1);


    // Graph 1 to 6 stores the accelerometer and gyroscope
    // axis, and share similar settings.
    // Their label can be set directly in the next array
    QString label[16] = {
        "",
        "X","Y","Z",    // Accelerometer's three axis
        "X","Y","Z"     // Gyroscope's three axis
    };
    for(int i=1;i<8;i++) {
        // Only one curve on those graphs : axis/time
        graph[i]->addGraph();
        // The datas are stored in x[1] (time) and y[i] vectors
        graph[i]->graph(0)->setData(*x[1],*y[i]);
        graph[i]->graph(0)->setPen(line);
        // Setting the labels of each axis, as well
        // as the range
        graph[i]->xAxis->setLabel("t");
        graph[i]->yAxis->setLabel(label[i]);
        graph[i]->yAxis->setRange(-32000,32000);
        // The X Axis should display time (text)
        graph[i]->setLocale(QLocale(QLocale::English, QLocale::Canada));
        graph[i]->xAxis->setTickLabelType(QCPAxis::ltDateTime);
        graph[i]->xAxis->setDateTimeFormat("hh:mm:ss");
        graph[i]->xAxis->setDateTimeSpec(Qt::OffsetFromUTC);
        // Activating the zoom and drag interraction in vertical mode
        graph[i]->setInteraction(QCP::iRangeDrag, true);
        graph[i]->setInteraction(QCP::iRangeZoom, true);
        graph[i]->yAxis->axisRect()->setRangeDrag(Qt::Vertical);
        graph[i]->yAxis->axisRect()->setRangeZoom(Qt::Vertical);
    }
    graph[2]->graph(0)->setPen(line_green);
    graph[3]->graph(0)->setPen(line_red);
    graph[5]->graph(0)->setPen(line_green);
    graph[6]->graph(0)->setPen(line_red);

    graph[7]->yAxis->setRange(0,150);

    // Populating the XY graph
    // Only one curve on this graph : X axis /Y axis of accelerometer
    graph[0]->addGraph();
    // The datas are stored in x[0] and y[0] vectors
    graph[0]->graph(0)->setData(*x[0],*y[0]);
    // Draw a red dot
    graph[0]->graph(0)->setPen(pen);
    // Setting the labels of each axis, as well
    // as the range
    graph[0]->xAxis->setLabel("X");
    graph[0]->yAxis->setLabel("Y");
    graph[0]->xAxis->setRange(-10000,10000);
    graph[0]->yAxis->setRange(-10000,10000);
    // Activating the zoom and drag interraction in vertical and horizontal mode
    graph[0]->setInteraction(QCP::iRangeDrag, true);
    graph[0]->setInteraction(QCP::iRangeZoom, true);

    // For each graph, making the lines lighter in order to clean up the view
    for(int i=0;i<8;i++) {
        graph[i]->xAxis->setBasePen(QPen(QColor(195,195,195)));
        graph[i]->xAxis->setTickPen(QPen(QColor(195,195,195)));
        graph[i]->xAxis->setSubTickPen(QPen(QColor(195,195,195)));
        graph[i]->yAxis->setBasePen(QPen(QColor(195,195,195)));
        graph[i]->yAxis->setTickPen(QPen(QColor(195,195,195)));
        graph[i]->yAxis->setSubTickPen(QPen(QColor(195,195,195)));
    }

    // For every setting that should be saved, connecting the saveSession slot to
    // the state change signal
    connect(ui->appendDate,SIGNAL(stateChanged(int)),this,SLOT(saveSession()));
    connect(ui->logToFile,SIGNAL(stateChanged(int)),this,SLOT(saveSession()));
    connect(ui->fileName,SIGNAL(textChanged(QString)),this,SLOT(saveSession()));
    connect(ui->cmdValue,SIGNAL(valueChanged(int)),this,SLOT(saveSession()));
    connect(settings,SIGNAL(updated()),this,SLOT(saveSession()));

    // Addding Window's title
    setWindowTitle("Doctor's Orders Data Logger");



    // Creating a Timer for frame fetching
    serialFetch = new QTimer();
    serialFetch->setInterval(2);
    connect(serialFetch,SIGNAL(timeout()),protocole,SLOT(fetch()));

    // Creating a Timer for GUI update
    guiUpdate = new QTimer();
    guiUpdate->setInterval(50);
    connect(guiUpdate,SIGNAL(timeout()),this,SLOT(update()));

    // Connecting the serial port to the updateData slot
    connect(protocole,SIGNAL(updateData()),this,SLOT(updateData()));
}
Exemplo n.º 17
0
void CLevel::animate()
{
	for ( int i = 0; i < boardChanges.count(); i++ )
	{
		CBoardChange* change = (CBoardChange*)boardChanges[i];
		if ( change->counter > 0 )
		{
			change->counter--;
			if ( change->counter <= 0 )
			{
				// Put the old data back in.  DON'T DELETE THE CHANGE.
				// The client remembers board changes and if we delete the
				// change, the client won't get the new data.
				applyChange(change->prevData, change->x, change->y, change->width, change->height);
				change->tileData = change->prevData;
				change->modifyTime = getSysTime();
				change->counter = -1;
			}
		}
	}

	for ( int i = 0; i < items.count(); i++ )
	{
		CItem* item = (CItem*)items[i];
		item->counter--;
		if(item->counter == 0)
		{
			items.remove(i);
			delete item;
			i--;
		}
	}

	for ( int i = 0; i < baddies.count(); i++ )
	{
		CBaddy* baddy = (CBaddy*)baddies[i];
		if(baddy->mode == DIE || !players.count())
		{
			if(baddy->respawn)
			{
				// Drop items.
				if ( baddy->respawnCount == baddyRespawn && baddyDropItems == true )
					dropBaddyItem( baddy->x, baddy->y );

				baddy->respawnCount--;
				if(!baddy->respawnCount)
				{
					baddy->reset();
					CPacket baddyProps;
					baddyProps << (char)SBADDYPROPS << (char)baddy->id << baddy->getPropList();
					for(int ii = 0; ii < players.count(); ii ++)
					{
						CPlayer*player = (CPlayer*)players[ii];
						player->sendPacket(baddyProps);
					}
				}
			}
			if(!baddy->respawn && !players.count())
			{
				baddyIds.replace(baddy->id, NULL);
				baddies.remove(baddy);
				delete baddy;
				i--;
			}
		}
	}

	for(int i = 0; i < horses.count(); i++)
	{
		CHorse* horse = (CHorse*)horses[i];
		horse->counter--;
		if(horse->counter == 0)
		{
			CPacket horseData;
			horseData << (char)SDELHORSE << (char)(horse->x*2) <<
				(char)(horse->y*2);
			for (int ii = 0; ii < players.count(); ii++)
				((CPlayer*)players[ii])->sendPacket(horseData);
			delete horse;
			horses.remove(i);
			i--;
		}
	}
	saveCounter--;
	if(saveCounter <= 0)
	{
		saveNpcs();
		saveCounter = 300;
	}
}
Exemplo n.º 18
0
static void sample()
{
  AccSampleSlideBuf* slideBuf = (AccSampleSlideBuf*)(globalAttitudeSensor.accSlideBuf) ;

  SysTime startTime , endTime ;
  getSysTime(&startTime);
  
  // 对加速度计采样,并低通滤波+滑动平均滤波
  updateAccelerometer() ;    
  globalAttitudeSensor.accSamplesCount ++ ;
  int curPos = slideBuf->curPos ;
  int nextPos = curPos + 1 ;
  if (nextPos==SLIDE_BUF_LEN)
    nextPos = 0 ;
  
  int oldX = slideBuf->x[nextPos] ;
  int oldY = slideBuf->y[nextPos] ;
  int oldZ = slideBuf->z[nextPos] ;
  
  
  int ratio = LOW_PASS_RATIO ;  //低通差分公式的比率因子的倒数,
  int ratio2 = ratio - 1 ;  
  // 低通滤波
  slideBuf->x[nextPos] = ( slideBuf->x[curPos]*ratio2 + 1000*globalAttitudeSensor.ax ) / ratio ;
  slideBuf->y[nextPos] = ( slideBuf->y[curPos]*ratio2 + 1000*globalAttitudeSensor.ay ) / ratio ;
  slideBuf->z[nextPos] = ( slideBuf->z[curPos]*ratio2 + 1000*globalAttitudeSensor.az ) / ratio ;
  slideBuf->curPos = nextPos ;
  
  // 更新各轴的sum和滑动平均值和跟随预测值
  int32_t deltaX = slideBuf->x[nextPos] - oldX ;
  int32_t deltaY = slideBuf->y[nextPos] - oldY ;
  int32_t deltaZ = slideBuf->z[nextPos] - oldZ ;
  slideBuf->sumX += deltaX ;
  slideBuf->sumY += deltaY ;
  slideBuf->sumZ += deltaZ ;  
  slideBuf->aveX = (slideBuf->sumX) / (SLIDE_BUF_LEN) ;
  slideBuf->aveY = (slideBuf->sumY) / (SLIDE_BUF_LEN) ;
  slideBuf->aveZ = (slideBuf->sumZ) / (SLIDE_BUF_LEN) ;
  slideBuf->followPredictX = slideBuf->aveX + deltaX ;
  slideBuf->followPredictY = slideBuf->aveY + deltaY ;
  slideBuf->followPredictZ = slideBuf->aveZ + deltaZ ;

  
  // 对陀螺仪采样
  updateGyroData();
  
  if ( ( globalAttitudeSensor.accSamplesCount % globalAttitudeSensor.M_sample_Period )==0 )   
  {
    
    float Ax, Ay, Az ;
    float Mx, My, Mz ;
    float  x,  y,  z ;
    
    updateMagnetometer();  

    // 磁场低通滤波
    float ratio = MagFilterRatio ;
    
    
    x = globalAttitudeSensor.filtered_mx - globalAttitudeSensor.mx ;
    y = globalAttitudeSensor.filtered_my - globalAttitudeSensor.my ;
    z = globalAttitudeSensor.filtered_mz - globalAttitudeSensor.mz ;
    float d = sqrt(x*x+y*y+z*z);
    if ( d < 0.04f*500 )
      ratio = 0.01f ;
    else if ( d < 0.08f*500 )
      ratio = 0.02f ;
    else if ( d < 0.2f*500 )
      ratio = 0.1f ;
    else 
      ratio = 0.25f ;
    
    
    globalAttitudeSensor.filtered_mx  =  globalAttitudeSensor.filtered_mx * (1.0f-ratio) + globalAttitudeSensor.mx * ratio ;
    globalAttitudeSensor.filtered_my  =  globalAttitudeSensor.filtered_my * (1.0f-ratio) + globalAttitudeSensor.my * ratio ;
    globalAttitudeSensor.filtered_mz  =  globalAttitudeSensor.filtered_mz * (1.0f-ratio) + globalAttitudeSensor.mz * ratio ;
    
    // 磁场水平分量(再滤波)

    Ax = getAccXStable(&globalAttitudeSensor) ;
    Ay = getAccYStable(&globalAttitudeSensor) ;
    Az = getAccZStable(&globalAttitudeSensor) ;
    Mx = globalAttitudeSensor.filtered_mx ;
    My = globalAttitudeSensor.filtered_my ;
    Mz = globalAttitudeSensor.filtered_mz ;
    
    x = Ay*Mz - My*Az ;
    y = Az*Mx - Mz*Ax ;
    z = Ax*My - Mx*Ay ;
    Mx = -x ;
    My = -y ;
    Mz = -z ;
    x = Ay*Mz - My*Az ;
    y = Az*Mx - Mz*Ax ;
    z = Ax*My - Mx*Ay ;
    float tmp = 1.0f / sqrt(x*x + y*y + z*z) ;
    x *= tmp ;
    y *= tmp ;
    z *= tmp ;
    
    ratio = 0.05 ;
    globalAttitudeSensor.filtered_Hmx = x*ratio + globalAttitudeSensor.filtered_Hmx*(1-ratio) ; 
    globalAttitudeSensor.filtered_Hmy = y*ratio + globalAttitudeSensor.filtered_Hmy*(1-ratio) ; 
    globalAttitudeSensor.filtered_Hmz = z*ratio + globalAttitudeSensor.filtered_Hmz*(1-ratio) ;
      
  }

  getSysTime(&endTime);
  sampleTime = getDeltaTime(&endTime,&startTime); 
}
Exemplo n.º 19
0
int procGetUnit(unitPtr uPtr,char *recvBuf,int recvLen,char *result,char bitpos,char *pRecvPtr) {
	char string[256];
	char error[1000];
	char buffer[MAXBUF];
	char *errPtr=error;
/* 	short t; */
	float erg;
	int ergI;
	char formatI[20];
	float floatV=0;
	char *inPtr;
	char *tPtr;
	/* hier die Typen fuer die Umrechnung in <type> Tag */
	int8_t charV;
	uint8_t ucharV;
	int16_t shortV;
	int16_t tmpS;
	uint16_t ushortV;
	uint16_t tmpUS;
	int32_t intV;
	int32_t tmpI;
	uint32_t tmpUI;
	uint32_t uintV;
	

	bzero(errPtr,sizeof(error));

	/* wir behandeln die verschiedenen <type> Eintraege */

	if (strstr(uPtr->type,"cycletime")==uPtr->type) { /* Schaltzeit */ 
		if (getCycleTime(recvBuf,recvLen,result))
				return(1);
		else 
			return(-1);
	}
	else if (strstr(uPtr->type,"systime")==uPtr->type) { /* Systemzeit */ 
		if (getSysTime(recvBuf,recvLen,result))
				return(1);
		else 
			return(-1);
	}
	else if (strstr(uPtr->type,"errstate")==uPtr->type) { /* Errrocode + Systemzeit */ 
		if (getErrState(uPtr->ePtr,recvBuf,recvLen,result))
				return(1);
		else 
			return(-1);
	}
	else if (strstr(uPtr->type,"enum")==uPtr->type) { /*enum*/
		if(bytes2Enum(uPtr->ePtr,recvBuf,&tPtr,recvLen)) {
			strcpy(result,tPtr);
			return(1);
		}
		else {
			sprintf(result,"Kein passendes Enum gefunden"); 
			return(-1);
		}
	}

				
		




	/* hier kommen die ganzen numerischen Typen */


	if (strstr(uPtr->type,"char")==uPtr->type) { /* Umrechnung in Char 1Byte */
		memcpy(&charV,recvBuf,1);	
		floatV=charV; /* impliziete Typumnwandlung nach float fuer unsere Arithmetic */
		sprintf(formatI,"%%02X %%s");
	}
	else if (strstr(uPtr->type,"uchar")==uPtr->type) { /* Umrechnung in Unsigned Char 1Byte */
		memcpy(&ucharV,recvBuf,1);	
		floatV=ucharV; /* impliziete Typumnwandlung nach float fuer unsere Arithmetic */
		sprintf(formatI,"%%02X %%s");
	}
	else if (strstr(uPtr->type,"short")==uPtr->type) { /* Umrechnung in Short 2Byte */
		memcpy(&tmpS,recvBuf,2);	
		/* je nach CPU Typ wird hier die Wandlung vorgenommen */
		shortV=__le16_to_cpu(tmpS);
		floatV=shortV; /* impliziete Typumnwandlung nach float fuer unsere Arithmetic */
		sprintf(formatI,"%%04X %%s");
	}
	else if (strstr(uPtr->type,"ushort")==uPtr->type) { /* Umrechnung in Short 2Byte */
		memcpy(&tmpUS,recvBuf,2);	
		/* je nach CPU Typ wird hier die Wandlung vorgenommen */
		ushortV=__le16_to_cpu(tmpUS);
		floatV=ushortV; /* impliziete Typumnwandlung nach float fuer unsere Arithmetic */
		sprintf(formatI,"%%04X %%s");
	}
	else if (strstr(uPtr->type,"int")==uPtr->type) { /* Umrechnung in Int 4Byte */
		memcpy(&tmpI,recvBuf,4);	
		/* je nach CPU Typ wird hier die Wandlung vorgenommen */
		intV=__le32_to_cpu(tmpI);
		floatV=intV; /* impliziete Typumnwandlung nach float fuer unsere Arithmetic */
		sprintf(formatI,"%%08X %%s");
	}
	else if (strstr(uPtr->type,"uint")==uPtr->type) { /* Umrechnung in Unsigned Int 4Byte */
		memcpy(&tmpUI,recvBuf,4);	
		/* je nach CPU Typ wird hier die Wandlung vorgenommen */
		uintV=__le32_to_cpu(tmpUI);
		floatV=uintV; /* impliziete Typumnwandlung nach float fuer unsere Arithmetic */
		sprintf(formatI,"%%08X %%s");
	}
	else if (uPtr->type) {
		bzero(string,sizeof(string));
		snprintf(string, sizeof(string),"Unbekannter Typ %s in Unit %s",uPtr->type,uPtr->name);
		logIT(LOG_ERR,string);
		return(-1);
	}
		

	/* etwas logging */
	int n;
	char *ptr;
	char res;
	ptr=recvBuf;
	bzero(buffer,sizeof(buffer));
	for(n=0;n<=9;n++) {/* Bytes 0..9 sind von Interesse */ 
		bzero(string,sizeof(string));
		unsigned char byte=*ptr++ & 255;
		snprintf(string, sizeof(string),"B%d:%02X ",n,byte);
		strcat(buffer,string);
		if (n >= MAXBUF-3)
			break;
	}
	if (uPtr->gCalc && *uPtr->gCalc) { /* <calc im XML und get darin definiert */
		snprintf(string, sizeof(string),"Typ: %s (in float: %f)",uPtr->type,floatV);
		logIT(LOG_INFO,string);
		inPtr=uPtr->gCalc;
		snprintf(string, sizeof(string),"(FLOAT) Exp:%s [%s]",inPtr,buffer);
		logIT(LOG_INFO,string);
		erg=execExpression(&inPtr,recvBuf,floatV,errPtr);
		if (*errPtr) {
			snprintf(string, sizeof(string),"Exec %s: %s",uPtr->gCalc,error);
			logIT(LOG_ERR,string);
			strcpy(result,string);
			return(-1);
		}
		sprintf(result,"%f %s",erg,uPtr->entity);
	}
	else if (uPtr->gICalc && *uPtr->gICalc) { /* <icalc im XML und get darin definiert */
		inPtr=uPtr->gICalc;
		snprintf(string, sizeof(string),"(INT) Exp:%s [BP:%d] [%s]",inPtr,bitpos,buffer);
		logIT(LOG_INFO,string);
		ergI=execIExpression(&inPtr,recvBuf,bitpos,pRecvPtr,errPtr);
		if (*errPtr) {
			snprintf(string, sizeof(string),"Exec %s: %s",uPtr->gCalc,error);
			logIT(LOG_ERR,string);
			strcpy(result,string);
			return(-1);
		}
		snprintf(string, sizeof(string),"Erg: (Hex max. 4Byte) %08x",ergI);
		logIT(LOG_INFO,string);
		res=ergI;
		if( uPtr->ePtr && bytes2Enum(uPtr->ePtr,&res,&tPtr,recvLen)) {
			strcpy(result,tPtr);
			return(1);
		}
		else {
			sprintf(result,formatI,ergI,uPtr->entity);
			return(1);
		}


		/* hier noch das durchsuchen der enums ggf durchfuehren */
	}
	return(1);
}
Exemplo n.º 20
0
uint32 CVanaTime::getVanaTime()
{
    return getSysTime() - 1009810800;
}
Exemplo n.º 21
0
void configureTimer(float modelBaseRate)
{int i = 0;
int setup;
   setup = getSysTime(modelBaseRate);
   i = registerTimer (modelBaseRate, model_step);
}
Exemplo n.º 22
0
uint32 CVanaTime::getVanaTime()
{
    return getSysTime() - VTIME_BASEDATE;
}