Exemplo n.º 1
0
/**
 * Read a number of bytes from the interface.
 *
 * @param data Pointer to the data byte array to write the bytes to
 * @param maxLength The maximum number of bytes to write
 **/
void SerialLink::readBytes()
{
    if (!validateConnection())
        return;

    if (mode_port)  // ESC32 special data read mode
        return readEsc32Tele();

    const qint64 maxLength = 2048;
    char data[maxLength];
    qint64 numBytes = 0, rBytes = 0;

    dataMutex.lock();
    while ((numBytes = port->bytesAvailable())) {
        /* Read as much data in buffer as possible without overflow */
        rBytes = numBytes;
        if(maxLength < rBytes) rBytes = maxLength;

        if (port->read(data, rBytes) == -1) { // -1 result means error
            emit portError();
            if (!m_linkLossExpected)
                emit communicationError(this->getName(), tr("Could not read data - link %1 is disconnected!").arg(this->getName()));
            return;
        }

        QByteArray b(data, rBytes);
        emit bytesReceived(this, b);
        bitsReceivedTotal += rBytes * 8;

    }
    dataMutex.unlock();
}
Exemplo n.º 2
0
void MessageQueue::readData() {
	bool gotmessage = false, gotsnapshot = false;
	int read, totalread=0;
	do {
		// Read available data
		read = _socket->read(_recvbuffer+_recvcount, MAX_BUF_LEN-_recvcount);
		if(read<0) {
			// Error!
			emit socketError(_socket->errorString());
			return;
		}
		_recvcount += read;

		// Extract all complete messages
		int len;
		while(2 < _recvcount && (len=Message::sniffLength(_recvbuffer)) <= _recvcount) {
			// Whole message received!
			Message *msg = Message::deserialize((const uchar*)_recvbuffer);
			if(!msg) {
				emit badData(len, _recvbuffer[2]);
			} else {
				if(msg->type() == MSG_STREAMPOS) {
					// Special handling for Stream Position message
					emit expectingBytes(static_cast<StreamPos*>(msg)->bytes() + totalread);
					delete msg;
				} else if(_expectingSnapshot) {
					// A message preceded by SnapshotMode::SNAPSHOT goes into the snapshot queue
					_snapshot_recv.enqueue(MessagePtr(msg));
					_expectingSnapshot = false;
					gotsnapshot = true;
				} else {
					if(msg->type() == MSG_SNAPSHOT && static_cast<SnapshotMode*>(msg)->mode() == SnapshotMode::SNAPSHOT) {
						delete msg;
						_expectingSnapshot = true;
					} else {
						_recvqueue.enqueue(MessagePtr(msg));
						gotmessage = true;
					}
				}
			}
			if(len < _recvcount) {
				memmove(_recvbuffer, _recvbuffer+len, _recvcount-len);
			}
			_recvcount -= len;
		}
		totalread += read;
	} while(read>0);

	if(totalread)
		emit bytesReceived(totalread);
	if(gotmessage)
		emit messageAvailable();
	if(gotsnapshot)
		emit snapshotAvailable();
}
Exemplo n.º 3
0
double DownloadItem::remainingTime() const
{
    if (!downloading())
        return -1.0;

    double timeRemaining = ((double)(bytesTotal() - bytesReceived())) / currentSpeed();

    // When downloading the eta should never be 0
    if (timeRemaining == 0)
        timeRemaining = 1;

    return timeRemaining;
}
Exemplo n.º 4
0
void XbeeLink::readBytes()
{
	xbee_pkt *xbeePkt;
	xbeePkt = xbee_getpacketwait(this->m_xbeeCon);
	if(!(NULL==xbeePkt))
	{
		QByteArray data;
		for(unsigned int i=0;i<=xbeePkt->datalen;i++)
		{
			data.push_back(xbeePkt->data[i]);
		}
		qDebug() << data;
		emit bytesReceived(this,data);
	}
}
Exemplo n.º 5
0
double DownloadItem::remainingTime() const {
    if (m_finishedDownloading)
        return -1.0;

    double speed = currentSpeed();
    double timeRemaining = 0.0;
    if (speed > 0.0)
        timeRemaining = ((double)(bytesTotal() - bytesReceived())) / speed;

    // When downloading the eta should never be 0
    if (timeRemaining == 0)
        timeRemaining = 1;

    return timeRemaining;
}
Exemplo n.º 6
0
void XbeeLink::readBytes()
{
	xbee_pkt *xbeePkt;
	xbeePkt = xbee_getpacketwait(this->m_xbeeCon);
	if(!(NULL==xbeePkt))
	{
		QByteArray data;
		for(unsigned int i=0;i<=xbeePkt->datalen;i++)
		{
			data.push_back(xbeePkt->data[i]);
        }

		_logInputDataRate(data.length(), QDateTime::currentMSecsSinceEpoch());
		emit bytesReceived(this, data);
	}
}
Exemplo n.º 7
0
void
Connection::socketDisconnected()
{
    tDebug() << "SOCKET DISCONNECTED" << this->name() << id()
             << "shutdown will happen after incoming queue empties."
             << "bytesavail:" << m_sock->bytesAvailable()
             << "bytesRecvd" << bytesReceived();

    m_peer_disconnected = true;
    emit socketClosed();

    if( m_msgprocessor_in.length() == 0 && m_sock->bytesAvailable() == 0 )
    {
        handleIncomingQueueEmpty();
        actualShutdown();
    }
}
Exemplo n.º 8
0
void
BaseShadow::logRequeueEvent( const char* reason )
{
	struct rusage run_remote_rusage;
	memset( &run_remote_rusage, 0, sizeof(struct rusage) );

	run_remote_rusage = getRUsage();

	int exit_reason = getExitReason();

	JobEvictedEvent event;

	event.terminate_and_requeued = true;

	if( exitedBySignal() ) {
		event.normal = false;
		event.signal_number = exitSignal();
	} else {
		event.normal = true;
		event.return_value = exitCode();
	}
			
	if( exit_reason == JOB_COREDUMPED ) {
		event.setCoreFile( core_file_name );
	}

	if( reason ) {
		event.setReason( reason );
	}

		// TODO: fill in local rusage
		// event.run_local_rusage = r;
	event.run_remote_rusage = run_remote_rusage;

		/* we want to log the events from the perspective 
		   of the user job, so if the shadow *sent* the 
		   bytes, then that means the user job *received* 
		   the bytes */
	event.recvd_bytes = bytesSent();
	event.sent_bytes = bytesReceived();
	
	if (!uLog.writeEvent (&event,jobAd)) {
		dprintf( D_ALWAYS, "Unable to log ULOG_JOB_EVICTED "
				 "(and requeued) event\n" );
	}
}
void WindowsPlatformIntegration::updateTaskbarButtons()
{
	const QList<Transfer*> transfers(TransfersManager::getInstance()->getTransfers());
	qint64 bytesTotal(0);
	qint64 bytesReceived(0);
	bool hasActiveTransfers(false);

	for (int i = 0; i < transfers.count(); ++i)
	{
		if (transfers[i]->getState() == Transfer::RunningState && transfers[i]->getBytesTotal() > 0)
		{
			hasActiveTransfers = true;
			bytesTotal += transfers[i]->getBytesTotal();
			bytesReceived += transfers[i]->getBytesReceived();
		}
	}

	const QList<MainWindow*> windows(Application::getInstance()->getWindows());

	for (int i = 0; i < windows.count(); ++i)
	{
		MainWindow *window(windows.at(i));

		if (hasActiveTransfers)
		{
			if (!m_taskbarButtons.contains(window))
			{
				m_taskbarButtons[window] = new QWinTaskbarButton(window);
				m_taskbarButtons[window]->setWindow(window->windowHandle());
				m_taskbarButtons[window]->progress()->show();
			}

			m_taskbarButtons[window]->progress()->setValue((bytesReceived > 0) ? qFloor((static_cast<qreal>(bytesReceived) / bytesTotal) * 100) : 0);
		}
		else if (m_taskbarButtons.contains(window))
		{
			m_taskbarButtons[window]->progress()->reset();
			m_taskbarButtons[window]->progress()->hide();
			m_taskbarButtons[window]->deleteLater();
			m_taskbarButtons.remove(window);
		}
	}
}
Exemplo n.º 10
0
void XbeeLink::readBytes()
{
	xbee_pkt *xbeePkt;
	xbeePkt = xbee_getpacketwait(this->m_xbeeCon);
	if(!(NULL==xbeePkt))
	{
		QByteArray data;
		for(unsigned int i=0;i<=xbeePkt->datalen;i++)
		{
			data.push_back(xbeePkt->data[i]);
        }

        emit bytesReceived(this, data);

        // Log the amount and time received for future data rate calculations.
        QMutexLocker dataRateLocker(&dataRateMutex);
        logDataRateToBuffer(inDataWriteAmounts, inDataWriteTimes, &inDataIndex, data.length(), QDateTime::currentMSecsSinceEpoch());
	}
}
Exemplo n.º 11
0
void
BaseShadow::logEvictEvent( int exitReason )
{
	struct rusage run_remote_rusage;
	memset( &run_remote_rusage, 0, sizeof(struct rusage) );

	run_remote_rusage = getRUsage();

	switch( exitReason ) {
	case JOB_CKPTED:
	case JOB_NOT_CKPTED:
	case JOB_KILLED:
		break;
	default:
		dprintf( D_ALWAYS, 
				 "logEvictEvent with unknown reason (%d), not logging.\n",
				 exitReason ); 
		return;
	}

	JobEvictedEvent event;
	event.checkpointed = (exitReason == JOB_CKPTED);
	
		// TODO: fill in local rusage
		// event.run_local_rusage = ???
			
		// remote rusage
	event.run_remote_rusage = run_remote_rusage;
	
	set_usageAd(jobAd, &event.pusageAd);

		/*
		  we want to log the events from the perspective of the user
		  job, so if the shadow *sent* the bytes, then that means the
		  user job *received* the bytes
		*/
	event.recvd_bytes = bytesSent();
	event.sent_bytes = bytesReceived();
	
	if (!uLog.writeEvent (&event,jobAd)) {
		dprintf (D_ALWAYS, "Unable to log ULOG_JOB_EVICTED event\n");
	}
}
Exemplo n.º 12
0
void Server::processEventQueue() {
    runExecutables();
    time_t now = time(nullptr);
    if (now < _nextDeadConnectionCheck) return;
    std::list<Connection*> toRemove;
    for (auto it = _connections.cbegin(); it != _connections.cend(); ++it) {
        time_t numSecondsSinceConnection = now - it->second;
        auto connection = it->first;
        if (connection->bytesReceived() == 0
            && numSecondsSinceConnection >= _lameConnectionTimeoutSeconds) {
            LS_INFO(_logger, formatAddress(connection->getRemoteAddress())
                    << " : Killing lame connection - no bytes received after "
                             << numSecondsSinceConnection << "s");
            toRemove.push_back(connection);
        }
    }
    for (auto it = toRemove.begin(); it != toRemove.end(); ++it) {
        delete *it;
    }
}
// Attempts to read at most 'bytes' bytes from the socket.
qint64 PeerWireClient::readFromSocket(qint64 bytes)
{
    char buffer[1024];
    qint64 totalRead = 0;
    do {
        qint64 bytesRead = socket.read(buffer, qMin<qint64>(sizeof(buffer), bytes - totalRead));
        if (bytesRead <= 0)
            break;
        qint64 oldSize = incomingBuffer.size();
        incomingBuffer.resize(oldSize + bytesRead);
        memcpy(incomingBuffer.data() + oldSize, buffer, bytesRead);

        totalRead += bytesRead;
    } while (totalRead < bytes);

    if (totalRead > 0) {
        downloadSpeedData[0] += totalRead;
        emit bytesReceived(totalRead);
        processIncomingData();
    }
    return totalRead;
}
Exemplo n.º 14
0
void Server::processEventQueue() {
    for (;;) {
        std::shared_ptr<Runnable> runnable = popNextRunnable();
        if (!runnable) break;
        runnable->run();
    }
    time_t now = time(NULL);
    if (now >= _nextDeadConnectionCheck) {
        std::list<Connection*> toRemove;
        for (auto it = _connections.cbegin(); it != _connections.cend(); ++it) {
            time_t numSecondsSinceConnection = now - it->second;
            auto connection = it->first;
            if (connection->bytesReceived() == 0 && numSecondsSinceConnection >= _lameConnectionTimeoutSeconds) {
                LS_INFO(_logger, formatAddress(connection->getRemoteAddress())
                        << " : Killing lame connection - no bytes received after " << numSecondsSinceConnection << "s");
                toRemove.push_back(connection);
            }
        }
        for (auto it = toRemove.begin(); it != toRemove.end(); ++it) {
            delete *it;
        }
    }
}
Exemplo n.º 15
0
bool
BaseShadow::updateJobInQueue( update_t type )
{
		// insert the bytes sent/recv'ed by this job into our job ad.
		// we want this from the perspective of the job, so it's
		// backwards from the perspective of the shadow.  if this
		// value hasn't changed, it won't show up as dirty and we
		// won't actually connect to the job queue for it.  we do this
		// here since we want it for all kinds of updates...
	MyString buf;
	buf.formatstr( "%s = %f", ATTR_BYTES_SENT, (prev_run_bytes_sent +
											  bytesReceived()) );
	jobAd->Insert( buf.Value() );
	buf.formatstr( "%s = %f", ATTR_BYTES_RECVD, (prev_run_bytes_recvd +
											   bytesSent()) );
	jobAd->Insert( buf.Value() );

	ASSERT( job_updater );

		// Now that the ad is current, just let our QmgrJobUpdater
		// object take care of the rest...
	return job_updater->updateJob( type );
}
Exemplo n.º 16
0
std::string Server::getStatsDocument() const {
    std::ostringstream doc;
    doc << "clear();" << std::endl;
    for (auto it = _connections.begin(); it != _connections.end(); ++it) {
        doc << "connection({";
        auto connection = it->first;
        jsonKeyPairToStream(doc,
                "since", EpochTimeAsLocal(it->second),
                "fd", connection->getFd(),
                "id", reinterpret_cast<uint64_t>(connection),
                "uri", connection->getRequestUri(),
                "addr", formatAddress(connection->getRemoteAddress()),
                "user", connection->credentials() ?
                        connection->credentials()->username : "******",
                "input", connection->inputBufferSize(),
                "read", connection->bytesReceived(),
                "output", connection->outputBufferSize(),
                "written", connection->bytesSent()
        );
        doc << "});" << std::endl;
    }
    return doc.str();
}
Exemplo n.º 17
0
void
Connection::socketDisconnected()
{
    Q_D( Connection );

    qint64 bytesAvailable = 0;
    if ( !d->sock.isNull() )
    {
        bytesAvailable = d->sock->bytesAvailable();
    }
    tDebug( LOGVERBOSE ) << "SOCKET DISCONNECTED" << this->name() << id()
                         << "shutdown will happen after incoming queue empties."
                         << "bytesavail:" << bytesAvailable
                         << "bytesRecvd" << bytesReceived();

    d->peer_disconnected = true;
    emit socketClosed();

    if ( d->msgprocessor_in.length() == 0 && bytesAvailable == 0 )
    {
        handleIncomingQueueEmpty();
        actualShutdown();
    }
}
Exemplo n.º 18
0
// kind defaults to US_NORMAL.
void
BaseShadow::logTerminateEvent( int exitReason, update_style_t kind )
{
	struct rusage run_remote_rusage;
	JobTerminatedEvent event;
	MyString corefile;

	memset( &run_remote_rusage, 0, sizeof(struct rusage) );

	switch( exitReason ) {
	case JOB_EXITED:
	case JOB_COREDUMPED:
		break;
	default:
		dprintf( D_ALWAYS, 
				 "UserLog logTerminateEvent with unknown reason (%d), aborting\n",
				 exitReason ); 
		return;
	}

	if (kind == US_TERMINATE_PENDING) {

		int exited_by_signal = FALSE;
		int exit_signal = 0;
		int exit_code = 0;

		getJobAdExitedBySignal(jobAd, exited_by_signal);
		if (exited_by_signal == TRUE) {
			getJobAdExitSignal(jobAd, exit_signal);
			event.normal = false;
			event.signalNumber = exit_signal;
		} else {
			getJobAdExitCode(jobAd, exit_code);
			event.normal = true;
			event.returnValue = exit_code;
		}

		/* grab usage information out of job ad */
		double real_value;
		if( jobAd->LookupFloat(ATTR_JOB_REMOTE_SYS_CPU, real_value) ) {
			run_remote_rusage.ru_stime.tv_sec = (time_t) real_value;
		}

		if( jobAd->LookupFloat(ATTR_JOB_REMOTE_USER_CPU, real_value) ) {
			run_remote_rusage.ru_utime.tv_sec = (time_t) real_value;
		}

		event.run_remote_rusage = run_remote_rusage;
		event.total_remote_rusage = run_remote_rusage;
	
		/*
		  we want to log the events from the perspective of the user
		  job, so if the shadow *sent* the bytes, then that means the
		  user job *received* the bytes
		*/
		jobAd->LookupFloat(ATTR_BYTES_SENT, event.recvd_bytes);
		jobAd->LookupFloat(ATTR_BYTES_RECVD, event.sent_bytes);

		event.total_recvd_bytes = event.recvd_bytes;
		event.total_sent_bytes = event.sent_bytes;
	
		if( exited_by_signal == TRUE ) {
			jobAd->LookupString(ATTR_JOB_CORE_FILENAME, corefile);
			event.setCoreFile( corefile.Value() );
		}

		if (!uLog.writeEvent (&event,jobAd)) {
			dprintf (D_ALWAYS,"Unable to log "
				 	"ULOG_JOB_TERMINATED event\n");
			EXCEPT("UserLog Unable to log ULOG_JOB_TERMINATED event");
		}

		return;
	}

	// the default kind == US_NORMAL path

	run_remote_rusage = getRUsage();
	
	if( exitedBySignal() ) {
		event.normal = false;
		event.signalNumber = exitSignal();
	} else {
		event.normal = true;
		event.returnValue = exitCode();
	}

		// TODO: fill in local/total rusage
		// event.run_local_rusage = r;
	event.run_remote_rusage = run_remote_rusage;
		// event.total_local_rusage = r;
	event.total_remote_rusage = run_remote_rusage;
	
		/*
		  we want to log the events from the perspective of the user
		  job, so if the shadow *sent* the bytes, then that means the
		  user job *received* the bytes
		*/
	event.recvd_bytes = bytesSent();
	event.sent_bytes = bytesReceived();

	event.total_recvd_bytes = prev_run_bytes_recvd + bytesSent();
	event.total_sent_bytes = prev_run_bytes_sent + bytesReceived();
	
	if( exitReason == JOB_COREDUMPED ) {
		event.setCoreFile( core_file_name );
	}

#if 1
	set_usageAd(jobAd, &event.pusageAd);
#else
	std::string resslist;
	if ( ! jobAd->LookupString("PartitionableResources", resslist))
		resslist = "Cpus, Disk, Memory";

	StringList reslist(resslist.c_str());
	if (reslist.number() > 0) {
		int64_t int64_value = 0;
		ClassAd * puAd = new ClassAd();

		reslist.rewind();
		char * resname = NULL;
		while ((resname = reslist.next()) != NULL) {
			MyString attr;
			int64_value = -1;
			attr.formatstr("%s", resname); // provisioned value
			if (jobAd->LookupInteger(attr.Value(), int64_value)) {
				puAd->Assign(resname, int64_value);
			} 
			// /*for debugging*/ else { puAd->Assign(resname, 42); }
			int64_value = -2;
			attr.formatstr("Request%s", resname);	// requested value
			if (jobAd->LookupInteger(attr.Value(), int64_value)) {
				puAd->Assign(attr.Value(), int64_value);
			}
			// /*for debugging*/ else { puAd->Assign(attr.Value(), 99); }
			int64_value = -3;
			attr.formatstr("%sUsage", resname); // usage value
			if (jobAd->LookupInteger(attr.Value(), int64_value)) {
				puAd->Assign(attr.Value(), int64_value);
			}
		}
		event.pusageAd = puAd;
	}
#endif
	
	if (!uLog.writeEvent (&event,jobAd)) {
		dprintf (D_ALWAYS,"Unable to log "
				 "ULOG_JOB_TERMINATED event\n");
		EXCEPT("UserLog Unable to log ULOG_JOB_TERMINATED event");
	}
}
Exemplo n.º 19
0
bool
BaseShadow::updateJobInQueue( update_t type )
{
		// insert the bytes sent/recv'ed by this job into our job ad.
		// we want this from the perspective of the job, so it's
		// backwards from the perspective of the shadow.  if this
		// value hasn't changed, it won't show up as dirty and we
		// won't actually connect to the job queue for it.  we do this
		// here since we want it for all kinds of updates...
	ClassAd ftAd;
	ftAd.Assign(ATTR_BYTES_SENT, (prev_run_bytes_sent + bytesReceived()) );

	ftAd.Assign(ATTR_BYTES_RECVD, (prev_run_bytes_recvd + bytesSent()) );

	FileTransferStatus upload_status = XFER_STATUS_UNKNOWN;
	FileTransferStatus download_status = XFER_STATUS_UNKNOWN;
	getFileTransferStatus(upload_status,download_status);
	switch(upload_status) {
	case XFER_STATUS_UNKNOWN:
		break;
	case XFER_STATUS_QUEUED:
		ftAd.Assign(ATTR_TRANSFER_QUEUED,true);
		ftAd.Assign(ATTR_TRANSFERRING_INPUT,true);
		break;
	case XFER_STATUS_ACTIVE:
		ftAd.Assign(ATTR_TRANSFER_QUEUED,false);
		ftAd.Assign(ATTR_TRANSFERRING_INPUT,true);
		break;
	case XFER_STATUS_DONE:
		ftAd.Assign(ATTR_TRANSFER_QUEUED,false);
		ftAd.Assign(ATTR_TRANSFERRING_INPUT,false);
		break;
	}
	switch(download_status) {
	case XFER_STATUS_UNKNOWN:
		break;
	case XFER_STATUS_QUEUED:
		ftAd.Assign(ATTR_TRANSFER_QUEUED,true);
		ftAd.Assign(ATTR_TRANSFERRING_OUTPUT,true);
		break;
	case XFER_STATUS_ACTIVE:
		ftAd.Assign(ATTR_TRANSFER_QUEUED,false);
		ftAd.Assign(ATTR_TRANSFERRING_OUTPUT,true);
		break;
	case XFER_STATUS_DONE:
		ftAd.Assign(ATTR_TRANSFER_QUEUED,false);
		ftAd.Assign(ATTR_TRANSFERRING_OUTPUT,false);
		break;
	}

	MergeClassAdsCleanly(jobAd,&ftAd);

	ASSERT( job_updater );

	if( type == U_PERIODIC ) {
			// Make an update happen soon.
		job_updater->resetUpdateTimer();
		return true;
	}

		// Now that the ad is current, just let our QmgrJobUpdater
		// object take care of the rest...
		//
		// Note that we force a non-durable update for X509 updates; if the
		// schedd crashes, we don't really care when the proxy was updated
		// on the worker node.
	return job_updater->updateJob( type, (type == U_PERIODIC) ? NONDURABLE : 0 );
}
Exemplo n.º 20
0
int main(void) {
#ifdef NEED_EVENT
	uint32_t DVSEventPointer;
	uint32_t DVSEventTimeLow;
	uint16_t DVSEvent;
	uint32_t timeStampMemory = 0, timeStampDelta = 0;
#endif

	int16_t angle = 0;
	uint32_t cnt =0;

	ExtraPinsInit();
	disablePeripherals();
	Chip_RIT_Init(LPC_RITIMER);
	RTC_TIME_T build = { .time = { BUILD_SEC_INT, BUILD_MIN_INT, BUILD_HOUR_INT, BUILD_DAY_INT, 0, 1, BUILD_MONTH_INT,
	BUILD_YEAR_INT } };
	buildTime = build;
	//This should be one of the first initializations routines to run.
	sensorsInit();
#ifdef NEED_EVENT
	DVS128ChipInit();
#endif
	DacInit();
	UARTInit(LPC_UART, BAUD_RATE_DEFAULT); /* baud rate setting */
	initMotors();
	PWMInit();
#if USE_IMU_DATA
	timerDelayMs(100);
	MPU9105Init();
#endif

#if USE_SDCARD
	SDCardInit();
#endif
#if USE_PUSHBOT
	MiniRobInit();
#endif

#ifdef TEST_RUN
	test();
	//This will not return
#endif

	LED1SetOn();
	// Start M0APP slave processor
	cr_start_m0(&__core_m0app_START__);
	LED1SetOff();

	LED0SetOn();
	LED0SetBlinking(ENABLE);
	UARTShowVersion();
	for (;;) {
		if (ledBlinking && toggleLed0) {
			LED0Toggle();
			toggleLed0 = 0;
		}
		// *****************************************************************************
		//    UARTIterate();
		// *****************************************************************************
		while (bytesReceived(&uart)) {  // incoming char available?
			UART0ParseNewChar(popByteFromReceptionBuffer(&uart));
		}

		// *****************************************************************************
		//    Deal with audio data
		// *****************************************************************************
		/*
		 * do the fft cross correlation and figure out the angle
		 * manipulate the proceeding direction of the pushbot
		 */
		// if buffer reaches a length of 1024
	/*	if(process_flag != -1){  // -1 for not ready, 0 for buffer0, 1 for buffer1
		//	SysTick->CTRL &= ~0x1;
			//xprintf("%d\n", process_flag);
			angle = itd();
			//SysTick->CTRL |= 0x1;
			if(++cnt>150){
				xprintf("angle = %d\n", angle);
				cnt = 0;
			}
		}*/


		// start doing math

#if USE_IMU_DATA
		updateIMUData();
#endif
#if USE_PUSHBOT
		refreshMiniRobSensors();
		if (motor0.updateRequired) {
			motor0.updateRequired = 0;
			updateMotorController(MOTOR0);
		}
		if (motor1.updateRequired) {
			motor1.updateRequired = 0;
			updateMotorController(MOTOR1);
		}
#endif
		/*
		// disable the data streaming through serial
		if (sensorRefreshRequested) {
			sensorRefreshRequested = 0;
			for (int i = 0; i < sensorsEnabledCounter; ++i) {
				if (enabledSensors[i]->triggered) {
					enabledSensors[i]->refresh();
					enabledSensors[i]->triggered = 0;
				}
			}
		}
		*/

#ifdef NEED_EVENT
		// *****************************************************************************
		//    processEventsIterate();
		// *****************************************************************************
		if (events.eventBufferWritePointer == events.eventBufferReadPointer) {		// more events in buffer to process?
			continue;
		}
		if (eDVSProcessingMode < EDVS_PROCESS_EVENTS) { //Not processing events
			if (freeSpaceForTranmission(&uart) < (TX_BUFFER_SIZE - 32) || !(eDVSProcessingMode & EDVS_STREAM_EVENTS)) {
#if LOW_POWER_MODE
				uart.txSleepingFlag = 1;
				__WFE();
#endif
				continue; //Wait until the buffer is empty.
			}
		}
		/*We are either processing events or streaming them.
		 * If streaming the buffer must be empty at this point
		 */

		events.ringBufferLock = true;
		events.eventBufferReadPointer = ((events.eventBufferReadPointer + 1) & DVS_EVENTBUFFER_MASK); // increase read pointer
		DVSEventPointer = events.eventBufferReadPointer;  // cache the value to be faster
		DVSEvent = events.eventBufferA[DVSEventPointer];		 // fetch event from buffer
		DVSEventTimeLow = events.eventBufferTimeLow[DVSEventPointer];	// fetch event from buffer
		events.ringBufferLock = false;
		if (eDVSProcessingMode & EDVS_STREAM_EVENTS) {
			if (freeSpaceForTranmission(&uart) > 6) {	// wait for TX to finish sending!
				pushByteToTransmission(&uart, (DVSEvent >> 8) | 0x80);      // 1st byte to send (Y-address)
				pushByteToTransmission(&uart, DVSEvent & 0xFF);                  // 2nd byte to send (X-address)
				if (eDVSDataFormat == EDVS_DATA_FORMAT_BIN_TSVB) {
					// Calculate delta...
					timeStampDelta = DVSEventTimeLow - timeStampMemory;
					timeStampMemory = DVSEventTimeLow;              // Save the current TS in delta
					// check how many bytes we need to send
					if (timeStampDelta < 0x7F) {
						// Only 7 TS bits need to be sent
						pushByteToTransmission(&uart, (timeStampDelta & 0x7F) | 0x80); // 3rd byte to send (7bit Delta TS, MSBit set to 1)
					} else if (timeStampDelta < 0x3FFF) {
						// Only 14 TS bits need to be sent
						pushByteToTransmission(&uart, (timeStampDelta >> 7) & 0x7F); // 3rd byte to send (upper 7bit Delta TS, MSBit set to 0)
						pushByteToTransmission(&uart, (timeStampDelta & 0x7F) | 0x80); // 4th byte to send (lower 7bit Delta TS, MSBit set to 1)
					} else if (timeStampDelta < 0x1FFFFF) {
						// Only 21 TS bits need to be sent
						pushByteToTransmission(&uart, (timeStampDelta >> 14) & 0x7F); // 3rd byte to send (upper 7bit Delta TS, MSBit set to 0)
						pushByteToTransmission(&uart, (timeStampDelta >> 7) & 0x7F); // 4th byte to send (middle 7bit Delta TS, MSBit set to 0)
						pushByteToTransmission(&uart, (timeStampDelta & 0x7F) | 0x80); // 5th byte to send (lower 7bit Delta TS, MSBit set to 1)
					} else {
Exemplo n.º 21
0
void
MpiResource::resourceExit( int reason, int status ) 
{
	dprintf( D_FULLDEBUG, "Inside MpiResource::resourceExit()\n" );

	RemoteResource::resourceExit( reason, status );

		// Also log a NodeTerminatedEvent to the ULog

	switch( reason ) {
	case JOB_COREDUMPED:
	case JOB_EXITED:
		{
			// Job exited on its own, normally or abnormally
			NodeTerminatedEvent event;
			event.node = node_num;
			if( exited_by_signal ) {
				event.normal = false;
				event.signalNumber = exit_value;
			} else {
				event.normal = true;
				event.returnValue = exit_value;
			}
			
			int had_core = 0;
			jobAd->LookupBool( ATTR_JOB_CORE_DUMPED, had_core );
			if( had_core ) {
				event.setCoreFile( shadow->getCoreName() );
			}

				// TODO: fill in local/total rusage
				// event.run_local_rusage = r;
			event.run_remote_rusage = remote_rusage;
				// event.total_local_rusage = r;
			event.total_remote_rusage = remote_rusage;
			
				/* we want to log the events from the perspective
				   of the user job, so if the shadow *sent* the
				   bytes, then that means the user job *received*
				   the bytes */
			event.recvd_bytes = bytesSent();
			event.sent_bytes = bytesReceived();
				// TODO: total sent and recvd
			event.total_recvd_bytes = bytesSent();
			event.total_sent_bytes = bytesReceived();
			if( !writeULogEvent(&event) ) {
				dprintf( D_ALWAYS,"Unable to log "
						 "ULOG_NODE_TERMINATED event\n" );
			}
		}
		break;	
	case JOB_CKPTED:
	case JOB_NOT_CKPTED:
			// XXX Todo: Do we want a Node evicted event?
		break;
	default:
		dprintf( D_ALWAYS, "Warning: Unknown exit_reason %d in "
				 "MpiResource::resourceExit()\n", reason );  
	}	

}
Exemplo n.º 22
0
void ConfigurablePage::showProgress()
{
	std::cerr << qPrintable(QString("").sprintf("%d%% %d KB/s", progress,
					((bytesReceived() / (time(NULL) - startTime))) / 1024
					).leftJustified(15, ' ')) << "\r";
}