Beispiel #1
0
void Game::gameLoop() {
    const GameClock::timeFormat timeDelta = updateTimestamp();

    mainWindow.clear(defaultClearColour);

    gameObjectManager.updateAll(timeDelta);
	mainWindow.display();

	sf::Event currentEvent;
	if(mainWindow.pollEvent(currentEvent)) {

	    switch(currentEvent.type) {
        case sf::Event::Closed:
            gameState = EXITING;
            break;
        case sf::Event::GainedFocus:
            unpause();
            break;
        case sf::Event::LostFocus:
            pause();
            break;
        default:
            break;
	    }
	}
}
void
TrackWidget::setTrackDetails()
{
    ui->trackTitle->setText( m_track.title( lastfm::Track::Corrected ) );
    ui->artist->setText( m_track.artist( lastfm::Track::Corrected ).name() );

    if ( m_track.title( lastfm::Track::Corrected ) != m_track.title( lastfm::Track::Original )
         || m_track.title( lastfm::Track::Corrected ) != m_track.title( lastfm::Track::Original ) )
    {
         ui->asterisk->show();
         ui->asterisk->setToolTip( tr( "Auto-corrected from: %1" ).arg( m_track.toString( lastfm::Track::Original ) ) );
    }

    if ( m_timestampTimer ) m_timestampTimer->stop();

    if ( m_track.scrobbleStatus() == lastfm::Track::Cached && !m_nowPlaying )
        ui->timestamp->setText( tr( "Cached" ) );
    else if ( m_track.scrobbleStatus() == lastfm::Track::Error && !m_nowPlaying )
        ui->timestamp->setText( tr( "Error: %1" ).arg( m_track.scrobbleErrorText() ) );
    else
        updateTimestamp();

    ui->love->setChecked( m_track.isLoved() );

    setTrackTitleWidth();
}
Beispiel #3
0
void
Motor::setEncoderOffset(int offset) {
	TRACER_ENTER_SCOPE("Motor[%s]@%p::setEncoderOffset(%i)",id_.str(),this,offset);
	encoderOffset_ = offset;
	position_ = (2.0*M_PI) * (1.0/((float)encoderCountsPerRev_)) * (encoderValue_ - encoderOffset_);
	updateTimestamp();
}
void
FriendWidget::setDetails()
{
    ui->userDetails->setText( userString( m_user ) );
    ui->username->setText( Label::boldLinkStyle( Label::anchor( m_user.www().toString(), name() ), Qt::black ) );
    ui->lastTrack->setText( m_track.toString() );

    if ( m_listeningNow )
    {
        // show the
        m_movie->start();
        ui->equaliser->show();

        ui->trackFrame->setObjectName( "nowListening" );
        style()->polish( ui->trackFrame );

        if ( !m_track.extra( "playerName" ).isEmpty() )
            ui->timestamp->setText( tr( "Scrobbling now from %1" ).arg( m_track.extra( "playerName" ) ) );
        else
            ui->timestamp->setText( tr( "Scrobbling now" ) );

        if ( m_timestampTimer ) m_timestampTimer->stop();
    }
    else
    {
        m_movie->stop();
        ui->equaliser->hide();

        ui->trackFrame->setObjectName( "groupBox" );
        style()->polish( ui->trackFrame );

        updateTimestamp();
    }
}
void
TrackWidget::updateTimestamp()
{
    if ( !m_timestampTimer )
    {
        m_timestampTimer = new QTimer( this );
        m_timestampTimer->setSingleShot( true );
        connect( m_timestampTimer, SIGNAL(timeout()), SLOT(updateTimestamp()));
    }

    if ( m_nowPlaying )
    {
        if ( isVisible() )
            m_movie->start();
        ui->equaliser->show();

        ui->timestamp->setText( tr( "Now listening" ) );
        ui->timestamp->setToolTip( "" );
    }
    else
    {        
        m_movie->stop();
        ui->equaliser->hide();

        unicorn::Label::prettyTime( *ui->timestamp, m_track.timestamp(), m_timestampTimer );
    }
}
Beispiel #6
0
void
Motor::setPosition(float pos) {
	TRACER_ENTER_SCOPE("Motor[%s]@%p::setPosition(%f)",id_.str(),this,pos);
	position_ = pos;
	//encoderValue_ = position_ * encoderCountsPerRev_ / (2.0*M_PI) + encoderOffset_;
	updateTimestamp();
}
BOOL CMakeGifDoc::OnNewDocument() {
  if(!CDocument::OnNewDocument()) {
    return FALSE;
  }
  setDocName();
  updateTimestamp();
  return TRUE;
}
void CMakeGifDoc::closeGif() {
  if(hasGifFile()) {
    deallocateGif(m_gif);
    m_gif = NULL;
    setDocName();
    updateTimestamp();
  }
}
Beispiel #9
0
/*
 * The news utility prints news items stored in /var/news.  When invoked
 * without any arguments, news prints the name and timestamp of each
 * current item followed by its contents, most recent first.
 */
int
main(int argc, char *argv[])
{
	int ch, len;
	char *home, *nf;

	extern int optind;

	f_all = f_name = f_short = 0;

#ifdef __NetBSD__
	setprogname(argv[0]);
#endif

	while ((ch = getopt(argc, argv, "ans")) != -1) {
		switch(ch) {
		case 'a':
			f_all = 1;
			break;
		case 'n':
			f_name = 1;
			f_short = 0;
			break;
		case 's':
			f_short = 1;
			f_name = 0;
			break;
		case '?':
		default:
			usage();
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	if (*argv && (f_all || f_name || f_short))
		errx(EXIT_FAILURE, "Options are not allowed with file names.");
		/* NOTREACHED */

	if ((home = getenv("HOME")) == NULL)
		errx(EXIT_FAILURE, "Unable to find HOME variable.");
		/* NOTREACHED */

	len = strlen(home) + strlen(NEWS_TIME) + 2;
	if ((nf = malloc(len)) == NULL)
		errx(EXIT_FAILURE, "Unable to allocate memory.");
		/* NOTREACHED */

	if ((snprintf(nf, len, "%s/%s", home, NEWS_TIME)) == -1)
		errx(EXIT_FAILURE, "Unable to prepare path.");
		/* NOTREACHED */

	nf_time = updateTimestamp(nf);
	free(nf);

	return printFiles(argv);
}
Beispiel #10
0
void
Motor::setEncoderValue(int val,bool updatePosition) {
	TRACER_ENTER_SCOPE("Motor[%s]@%p::setEncoderValue(%i,%i)",id_.str(),this,val,updatePosition);
	encoderValue_ = val;
	if (updatePosition) {
		position_ = (2.0*M_PI) * (1.0/((float)encoderCountsPerRev_)) * (encoderValue_ - encoderOffset_);
	}
	updateTimestamp();
}
Beispiel #11
0
void GamePlay::setCurrentUser()//gets the currently selected user from an index
{
    if(userTimestamp.size()>0)
    {
        double i=getIndex();
        currentUser[1]=userPlayer[i];
        currentUser[2]=userLevel[i];
        updateTimestamp(currentUser[1]);
        currentUser[0]=userTimestamp[i];
    }
}
Beispiel #12
0
void GamePlay::updateCurrentUser(QString name)//used to save users and update there timestamps,levle etc
{
    if(userTimestamp.size()>0)
    {
        double i=getNameIndex(name);
        currentUser[1]=userPlayer[i];
        currentUser[2]=userLevel[i];
        updateTimestamp(currentUser[1]);
        currentUser[0]=userTimestamp[i];
    }
}
void
FriendWidget::updateTimestamp()
{
    if ( !m_timestampTimer )
    {
        m_timestampTimer = new QTimer( this );
        m_timestampTimer->setSingleShot( true );
        connect( m_timestampTimer, SIGNAL(timeout()), SLOT(updateTimestamp()));
    }

    unicorn::Label::prettyTime( *ui->timestamp, m_track.timestamp(), m_timestampTimer );
}
void CMakeGifDoc::loadGif(const String &fileName) {
  GifFileType *oldGif = m_gif;

  try {;
    m_gif = ::loadGif(ByteInputFile(fileName));
    setDocName(fileName);
    updateTimestamp();
    if(oldGif) {
      deallocateGif(oldGif);
    }
    setSaveTime(m_lastUpdate);
  } catch(Exception e) {
    m_gif = oldGif;
    throw;
  }
}
Beispiel #15
0
void
Motor::setTorque(float torque) {
	TRACER_ENTER_SCOPE("Motor[%s]@%p::setTorque(%f)",id_.str(),this,torque);
	torque_ = torque;

	const float TFmotor     = 1 / tauPerAmp_;    // Determine the motor TF  = 1/(tau per amp)
	const float TFamplifier =     dacCountsPerAmp_;    // Determine the amplifier TF = (DAC_per_amp)

	int DACVal = (int)(torque_ * TFmotor * TFamplifier);  //compute DAC value: DAC=[tau*(amp/torque)*(DACs/amp)]

	//Perform range checking and convert to short int
	//Note: saturateShort saturates at max value for short int.
	saturateShort(DACVal, &dacCommand_);
	TRACER_PRINT("Motor[%i]@%p::setDacCommand(%hi)",id_.str(),this,dacCommand_);

	updateTimestamp();
}
void
TrackWidget::setTrackDetails()
{
    ui->trackTitle->setText( m_track.title() );
    ui->artist->setText( m_track.artist().name() );

    if ( m_timestampTimer ) m_timestampTimer->stop();

    if ( m_track.scrobbleStatus() == lastfm::Track::Cached && !m_nowPlaying )
        ui->timestamp->setText( tr( "Cached" ) );
    else if ( m_track.scrobbleStatus() == lastfm::Track::Error && !m_nowPlaying )
        ui->timestamp->setText( tr( "Error: %1" ).arg( m_track.scrobbleErrorText() ) );
    else
        updateTimestamp();

    ui->love->setChecked( m_track.isLoved() );

    setTrackTitleWidth();
}
bool CMakeGifDoc::addImagesToGif() {
  const PixRectArray &prArray = getQuantizedPrArray();
  if(prArray.size() == 0) {
    return false;
  }
  if(!hasGifFile()) {
    const CSize size = prArray.getMaxSize();
    m_gif = allocateGifFile(size.cx, size.cy);
  }
  const SavedImageArray images(prArray, m_imageSettings.m_colorCount);
  for(size_t i = 0; i < images.size(); i++) {
    GifMakeSavedImage(m_gif, images[i]);
  }

  const SavedImage *image0 = images[0];
  const ColorMapObject *colorMap = image0->ImageDesc.ColorMap;
  m_gif->SColorMap = GifMakeMapObject(colorMap->ColorCount, colorMap->Colors);
  updateTimestamp();
  return true;
}
Beispiel #18
0
/*
 *	Return pointer to new FileEntry in a 2k allocated block to be free'd when no longer required.
 *	Only basic data is filled in. 
 */
struct fileEntry* 
makeFileEntry() 
{
    struct fileEntry *fe = (struct fileEntry*) calloc(2048, 1);

    updateTimestamp(0,0);
    fe->descTag.tagIdent = TAG_IDENT_FE;
    fe->descTag.descVersion = 2;
    fe->descTag.tagSerialNum = lvd->descTag.tagSerialNum;
    fe->icbTag.strategyType = 4;
    fe->icbTag.numEntries = 1;
    fe->icbTag.fileType = ICBTAG_FILE_TYPE_REGULAR;
    /* User has all permission; Group/Others Read/Exec */
    fe->permissions = FE_PERM_U_READ | FE_PERM_U_WRITE | FE_PERM_U_DELETE | FE_PERM_U_CHATTR | FE_PERM_U_EXEC |
	FE_PERM_G_READ | FE_PERM_G_EXEC | FE_PERM_O_READ | FE_PERM_O_EXEC;
    fe->fileLinkCount = 1;
    fe->accessTime = timeStamp;
    fe->modificationTime = timeStamp;
    fe->attrTime = timeStamp;
    fe->impIdent = entityWRUDF;
    fe->uniqueID = ((struct logicalVolHeaderDesc*)lvid->logicalVolContentsUse)->uniqueID++;
    return fe;
}
bool ItemManager::append(const QString& filePath)
{
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists())
    {
        return false;
    }

    ItemInfoType info;
    info.filePath            = fileInfo.canonicalFilePath();
    info.timestampOfCreated  = fileInfo.created();
    info.timestampOfModified = fileInfo.lastModified();
    info.timestampOfRead     = fileInfo.lastRead();

    updateTimestamp(info);

    beginInsertRows(QModelIndex(), m_itemList.count(), m_itemList.count());

    m_itemList.append(info);

    endInsertRows();

    return true;
}
 WebSession(const QString& id)
     : id(id)
 {
     updateTimestamp();
 }
Beispiel #21
0
void Joint::setVelocity(float vel) {
	TRACER_ENTER_SCOPE("Joint[%s]@%p::setVelocity(%f)",id_.str(),this,vel);
	velocity_ = vel;
	updateTimestamp();
}
Beispiel #22
0
void Joint::setPosition(float pos) {
	TRACER_ENTER_SCOPE("Joint[%s]@%p::setPosition(%f)",id_.str(),this,pos);
	position_ = pos;
	updateTimestamp();
}
/*
 * This will handle connection for each client
 * */
void *connection_handler(void *args)
{
	//Get the socket descriptor
	struct arg_struct *argStr = (struct arg_struct*) args; 
	int sock = argStr->socket;
	int index = argStr->index;
	free(argStr);
	int read_size;
	char *message , client_message[MESSAGE_SIZE];
	char name[CONTENT_SIZE],mgName[CONTENT_SIZE],content[CONTENT_SIZE],mytime[TIMESTAMP_SIZE];
	
	time_t ltime;
	struct tm *tm;

	/// @sleep befor read from socket in order to wait until first msg be a complete message
	sleep(1);
	//Receive a message from client
	while( (read_size = recv(sock , client_message , MESSAGE_SIZE , 0)) > 0 )
	{
		//Send the message back to client
		write(sock , client_message , strlen(client_message));

		/// read from client msg and fill struct

		readXML(client_message,name,  mgName , content ,  mytime);

		//debug
		// printf("$$$ name %s time is %s \n",name, mytime );

		 pthread_mutex_lock(&mutexArray[index]);
		 	strcpy(clients[index].name ,name);
		 	if( strcmp(mgName,"cpu") == 0 )
		 	{
		 		// printf("@@@@@@@C \n %s \t %s \n",clients[index].cpu , content );
		 		strcpy(clients[index].cpu ,content);
		 	}
		 	else if( strcmp(mgName,"mem") == 0 )
		 	{
		 		// printf("@@@@@@@M \n %s \t %s \n",clients[index].mem , content );
		 		strcpy(clients[index].mem ,content);
		 	}
		 	else if( strcmp(mgName,"fsw") == 0 )
		 	{
		 		// printf("@@@@@@@W \n %s \t %s \n",clients[index].fsw , content );
		 		strcpy(clients[index].fsw ,content);
		 		// printf("@@@@@@@ \n %s \t %s \n",clients[index].fsw , content );
		 	}
		 	else if( strcmp(mgName,"fsr") == 0 )
		 	{
		 		// printf("@@@@@@@R \n %s \t %s \n",clients[index].fsr , content );
				strcpy(clients[index].fsr ,content);
		 		// printf("@@@@@@@ \n %s \t %s \n",clients[index].fsr , content );
		 		
		 	}
		 	else{
		 		printf("bad requset :(\n");
		 	}
			
			ltime=time(NULL);
			tm=localtime(&ltime);
			
			sprintf(clients[index].midServerTime,"%d:%d:%d",tm->tm_hour,tm->tm_min,tm->tm_sec);
			
		 	updateTimestamp(mytime , index);

		 	// printf("@@@@@@@@@@@@@\n%s\n",clients[index].timestamp );
   		 pthread_mutex_unlock(&mutexArray[index]);

   		 //debug
   		 // printf("@@@@@@@@@@@@@\n%s\n",client_message );
   		 // printf("@@@@@@@@@@@@@@@@@@@@\n%s\nat %s\nCPU usage: %s%%\nMemory usage: %s%%\nFS write: %s B/sec\nFS read: %s B/sec\n===================\n",
		 			// clients[index].name,clients[index].timestamp,clients[index].cpu,
		 			// clients[index].mem,clients[index].fsw,clients[index].fsr);
   		 //end debug


   		 /// memset agian
   		 memset(client_message,0,sizeof(char) * MESSAGE_SIZE);
   		 memset(name,0,sizeof(char) * CONTENT_SIZE);
   		 memset(mgName,0,sizeof(char) * CONTENT_SIZE);
   	  	 memset(content,0,sizeof(char) * CONTENT_SIZE);
   	  	 memset(mytime,0,sizeof(char) * TIMESTAMP_SIZE);


	}
	
	if(read_size == 0)
	{
		puts("Client disconnected");
		fflush(stdout);
	}
	else if(read_size == -1)
	{
		perror("recv failed");
	}


		
	
	return 0;
}
void
TrackWidget::setNowPlaying( bool nowPlaying )
{
    m_nowPlaying = nowPlaying;
    updateTimestamp();
}
Beispiel #25
0
void Motor::setDacCommand(short int cmd) {
	TRACER_ENTER_SCOPE("Motor[%s]@%p::setDacCommand(%hi)",id_.str(),this,cmd);
	dacCommand_ = cmd;
	updateTimestamp();
}
Beispiel #26
0
void Motor::setGravitationalTorqueEstimate(float gte) {
	gravitationalTorqueEstimate_ = gte;
	updateTimestamp();
}
Beispiel #27
0
//============================================================================
int main(int argc, char *argv[]) {
#ifndef WIN32
	signal(SIGINT, exitProgram);
	signal(SIGTERM, exitProgram);
	signal(SIGHUP, exitProgram);
	signal(SIGKILL, exitProgram);
#endif

	timestamp = updateTimestamp();
	
	// Set Default values
	sendRate = 1.0;
	strcpy(missionId, "Mission 01");
	strcpy(platform, "Demo");
	latitude = (uint32_t)htonl(mapLatitude("44.64423"));
	longitude = (uint32_t)htonl(mapLongitude("-93.24013"));
	altitude = (uint16_t)htons(mapAltitude("333"));
	strcpy(address, "127.0.0.1");
	servPort = 9000;
	DEBUG = 0;
	
	printf("\nUDP Generator, Version 1.0.1\nKevan Ahlquist\nAll Rights Reserved\n\n");
	
	// read user options
	int option_index = 0;
	char optc;
	static struct option long_options[] =
		{
		 {"address", 		required_argument, 0, 'a'},
		 {"port", 	 		required_argument, 0, 'p'},
		 {"rate",  	 		required_argument, 0, 'r'},
		 {"mission-id", required_argument, 0, 'm'},
		 {"platform",   required_argument, 0, 'n'},
		 {"latitude",   required_argument, 0, 't'},
		 {"longitude",  required_argument, 0, 'g'},
		 {"altitude",   required_argument, 0, 'e'},
		 {"help", no_argument,       0, 'h'},
		 {"version", no_argument,       0, 'v'},
		 {0, 0, 0, 0}
		};
	while (( optc = getopt_long(argc, argv, "a:p:r:m:n:t:g:e:hv", long_options, &option_index)) != -1) {
		switch(optc) {
			case 'a':
				strncpy(address, optarg, 16);
				address[15] = '\0'; // Prevent buffer overrun
				printf("Address received: %s\n", address);
				break;
			case 'p':
				servPort = atol(optarg);
				printf("Port received: %d\n", servPort);
				break;
			case 'r':
				sendRate = atof(optarg);
				printf("Rate received: %f\n", sendRate);
				if (sendRate > 1000000) {
					printf("Values greater than 1,000,000 packets per second are not supported\n");
					exit(0);
				}
				break;
			case 'm':
				strncpy(missionId, optarg, 12);
				missionId[12] = '\0'; // Prevent buffer overrun
				if (strlen(optarg) > 12) printf("WARNING: Mission ID truncated to 12 characters\n");
				printf("Mission ID received: %s\n", missionId);
				break;
			case 'n':
				strncpy(platform, optarg, 12);
				platform[12] = '\0'; // Prevent buffer overrun
				if (strlen(optarg) > 12) printf("WARNING: Platform truncated to 12 characters\n");
				printf("Platform received: %s\n", platform);
				break;
			case 't':
				latitude = (uint32_t)htonl(mapLatitude(optarg));
				printf("Latitude received: %s\n", optarg);
				if (atof(optarg) < -90.0 || atof(optarg) > 90.0) {
					printf("ERROR: Latitude out of range (-90,90)\n");
					exit(0);
				}
				break;
			case 'g':
				longitude = (uint32_t)htonl(mapLongitude(optarg));
				printf("Longitude received: %s\n", optarg);
				if (atof(optarg) < -180.0 || atof(optarg) > 180.0) {
					printf("ERROR: Longitude out of range (-180,180)\n");
					exit(0);
				}
				break;
			case 'e':
				altitude = (uint16_t)htons(mapAltitude(optarg));
				printf("Altitude received: %s\n", optarg);
				if (atof(optarg) < -900 || atof(optarg) > 19000) {
					printf("ERROR: Altitude out of range(-900,19000)\n");
					exit(0);
				}
				break;
			case 'h':
				help();
				exit(0);
				break;
			case 'v':
				exit(0);
				break;
			default:
				printf("Usage: klvgen -a <address>:<port> -r <rate> -m<mission-id> -p <platform> -t <lat> -g <long> -e <elev>\n");
				printf("For help use option -h or --help\n");
				exit(0);
		}
	}
	
	if (udpInit() == -1) exit(-1);
	
	// TESTING ================================================================
	int i;
	if (DEBUG) {
		printf("Testing mapping functions===============\n");
		printf("map 0 from 0-10 to 0-100: %d\n", mapValue(0,0,10,0,100));
		printf("map 10 from 0-10 to 0-100: %d\n", mapValue(10,0,10,0,100));
		printf("map 5 from 0-10 to 0-100: %d\n", mapValue(5,0,10,0,100));
	}
	if (DEBUG) {
		printf("uasLdsKey:\n");
		for (i = 0; i < 16; ++i) {
			printf("%X", uasLdsKey[i]);
		}
		printf("\n");
#ifdef WIN32
		printf("Timestamp (truncated): %u\n", (unsigned int)timestamp);
#else
		printf("Timestamp: %llu\n", timestamp);
#endif
	}
	if (DEBUG) {
		printf("Testing makePacket, packetBuffer:\n");
		printf(" K  L  Value...\n");
		makePacket(packetBuffer);
		for (i = 0; i < 80; ++i) {
			printf("%2X ", packetBuffer[i]);
			if ((i == 15) || (i == 25) || (i == 39) || (i == 53) || (i == 59) || (i == 65) || (i == 69) || (i == 72)) {
				printf("\n");
			}
		}
		printf("\n");
		udpSendPacket((const char *)packetBuffer);
	}
	if (DEBUG) {
		printf("Testing htonll function:\n num: 0x 01 02 03 04 05 06 07 08\n");
		uint64_t number = 0x0102030405060708ULL;
		uint64_t num2 = htonll(number);
		printf("number: ");
		printf("%2X ", (char)(number & 0xFF));
		printf("%2X ", (char)((number & 0xFF00) >> 8));
		printf("%2X ", (char)((number & 0xFF0000) >> 16));
		printf("%2X ", (char)((number & 0xFF000000) >> 24));
		printf("%2X ", (char)((number & 0xFF00000000ULL) >> 32));
		printf("%2X ", (char)((number & 0xFF0000000000ULL) >> 40));
		printf("%2X ", (char)((number & 0xFF000000000000ULL) >> 48));
		printf("%2X ", (char)((number & 0xFF00000000000000ULL) >> 56));
		printf("\n");
		printf("num2: ");
		printf("%2X ", (char)(num2 & 0xFF));
		printf("%2X ", (char)((num2 & 0xFF00) >> 8));
		printf("%2X ", (char)((num2 & 0xFF0000) >> 16));
		printf("%2X ", (char)((num2 & 0xFF000000) >> 24));
		printf("%2X ", (char)((num2 & 0xFF00000000ULL) >> 32));
		printf("%2X ", (char)((num2 & 0xFF0000000000ULL) >> 40));
		printf("%2X ", (char)((num2 & 0xFF000000000000ULL) >> 48));
		printf("%2X ", (char)((num2 & 0xFF00000000000000ULL) >> 56));
		printf("\n");
	}
	// END TESTING==========================================================
	
	while (1) {
		timestamp = htonll(updateTimestamp());
		makePacket(packetBuffer);
		udpSendPacket((const char *)packetBuffer);
		if (DEBUG) {
			printf("\n K  L  Value...\n");
			for (i = 0; i < 80; ++i) {
				printf("%2X ", packetBuffer[i]);
				if ((i == 16) || (i == 26) || (i == 40) || (i == 54) || 
						(i == 60) || (i == 66) || (i == 70) || (i == 73)) {
					printf("\n");
				}
			}
		}
#ifdef WIN32
		Sleep((1 / sendRate) * 1000);
#else
		usleep((1 / sendRate) * 1000); // usleep is untested, may not compile
#endif
	}
}
Beispiel #28
0
int Boxoffice::processEvent(fsm::status_t status, 
                            std::stringstream* sstream) {
  fsm::event_t event = fsm::get_event_by_status_code(status);

  if (F_MSG_DEBUG) printf("bo: checking event with state %d, event %d and status %d\n", 
    state_, event, status);
  if ( fsm::check_event(state_, event, status) ) {

    // RECEIVED_HEARTBEAT_EVENT
    if ( event == fsm::received_heartbeat_event ) {
      // Synchronize the node's local time
      updateTimestamp(sstream);

      switch ( status ) {
        // STATUS_100
        // if the received status was simply 100, do nothing...
        case fsm::status_100: {
          stop_sync_timeout_received_ = false;
          break;
        }

        // STATUS_121
        // waiting for all nodes to reply, so increment node_reply_counter_
        // until all nodes replied, then manually change the status
        case fsm::status_121: {
          ++node_reply_counter_;

          if ( node_reply_counter_ == total_node_number_ ) {
            node_reply_counter_ = 0;
            status = fsm::status_122;
            event = fsm::get_event_by_status_code(status);
            if ( !check_event(state_, event, status) ) return 1;
          }

          break;
        }
        // STATUS_161
        // waiting for all nodes to reply, so increment node_reply_counter_
        // until all nodes replied, then manually change the status
        case fsm::status_161: {
          ++node_reply_counter_;

          if ( node_reply_counter_ == total_node_number_ ) {
            node_reply_counter_ = 0;
            status = fsm::status_162;
            event = fsm::get_event_by_status_code(status);
            if ( !check_event(state_, event, status) ) return 1;
          }

          break;
        }
        // STATUS_165
        // waiting for all nodes to reply, so increment node_reply_counter_
        // until all nodes replied, then manually change the status
        case fsm::status_165: {
          ++node_reply_counter_;

          if ( node_reply_counter_ == total_node_number_ ) {
            node_reply_counter_ = 0;
            status = fsm::status_166;
            event = fsm::get_event_by_status_code(status);
            if ( !check_event(state_, event, status) ) return 1;
          }

          break;
        }

        // STATUS_140
        // waiting for all nodes to reply, so increment node_reply_counter_
        // until all nodes replied, then manually change the status to 150
        case fsm::status_140: {
          ++node_reply_counter_;

          if ( node_reply_counter_ == total_node_number_ ) {
            node_reply_counter_ = -1;

            status = fsm::status_142;
            event = fsm::get_event_by_status_code(status);
            if ( !check_event(state_, event, status) ) return 1;
          }

          break;
        }
        // STATUS_141
        // waiting for all nodes to reply, so increment node_reply_counter_
        // until all nodes replied, then manually change the status
        case fsm::status_141: {
          ++node_reply_counter_;

          if ( node_reply_counter_ == total_node_number_ ) {
            node_reply_counter_ = -1;

            if (file_list_metadata_.size() > 0) {
              // have more metadata only files
              status = fsm::status_174;
            } else if (file_list_data_.size() > 1) {
              // have multiple files
              status = fsm::status_178;
            } else if (file_list_data_.size() > 0) {
              // have one file
              status = fsm::status_177;
            } else {
              // everything transmitted
              status = fsm::status_172;
            }
            event = fsm::get_event_by_status_code(status);
            if ( !check_event(state_, event, status) ) return 1;
          }

          break;
        }

        // STATUS_120 || STATUS_124 || STATUS_140
        case fsm::status_120:
        case fsm::status_124:
          {
            notified_dispatch_ = false;
            break;
          }
        // STATUS_132
        case fsm::status_132:
          {
            node_reply_counter_ = 0;
            break;
          }

        // STATUS_130
        // waiting for file metadata
        case fsm::status_130: {
          if ( state_ == fsm::promoting_new_file_metadata_state
                && !notified_dispatch_ ) {
            sstream->seekg(1, std::ios_base::cur);
            char box_hash_s[F_GENERIC_HASH_LEN];
            sstream->read(box_hash_s, F_GENERIC_HASH_LEN);
            unsigned char box_hash[F_GENERIC_HASH_LEN];
            std::memcpy(box_hash, box_hash_s, F_GENERIC_HASH_LEN);

            Hash* hash = new Hash(box_hash);
            Box* box = boxes[hash];
            File* new_file = new File(box->getBaseDir(), hash);
            *sstream >> *new_file;
            if (!file_metadata_written_) {
              new_file->storeMetadata();
              new_file->resize();
              file_metadata_written_ = true;
            }
            delete new_file;

            char* timing_offset_c = new char[8];
            sstream->read(timing_offset_c, 8);

            std::stringstream* message = new std::stringstream();
            *message << F_SIGTYPE_FSM  << " "
                     << fsm::status_130 << " ";
            message->write(timing_offset_c, 8);
            zmqpp::message z_msg;
            z_msg << message->str();
            z_bo_disp->send(z_msg);
            notified_dispatch_ = true;
          }

          break;
        }
        // STATUS_160
        // acknowledging new file metadata
        case fsm::status_160: {
          file_metadata_written_ = false;
          break;
        }
        // STATUS_170
        // receiving file metadata
        case fsm::status_170: {
          if (state_ == fsm::receiving_file_metadata_change_state) {
            sstream->seekg(1, std::ios_base::cur);
            char box_hash_s[F_GENERIC_HASH_LEN];
            sstream->read(box_hash_s, F_GENERIC_HASH_LEN);
            unsigned char box_hash[F_GENERIC_HASH_LEN];
            std::memcpy(box_hash, box_hash_s, F_GENERIC_HASH_LEN);

            Hash* hash = new Hash(box_hash);
            Box* box = boxes[hash];
            File* new_file = new File(box->getBaseDir(), hash);
            *sstream >> *new_file;

            if (!new_file->isToBeDeleted() && !file_metadata_written_) {
              if (new_file->exists()) {
                new_file->resize();
              } else {
                new_file->create();
              }
              new_file->storeMetadata();
              file_metadata_written_ = true;
            }
            delete new_file;

            status = fsm::status_173;
            file_metadata_written_ = false;
            event = fsm::get_event_by_status_code(status);
            if ( !check_event(state_, event, status) ) return 1;
          }

          break;
        }
        // STATUS_174
        // receiving file metadata with additional files to come
        case fsm::status_174: {
          if (state_ == fsm::receiving_file_metadata_change_with_more_state) {
            sstream->seekg(1, std::ios_base::cur);
            char box_hash_s[F_GENERIC_HASH_LEN];
            sstream->read(box_hash_s, F_GENERIC_HASH_LEN);
            unsigned char box_hash[F_GENERIC_HASH_LEN];
            std::memcpy(box_hash, box_hash_s, F_GENERIC_HASH_LEN);

            Hash* hash = new Hash(box_hash);
            Box* box = boxes[hash];
            File* new_file = new File(box->getBaseDir(), hash);
            *sstream >> *new_file;

            if (!new_file->isToBeDeleted() && !file_metadata_written_) {
              if (new_file->exists()) {
                new_file->resize();
              } else {
                new_file->create();
              }
              new_file->storeMetadata();
              // \TODO in status_174 the sender sends the metadata
              //       of all files without changing the status, this 
              //       isn't handled yet
              file_metadata_written_ = true;
            }
            std::memcpy(current_box_, box_hash, F_GENERIC_HASH_LEN);
            std::stringstream cf;
            cf << *new_file;
            current_file_ << cf.str().substr(32);
            delete new_file;
            notified_dispatch_ = false;

            status = fsm::status_173;
            event = fsm::get_event_by_status_code(status);
            if ( !check_event(state_, event, status) ) return 1;
          }

          break;
        }