Example #1
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Create timer to add 1 XP every second
    timer = new QTimer(this);
    timer->setInterval(1000);
    timer->start();

    xp = 0;
    level = 0;
    currentMaxXp = INITIAL_MAX_XP;
    questLength = INITIAL_QUEST_TIME;
    questTime = 0;
    questCount = 0;
    itemGenerator = new ItemGenerator();
    questGenerator = new QuestGenerator();
    currentQuest = questGenerator->getQuest(getQuestXP(INITIAL_QUEST_TIME),
                                           INITIAL_QUEST_TIME);

    ui->progressBar->setFormat("%v/%m XP");
    ui->progressBar->setMaximum(currentMaxXp);
    ui->questProgress->setMaximum(currentQuest->getLength());

    ui->lbl_level->setText((new QString("Level %1"))->arg(QString::number(level)));
    ui->questList->addItem("Selecting class...");

    connect(timer, SIGNAL(timeout()), this, SLOT(timerTick()));

    timerTick();
}
Example #2
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    trayIconMenu = new QMenu(this);
    restoreAction = new QAction(tr("Restore"), this);
    closeAction = new QAction(tr("Exit"), this);
    trayIconMenu->addAction(restoreAction);
    trayIconMenu->addAction(closeAction);
    trayIcon = new QSystemTrayIcon(QIcon(":/img/ckb-logo.png"), this);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->show();

    ui->tabWidget->addTab(noKbWidget = new QWidget(this), noKbMsg);

    connect(ui->actionExit, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()));
    connect(closeAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(show()));

    eventTimer = new QTimer(this);
    connect(eventTimer, SIGNAL(timeout()), this, SLOT(timerTick()));
    eventTimer->start(16);

    scanKeyboards();
}
Example #3
0
		/* Execute the next timer event */
		timerTick();
	}

	free(finish);
	free(current);
	free(sleepTime);
	free(remainingTime);
}
#else /* WIN32 */
void MasterTimer::run()
{
	/* This timer implementation requires 64bit support from compiler.
	   (Not 64bit processor architecture, though.) */
	LARGE_INTEGER frequency;
	LARGE_INTEGER start;
	LARGE_INTEGER lap;
	LONGLONG target;

	/* Calculate the target time that should be waited before each event */
	QueryPerformanceFrequency(&frequency);
	target = frequency.QuadPart / KFrequency;

	while (m_running == true)
	{
		/* Reset the timer and make the first check */
		QueryPerformanceCounter(&start);
		QueryPerformanceCounter(&lap);

		/* Loop here until $target ticks have passed */
		while ((lap.QuadPart - start.QuadPart) < target)
		{
			/* Relinquish this thread's time slot, but don't sleep
			   because that would skew the timer at least 30ms. */
			Sleep(0);

			/* Check how many ticks have passed */
			QueryPerformanceCounter(&lap);
		}

		/* Execute the next timer event */
		timerTick();
	}
}
Example #4
0
SimulationTimer::SimulationTimer(GUIManager& listener,
								hpreal minTime, hpreal maxTime,
								int ticksPerSimulation, hpreal tickTime):
								m_listener(listener),
								m_currentTime(minTime),
								m_minTime(minTime),
								m_maxTime(maxTime),
								m_deltaTick((maxTime - minTime)/(hpreal)ticksPerSimulation),
								m_startStopButton(new QPushButton("start")),
								m_tickTime(tickTime),
								m_timer(new QTimer(this)),
								m_timerIsRunning(false),
								m_timeSlider(new LabeledRealValuedSlider("Time", this)){

	QVBoxLayout* layout = new QVBoxLayout();
	layout->addWidget(m_timeSlider);
	layout->addWidget(m_startStopButton);
	setLayout(layout);

	connect(m_timer, SIGNAL(timeout()), this, SLOT(timerTick()));
	connect(m_timeSlider, SIGNAL(valueChanged(hpreal)), this, SLOT(changeTime(hpreal)));
	connect(m_startStopButton, SIGNAL(clicked()), this, SLOT(startStopTimer()));

	updateSlider();
}
Example #5
0
TitlePlayDialog::TitlePlayDialog(QWidget *parent, AudioPlayerBridge *apb, API *api, Song *song) :
    QDialog(parent),
    ui(new Ui::TitlePlayDialog)
{
    this->setAttribute(Qt::WA_QuitOnClose, false);
    this->setAttribute(Qt::WA_DeleteOnClose);
    posChanging = false;
    posTimer = new QTimer(this);
    posTimer->setInterval(200);
    posTimer->setSingleShot(false);
    connect(posTimer, SIGNAL(timeout()), this , SLOT(timerTick()));
    posTimer->start();
    this->apb = new AudioPlayerBridge(this, false);
    this->apb->setVolume(apb->getVolume());
    this->api = api;
    this->song = song;
    ui->setupUi(this);
    this->setWindowFlags(this->windowFlags() & ~(Qt::WindowFullscreenButtonHint));
    QRect geometry = QApplication::desktop()->screenGeometry();
    this->setGeometry((geometry.width() - this->width()) / 2, (geometry.height() - this->height()) / 2, this->width(), this->height());
    this->setFixedSize(this->size());
    this->setWindowTitle(QString::fromStdString(song->getSongName() + " - " + song->getArtistName()));
    ui->lblSong->setText(QString::fromStdString(song->getSongName() + " - " + song->getArtistName()));
    ui->sldVolume->setValue(this->apb->getVolume());
    ui->sldVolume->setStyle(new MyVolumeStyle);
    ui->sldPosition->setStyle(new MyVolumeStyle);
    connect(api, SIGNAL(streamKeyReady(StreamInformation*)), this, SLOT(gotSongInformation(StreamInformation*)));
    connect(this->apb, SIGNAL(startedPlaying()), this, SLOT(songStarted()));
    connect(this->apb, SIGNAL(songFinished()), this, SLOT(songFinished()));
    connect(api, SIGNAL(songError(int)), this, SLOT(songFailed(int)));
    play();
}
Example #6
0
CircuitsWidget::CircuitsWidget(QWidget *parent) : QWidget(parent) {
	connectingComponent = false;
	componentOnConnection = NULL;
	setMouseTracking(true);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerTick()));
}
Example #7
0
ImageCapture::ImageCapture(QWidget *parent) : QWidget(parent) {
    cvCaptureTimer = new QTimer(this);
    counter = 0;
    threshold = 0;
    mode = 0;

    // Connect signal to slot.
    connect(cvCaptureTimer, SIGNAL(timeout()), this, SLOT(timerTick()));
}
void SoundCore::update() {
	generateBarEvents();
	ERRCHECK(system->update());
	if(timer != oldtimer){
		timerTick();
		oldtimer = timer;
	}
	generateBarEvents();
}
Example #9
0
Chronos::Chronos(QObject *parent):QThread(parent)
{
    serial = new UnixSerialInterface();
    enabled = false;
    packetsMissed = 0;
    packetsReceived = 0;
    ChronosTimeoutLimit = 5;
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(timerTick()));
}
Example #10
0
VideoWidget::VideoWidget(QDeclarativeItem *parent) : QDeclarativeItem(parent)
{
	mediaLoaded = false;
	pix = new QImage(800,600,QImage::Format_RGB32);
	inst = libvlc_new (0, NULL);
	setFlag(QGraphicsItem::ItemHasNoContents,false);
	setFlag(QGraphicsItem::ItemIsFocusable,true);
	timer = new QTimer(this);
	connect(timer,SIGNAL(timeout()),this,SLOT(timerTick()));
	timer->start(20);
	return;
}
Example #11
0
MouseMux::MouseMux(QObject* parent) : QObject(parent) {
	pb = new QPushButton("Quit");
	pb->show();
	QObject::connect(pb, SIGNAL(clicked()),
				qApp, SLOT(quit()));

	timer = new QTimer(this);
	QObject::connect(timer, SIGNAL(timeout()),
				this, SLOT(timerTick()));
	timer->start(8);
	// Init the serial port we'll talk to the Arduino over.
	sp = new SerialPort();
	serial_enabled = sp->open();
}
Example #12
0
MainApp::MainApp(QWidget *parent) :
    QGLWidget(QGLFormat(QGL::DoubleBuffer | QGL::DepthBuffer), parent),
    m_good(true),
    m_camera{Camera(glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), CameraMode::CAMERA_Y_LOCK_VERT),
             Camera(glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), CameraMode::CAMERA_Y_LOCK_VERT)},
    m_keyFlags(0),
    m_ignoreNextMovement(false),
    m_mouseEnable(false),
    m_cameraSelect(0)
{
    this->setCursor(QCursor(Qt::CrossCursor));
    connect(&m_timer,SIGNAL(timeout()),this,SLOT(timerTick()));
    m_timer.start(TICK_RATE);
    m_time.start();
}
Example #13
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mainWindow = this;

    trayIconMenu = new QMenu(this);
    restoreAction = new QAction(tr("Restore"), this);
    closeAction = new QAction(tr("Quit ckb"), this);
    trayIconMenu->addAction(restoreAction);
    trayIconMenu->addAction(closeAction);
    trayIcon = new QSystemTrayIcon(QIcon(":/img/ckb-logo.png"), this);
    trayIcon->setContextMenu(trayIconMenu);
    if(!CkbSettings::get("Program/SuppressTrayIcon").toBool())
        trayIcon->show();

#ifdef Q_OS_MACX
    // Make a custom "Close" menu action for OSX, as the default one brings up the "still running" popup unnecessarily
    QMenuBar* menuBar = new QMenuBar(this);
    setMenuBar(menuBar);
    this->menuBar()->addMenu("ckb")->addAction(closeAction);
#else
    // On linux, add a handler for Ctrl+Q
    new QShortcut(QKeySequence("Ctrl+Q"), this, SLOT(quitApp()));
#endif

    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(quitApp()));
    connect(closeAction, SIGNAL(triggered()), this, SLOT(quitApp()));
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showWindow()));
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconClicked(QSystemTrayIcon::ActivationReason)));

    connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(cleanup()));

    eventTimer = new QTimer(this);
    eventTimer->setTimerType(Qt::PreciseTimer);
    connect(eventTimer, SIGNAL(timeout()), this, SLOT(timerTick()));
    eventTimer->start(1000 / 60);

    QCoreApplication::setOrganizationName("ckb");

    ui->tabWidget->addTab(settingsWidget = new SettingsWidget(this), configLabel);
    settingsWidget->setVersion("ckb " CKB_VERSION_STR);

    ckbGuiVersion = PARSE_CKB_VERSION(CKB_VERSION_STR);
    scanKeyboards();
}
Example #14
0
/*
 *	This function does the following:
 *		1. Loads OS Startup Code.
 *		2. Copies the instruction to be parsed as per the address specified by the IP register.
 *		3. Checks whether interrupt is disabled. If not th clock ticks.
 *		4. Begins the lexical analysis by getting the first token and passing it as arguement to executeOneInstruction.
 *		5. If step flag is enabled enters debug mode
 *		6. Finally checks if time slice allocated is over or not. If yes and mode is user mode ,and if interrupt is enabled then
 *			INT 0 code is run.
 */
void run(int is_timer_enabled) {
	if (is_timer_enabled) resetTimer();
	loadStartupCode();
	int instr;
	while (1) {
		YY_FLUSH_BUFFER;
		if (getInstruction(instruction) == -1) continue;	//gets the next instruction in variable instruction		
		instr = yylex();
		if (mode == USER_MODE && is_timer_enabled) timerTick();
		executeOneInstruction(instr);
		if ((watch_count > 0 && checkWatch() == 1) || step_flag == 1) debugInterface();
		if (isTimerCountZero() && is_timer_enabled && mode == USER_MODE) {
			resetTimer();
			invokeHardwareInterrupt(0);
			if (step_flag == 1) printf("TIMER Interrupt\n");
		}
	}
}
Example #15
0
int Chronos::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QThread::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: deviceAvailible(); break;
        case 1: deviceUnAvailible(); break;
        case 2: accDataAvailible((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
        case 3: logEvent((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 4: timerTick(); break;
        default: ;
        }
        _id -= 5;
    }
    return _id;
}
Example #16
0
void startTimer(int duration) {
  if(s_timerActive) {
    // Nasty hack to tidy up :)
    if(duration == s_duration1 && s_selectedDuration >=30)
      s_selectedDuration -= 15;
    if(duration == s_duration3 && s_selectedDuration <120)
      s_selectedDuration += 15;
    return;
  }
  
  s_timerActive = true;
  
  app_timer_cancel(s_timer);
  s_currentTimer = -1;
  s_selectedDuration = duration;
  window_set_background_color(s_window, GColorGreen);
  setHiddenRestarts(true);
  timerTick(NULL);
}
Example #17
0
void AudioZrtpSession::run()
{
    // Set recording sampling rate
    call_.setRecordingSmplRate(getCodecSampleRate());
    DEBUG("Entering mainloop for call %s", call_.getCallId().c_str());

    uint32 timeout = 0;

    while (isActive()) {
        if (timeout < 1000)
            timeout = getSchedulingTimeout();

        // Send session
        if (DtmfPending())
            sendDtmfEvent();
        else
            sendMicData();

        controlReceptionService();
        controlTransmissionService();
        uint32 maxWait = timeval2microtimeout(getRTCPCheckInterval());
        // make sure the scheduling timeout is
        // <= the check interval for RTCP
        // packets
        timeout = (timeout > maxWait) ? maxWait : timeout;

        if (timeout < 1000) {   // !(timeout/1000)
            // dispatchDataPacket();
            timerTick();
        } else {
            if (isPendingData(timeout / 1000)) {

                if (isActive())
                    takeInDataPacket();
            }
            timeout = 0;
        }
    }

    DEBUG("Left main loop for call %s", call_.getCallId().c_str());
}
FFMPEGVideoWidget::FFMPEGVideoWidget(QWidget *parent) :
    QGLWidget(QGLFormat(QGL::SampleBuffers), parent),
    first_frame(true)
{
    setFixedSize(320, 240);
    setAutoFillBackground(false);
    //Set up the demuxer
    m_demuxer = new Demuxer(QString(PIPENAME));
    m_ffmpeg = new FFMPEGWrapper(39082, m_demuxer);
    m_ffmpeg_thread = new QThread(this);
    m_ffmpeg->moveToThread(m_ffmpeg_thread);
    connect(m_ffmpeg_thread, SIGNAL(started()), m_ffmpeg, SLOT(demux()));
    connect(m_ffmpeg, SIGNAL(finished()), m_ffmpeg_thread, SLOT(quit()));

    connect(m_demuxer, SIGNAL(newImage(QImage *)), this, SLOT(addImage(QImage *)));

    //Set up the timer
    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(timerTick()));

}
Example #19
0
MainWindow::MainWindow(vector<TimeOption> timeOptions_, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    timer(this),
    finishedSource(":/sounds/alarm.raw"),
    timeOptions(timeOptions_)
{

    ui->setupUi(this);

    for (vector<TimeOption>::iterator it = timeOptions.begin(); it!= timeOptions.end(); ++ it) {
        TimeOption o = *it;
        ui->timeSelection->addItem(QString::fromStdString(o.name));
    }

    finishedSource.open(QIODevice::ReadOnly);
    QAudioFormat format;
    format.setSampleRate(44100);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
    if (!info.isFormatSupported(format)) {
        qWarning() << "Raw audio format not supported by backend, cannot play audio.";
        finishedSound = NULL;
    } else {
        finishedSound = new QAudioOutput(format, this);
        //finishedSound->start(&finishedSource);
    }

    connect(ui->startTimer, SIGNAL(clicked()), this, SLOT(startCountDown()));
    connect(&timer, SIGNAL(timeout()), this, SLOT(timerTick()));
    connect(ui->fullscreen, SIGNAL(clicked()), this, SLOT(fullScreenClicked()));
}
Example #20
0
void idle() {
	timerTick();
	sphere.fall(GRAVITY, deltaTime);
	display();

}
Example #21
0
/**
 * Interrupt 20h. Handles the IRQ0 also know as timmer tick.
 *
 *  @param regs Pointer to struct containing micro's registers.
 */
void int20(registers* regs) {
    timerTick();
}
Example #22
0
void DW1000RangingClass::loop() {
	//we check if needed to reset !
	checkForReset();
	long time = millis();
	if(time-timer > _timerDelay) {
		timer = time;
		timerTick();
	}
	
	if(_sentAck) {
		_sentAck = false;
		
		
		int messageType = detectMessageType(data);
		
		if(messageType != POLL_ACK && messageType != POLL && messageType != RANGE)
			return;
		
		
		//A msg was sent. We launch the ranging protocole when a message was sent
		if(_type == ANCHOR) {
			if(messageType == POLL_ACK) {
				DW1000Device* myDistantDevice = searchDistantDevice(_lastSentToShortAddress);
				
				DW1000.getTransmitTimestamp(myDistantDevice->timePollAckSent);
			}
		}
		else if(_type == TAG) {
			if(messageType == POLL) {
				DW1000Time timePollSent;
				DW1000.getTransmitTimestamp(timePollSent);
				//if the last device we send the POLL is broadcast:
				if(_lastSentToShortAddress[0] == 0xFF && _lastSentToShortAddress[1] == 0xFF) {
					//we save the value for all the devices !
					for(short i = 0; i < _networkDevicesNumber; i++) {
						_networkDevices[i].timePollSent = timePollSent;
					}
				}
				else {
					//we search the device associated with the last send address
					DW1000Device* myDistantDevice = searchDistantDevice(_lastSentToShortAddress);
					//we save the value just for one device
					myDistantDevice->timePollSent = timePollSent;
				}
			}
			else if(messageType == RANGE) {
				DW1000Time timeRangeSent;
				DW1000.getTransmitTimestamp(timeRangeSent);
				//if the last device we send the POLL is broadcast:
				if(_lastSentToShortAddress[0] == 0xFF && _lastSentToShortAddress[1] == 0xFF) {
					//we save the value for all the devices !
					for(short i = 0; i < _networkDevicesNumber; i++) {
						_networkDevices[i].timeRangeSent = timeRangeSent;
					}
				}
				else {
					//we search the device associated with the last send address
					DW1000Device* myDistantDevice = searchDistantDevice(_lastSentToShortAddress);
					//we save the value just for one device
					myDistantDevice->timeRangeSent = timeRangeSent;
				}
				
			}
		}
		
	}
	
	//check for new received message
	if(_receivedAck) {
		_receivedAck = false;
		
		
		//we read the datas from the modules:
		// get message and parse
		DW1000.getData(data, LEN_DATA);
		
		
		int messageType = detectMessageType(data);
		
		//we have just received a BLINK message from tag
		if(messageType == BLINK && _type == ANCHOR) {
			byte address[8];
			byte shortAddress[2];
			_globalMac.decodeBlinkFrame(data, address, shortAddress);
			//we crate a new device with th tag
			DW1000Device myTag(address, shortAddress);
			
			if(addNetworkDevices(&myTag)) {
				Serial.print("blink; 1 device added ! -> ");
				Serial.print(" short:");
				Serial.println(myTag.getShortAddress(), HEX);
				
				//we relpy by the transmit ranging init message
				transmitRangingInit(&myTag);
				noteActivity();
			}
			_expectedMsgId = POLL;
		}
		else if(messageType == RANGING_INIT && _type == TAG) {
			
			byte address[2];
			_globalMac.decodeLongMACFrame(data, address);
			//we crate a new device with the anchor
			DW1000Device myAnchor(address, true);
			
			if(addNetworkDevices(&myAnchor, true)) {
				Serial.print("ranging init; 1 device added ! -> ");
				Serial.print(" short:");
				Serial.println(myAnchor.getShortAddress(), HEX);
			}
			
			noteActivity();
			
		}
		else {
			//we have a short mac layer frame !
			byte address[2];
			_globalMac.decodeShortMACFrame(data, address);
			
			
			
			//we get the device which correspond to the message which was sent (need to be filtered by MAC address)
			DW1000Device* myDistantDevice = searchDistantDevice(address);
			
			
			if(myDistantDevice == NULL) {
				Serial.println("Not found");
				//we don't have the short address of the device in memory
				/*
				Serial.print("unknown: ");
				Serial.print(address[0], HEX);
				Serial.print(":");
				Serial.println(address[1], HEX);
				*/
				return;
			}
			
			
			//then we proceed to range protocole
			if(_type == ANCHOR) {
				if(messageType != _expectedMsgId) {
					// unexpected message, start over again (except if already POLL)
					_protocolFailed = true;
				}
				if(messageType == POLL) {
					//we receive a POLL which is a broacast message
					//we need to grab info about it
					short numberDevices = 0;
					memcpy(&numberDevices, data+SHORT_MAC_LEN+1, 1);
					
					for(short i = 0; i < numberDevices; i++) {
						//we need to test if this value is for us:
						//we grab the mac address of each devices:
						byte shortAddress[2];
						memcpy(shortAddress, data+SHORT_MAC_LEN+2+i*4, 2);
						
						//we test if the short address is our address
						if(shortAddress[0] == _currentShortAddress[0] && shortAddress[1] == _currentShortAddress[1]) {
							//we grab the replytime wich is for us
							unsigned int replyTime = 0;
							memcpy(&replyTime, data+SHORT_MAC_LEN+2+i*4+2, 2);
							//we configure our replyTime;
							_replyDelayTimeUS = replyTime;
							
							// on POLL we (re-)start, so no protocol failure
							_protocolFailed = false;
							
							DW1000.getReceiveTimestamp(myDistantDevice->timePollReceived);
							//we note activity for our device:
							myDistantDevice->noteActivity();
							//we indicate our next receive message for our ranging protocole
							_expectedMsgId = RANGE;
							transmitPollAck(myDistantDevice);
							noteActivity();
							
							return;
						}
						
					}
					
					
				}
				else if(messageType == RANGE) {
					//we receive a RANGE which is a broacast message
					//we need to grab info about it
					short numberDevices = 0;
					memcpy(&numberDevices, data+SHORT_MAC_LEN+1, 1);
					
					
					for(short i = 0; i < numberDevices; i++) {
						//we need to test if this value is for us:
						//we grab the mac address of each devices:
						byte shortAddress[2];
						memcpy(shortAddress, data+SHORT_MAC_LEN+2+i*17, 2);
						
						//we test if the short address is our address
						if(shortAddress[0] == _currentShortAddress[0] && shortAddress[1] == _currentShortAddress[1]) {
							//we grab the replytime wich is for us
							DW1000.getReceiveTimestamp(myDistantDevice->timeRangeReceived);
							noteActivity();
							_expectedMsgId = POLL;
							
							if(!_protocolFailed) {
								
								myDistantDevice->timePollSent.setTimestamp(data+SHORT_MAC_LEN+4+17*i);
								myDistantDevice->timePollAckReceived.setTimestamp(data+SHORT_MAC_LEN+9+17*i);
								myDistantDevice->timeRangeSent.setTimestamp(data+SHORT_MAC_LEN+14+17*i);
								
								// (re-)compute range as two-way ranging is done
								DW1000Time myTOF;
								computeRangeAsymmetric(myDistantDevice, &myTOF); // CHOSEN RANGING ALGORITHM
								
								float distance = myTOF.getAsMeters();
								
								myDistantDevice->setRXPower(DW1000.getReceivePower());
								myDistantDevice->setRange(distance);
								
								myDistantDevice->setFPPower(DW1000.getFirstPathPower());
								myDistantDevice->setQuality(DW1000.getReceiveQuality());
								
								//we send the range to TAG
								transmitRangeReport(myDistantDevice);
								
								//we have finished our range computation. We send the corresponding handler
								_lastDistantDevice = myDistantDevice->getIndex();
								if(_handleNewRange != 0) {
									(*_handleNewRange)();
								}
								
							}
							else {
								transmitRangeFailed(myDistantDevice);
							}
							
							
							return;
						}
						
					}
					
					
				}
			}
			else if(_type == TAG) {
				// get message and parse
				if(messageType != _expectedMsgId) {
					// unexpected message, start over again
					//not needed ?
					return;
					_expectedMsgId = POLL_ACK;
					return;
				}
				if(messageType == POLL_ACK) {
					DW1000.getReceiveTimestamp(myDistantDevice->timePollAckReceived);
					//we note activity for our device:
					myDistantDevice->noteActivity();
					
					
					
					
					//in the case the message come from our last device:
					if(myDistantDevice->getIndex() == _networkDevicesNumber-1) {
						_expectedMsgId = RANGE_REPORT;
						//and transmit the next message (range) of the ranging protocole (in broadcast)
						transmitRange(NULL);
					}
				}
				else if(messageType == RANGE_REPORT) {
					
					float curRange;
					memcpy(&curRange, data+1+SHORT_MAC_LEN, 4);
					float curRXPower;
					memcpy(&curRXPower, data+5+SHORT_MAC_LEN, 4);
					//we have a new range to save !
					myDistantDevice->setRange(curRange);
					myDistantDevice->setRXPower(curRXPower);
					
					
					//We can call our handler !
					//we have finished our range computation. We send the corresponding handler
					_lastDistantDevice = myDistantDevice->getIndex();
					if(_handleNewRange != 0) {
						(*_handleNewRange)();
					}
				}
				else if(messageType == RANGE_FAILED) {
					//not needed as we have a timer;
					return;
					_expectedMsgId = POLL_ACK;
				}
			}
		}
		
	}
}
Example #23
0
void DW1000RangingClass::loop(){
    //we check if needed to reset !
    checkForReset();
    long time=millis(); 
    if(time-timer>DEFAULT_TIMER_DELAY){
        timer=time;
        timerTick();
    }
    
    if(_sentAck){
        _sentAck = false;
        
        
        int messageType=detectMessageType(data);
        
        if(messageType!=POLL_ACK && messageType!= POLL && messageType!=RANGE)
            return;
        
        
        DW1000Device *myDistantDevice=searchDistantDevice(_lastSentToShortAddress);
        
        if(myDistantDevice==0)
        {
            //we don't have the short address of the device in memory
            /*
            Serial.print("unknown sent: ");
            Serial.print(_lastSentToShortAddress[0], HEX);
            Serial.print(":");
            Serial.println(_lastSentToShortAddress[1], HEX);
             */
        }
        
        
        //A msg was sent. We launch the ranging protocole when a message was sent
        if(_type==ANCHOR){
            if(messageType == POLL_ACK) {
                DW1000.getTransmitTimestamp(myDistantDevice->timePollAckSent);
            }
        }
        else if(_type==TAG){
            if(messageType == POLL) {
                DW1000.getTransmitTimestamp(myDistantDevice->timePollSent);
                //Serial.print("Sent POLL @ "); Serial.println(timePollSent.getAsFloat());
            } else if(messageType == RANGE) { 
                
                DW1000.getTransmitTimestamp(myDistantDevice->timeRangeSent);
            }
        }
        
    }
    
    //check for new received message
    if(_receivedAck){
        _receivedAck=false;
        
        //we read the datas from the modules:
        // get message and parse
        DW1000.getData(data, LEN_DATA);
        
        
        int messageType=detectMessageType(data);
        
        //we have just received a BLINK message from tag
        if(messageType==BLINK && _type==ANCHOR){ 
            byte address[8];
            byte shortAddress[2];
            _globalMac.decodeBlinkFrame(data, address, shortAddress);
            //we crate a new device with th tag
            DW1000Device myTag(address, shortAddress);
            
            if(addNetworkDevices(&myTag))
            {
                Serial.print("blink; 1 device added ! -> "); 
                Serial.print(" short:");
                Serial.println(myTag.getShortAddress(), HEX);
                
                //we relpy by the transmit ranging init message
                transmitRangingInit(&myTag);
                noteActivity();
            }
            _expectedMsgId=POLL;
        }
        else if(messageType==RANGING_INIT && _type==TAG){
            
            byte address[2];
            _globalMac.decodeLongMACFrame(data, address);
            //we crate a new device with the anchor
            DW1000Device myAnchor(address, true);
            
            if(addNetworkDevices(&myAnchor, true))
            {
                Serial.print("ranging init; 1 device added ! -> ");
                Serial.print(" short:");
                Serial.println(myAnchor.getShortAddress(), HEX);
            }
            //we relpy by the transmit ranging init message
            //transmitPoll(&myAnchor);
        
            noteActivity();
            
        }
        else
        {
            //we have a short mac layer frame !
            byte address[2];
            _globalMac.decodeShortMACFrame(data, address);
            
             
            
            //we get the device which correspond to the message which was sent (need to be filtered by MAC address)
            DW1000Device *myDistantDevice=searchDistantDevice(address);
            
            if(myDistantDevice==0)
            {
                //we don't have the short address of the device in memory
                /*
                Serial.print("unknown: ");
                Serial.print(address[0], HEX);
                Serial.print(":");
                Serial.println(address[1], HEX);
                */
                return;
            }
            
            
            
        
            //then we proceed to range protocole
            if(_type==ANCHOR){
                if(messageType != _expectedMsgId) {
                    // unexpected message, start over again (except if already POLL)
                    _protocolFailed = true;
                }
                if(messageType == POLL) {
                    //Serial.println("receive poll");
                    // on POLL we (re-)start, so no protocol failure
                    _protocolFailed = false;
                    
                    DW1000.getReceiveTimestamp(myDistantDevice->timePollReceived);
                    //we note activity for our device:
                    myDistantDevice->noteActivity();
                    //we indicate our next receive message for our ranging protocole
                    _expectedMsgId = RANGE;
                    transmitPollAck(myDistantDevice);
                    noteActivity();
                }
                else if(messageType == RANGE) {
                    DW1000.getReceiveTimestamp(myDistantDevice->timeRangeReceived);
                    noteActivity();
                    _expectedMsgId = POLL;
                    
                    if(!_protocolFailed) {
                        
                        myDistantDevice->timePollSent.setTimestamp(data+1+SHORT_MAC_LEN);
                        myDistantDevice->timePollAckReceived.setTimestamp(data+6+SHORT_MAC_LEN);
                        myDistantDevice->timeRangeSent.setTimestamp(data+11+SHORT_MAC_LEN);
                        
                        // (re-)compute range as two-way ranging is done
                        DW1000Time myTOF;
                        computeRangeAsymmetric(myDistantDevice, &myTOF); // CHOSEN RANGING ALGORITHM
                        
                        float distance=myTOF.getAsMeters();
                        
                        myDistantDevice->setRXPower(DW1000.getReceivePower());
                        myDistantDevice->setRange(distance);
                         
                        myDistantDevice->setFPPower(DW1000.getFirstPathPower());
                        myDistantDevice->setQuality(DW1000.getReceiveQuality());
                        
                        //we send the range to TAG
                        transmitRangeReport(myDistantDevice);
                        
                        //we have finished our range computation. We send the corresponding handler
                        
                        if(_handleNewRange != 0) {
                            (*_handleNewRange)();
                        }
                        
                    }
                    else {
                        transmitRangeFailed(myDistantDevice);
                    }
                    
                    noteActivity();
                }
            }
            else if(_type==TAG){
                // get message and parse
                if(messageType != _expectedMsgId) {
                    // unexpected message, start over again
                    _expectedMsgId = POLL_ACK;
                    //transmitPoll(myDistantDevice);
                    return;
                }
                if(messageType == POLL_ACK) {
                    DW1000.getReceiveTimestamp(myDistantDevice->timePollAckReceived);
                    _expectedMsgId = RANGE_REPORT;
                    //we note activity for our device:
                    myDistantDevice->noteActivity();
                    //and transmit the next message (range) of the ranging protocole
                    transmitRange(myDistantDevice);
                }
                else if(messageType == RANGE_REPORT) {
                    _expectedMsgId = POLL_ACK;
                    float curRange;
                    memcpy(&curRange, data+1+SHORT_MAC_LEN, 4);
                    float curRXPower;
                    memcpy(&curRXPower, data+5+SHORT_MAC_LEN, 4);
                    //we have a new range to save !
                    myDistantDevice->setRange(curRange);
                    myDistantDevice->setRXPower(curRXPower);
                    
                    
                    //We can call our handler !
                    if(_handleNewRange != 0){
                        (*_handleNewRange)();
                    }
                }
                else if(messageType == RANGE_FAILED) {
                    _expectedMsgId = POLL_ACK;
                }
            }
        }
        
    }
}
Example #24
0
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_CREATE:
		break;
	case WM_PAINT:

		hdc = BeginPaint(hWnd, &ps);

		{
			RECT cr;
			GetClientRect(hWnd, &cr);

			int width = cr.right - cr.left;
			int height = cr.bottom - cr.top;

			HDC bufDC;
			HBITMAP bufBMP;

			bufDC = CreateCompatibleDC(hdc);
			bufBMP = CreateCompatibleBitmap(hdc, width, height);
			SelectObject(bufDC, bufBMP);

			setPaintDC(bufDC);

			RECT r = {0};
			r.right = width;
			r.bottom = height;

			FillRect(bufDC, &r, GetStockBrush(WHITE_BRUSH));

			paint();

			setPaintDC(NULL);

			BitBlt(hdc, 0, 0, width, height, bufDC, 0, 0, SRCCOPY);

			DeleteObject(bufBMP);
			DeleteDC(bufDC);
		}

		EndPaint(hWnd, &ps);
		break;
	
	case WM_MOUSEMOVE:
		{
			int x = GET_X_LPARAM(lParam); 
			int y = GET_Y_LPARAM(lParam);

			mouseMove(x, y);
		}
	break;
	
	case WM_LBUTTONDOWN:
		SetCapture(hWnd);
		mouseDown();
	break;

	case WM_LBUTTONUP:
		ReleaseCapture();
		mouseUp();
	break;

	case WM_KEYDOWN:
		{
			int vk = wParam;
			char ch = MapVirtualKey(vk, MAPVK_VK_TO_CHAR);

			keyDown(ch, vk);
		}

		break;
	
	case WM_KEYUP:
		{
			int vk = wParam;
			char ch = MapVirtualKey(vk, MAPVK_VK_TO_CHAR);

			keyUp(ch, vk);
		}

		break;

	case WM_TIMER:
		switch(wParam)
		{
		case IDT_TIMER0:
			timerTick();
			break;
		}
		
		break;

	case WM_DESTROY:
		finalize();

		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Example #25
0
Slider::Slider(QWidget *parent,Tokeniser *t) :
QWidget(NULL)
{
    bool rangeGot = false;
    bool always = false;
    bool vertical = false;
    immediate = false;
    renderer = NULL;
    char outVar[64]; //!< name of the variable to write to
    title[0]=0;
    inverse = ConfigManager::inverse;
    
    ConfigRect pos = ConfigManager::parseRect();
    bool done = false;
    
    t->getnextcheck(T_OCURLY);
    
    initSet=false;
    
    DataBuffer<float> *buf=NULL;
    
    outVar[0]=0;
    epsilon = 0.001f;
    isInteger=false;
    
    while(!done){
        switch(t->getnext()){
        case T_EXPR: // optional, provides a 'feedback' value
        case T_VAR:
            t->rewind();
            buf = ConfigManager::parseFloatSource();
            break;
        case T_EPSILON:
            epsilon = t->getnextfloat();
            break;
        case T_INTEGER:
            isInteger=true;
            break;
        case T_OUT:
            t->getnextident(outVar);
            break;
        case T_INITIAL:
            initial = t->getnextfloat();
            initSet=true;
            break;
        case T_HORIZONTAL: // dummy since it's the default
            break;
        case T_VERTICAL:
            vertical = true;
            break;
        case T_RANGE:
            minVal = t->getnextfloat();
            t->getnextcheck(T_TO);
            maxVal = t->getnextfloat();
            rangeGot=true;
            break;
        case T_TITLE:
            t->getnextstring(title);
            break;
        case T_ALWAYS:
            always=true;
            break;
        case T_IMMEDIATE:
            immediate=true;
            break;
        case T_CCURLY:
            done=true;
            break;
        default:
            throw Exception(t->getline()).set("Unexpected '%s'",t->getstring());
        }
    }
    
    if(!outVar[0])
        throw Exception("no output name given for slider",t->getline());
    if(!rangeGot)
        throw Exception("no range given for slider",t->getline());
    if(!initSet)initial=minVal;
    
    // create a new outvar
    
    out = new OutValue(outVar,0,always);
    out->listener=this; // so we know when our var was sent
    UDPClient::getInstance()->add(out);
    
    if(!title[0])
        strcpy(title,outVar);
    
    renderer = buf ? new DataRenderer(this,buf) : NULL;
    connect(&timer,SIGNAL(timeout()),this,SLOT(timerTick()));
    
    try{
        ConfigManager::registerNudgeable(outVar,this);
    }catch(Exception& e){
        throw Exception(e,t->getline());
    }
    
    QVBoxLayout *layout;
    
    layout = new QVBoxLayout(this);
    layout->setSpacing(0);
    slider = new InternalSlider(vertical?Qt::Vertical:Qt::Horizontal,this);
    slider->setMaximum(100);
    slider->setMinimum(0);
    layout->setAlignment(Qt::AlignCenter);
    label = new QLabel(title);
    label->setAlignment(Qt::AlignCenter);
    label->setMaximumSize(10000,30);
    layout->addWidget(slider);
    layout->addWidget(label);
    setLayout(layout);
    
    slider->setStyleSheet(defaultStyle);
    connect(slider,SIGNAL(sliderPressed()),this,SLOT(pressed()));
    connect(slider,SIGNAL(sliderReleased()),this,SLOT(released()));
    
    QGridLayout *l = (QGridLayout*)parent->layout();
    l->addWidget(this,pos.y,pos.x,pos.h,pos.w);
    setMinimumSize(100,100);
    timer.start(200);
    
    machine.start(initState,this);
    setDrawProperties();
}
Example #26
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mainWindow = this;

    // Start device manager
    KbManager::init(CKB_VERSION_STR);
    connect(KbManager::kbManager(), SIGNAL(kbConnected(Kb*)), this, SLOT(addDevice(Kb*)));
    connect(KbManager::kbManager(), SIGNAL(kbDisconnected(Kb*)), this, SLOT(removeDevice(Kb*)));
    connect(KbManager::kbManager(), SIGNAL(versionUpdated()), this, SLOT(updateVersion()));
    connect(KbManager::scanTimer(), SIGNAL(timeout()), this, SLOT(timerTick()));

    // Set up tray icon
    restoreAction = new QAction(tr("Restore"), this);
    closeAction = new QAction(tr("Quit ckb"), this);
#ifdef USE_LIBAPPINDICATOR
    QString desktop = std::getenv("XDG_CURRENT_DESKTOP");
    unityDesktop = (desktop.toLower() == "unity");

    if(unityDesktop){
        trayIcon = 0;

        indicatorMenu = gtk_menu_new();
        indicatorMenuRestoreItem = gtk_menu_item_new_with_label("Restore");
        indicatorMenuQuitItem = gtk_menu_item_new_with_label("Quit ckb");

        gtk_menu_shell_append(GTK_MENU_SHELL(indicatorMenu), indicatorMenuRestoreItem);
        gtk_menu_shell_append(GTK_MENU_SHELL(indicatorMenu), indicatorMenuQuitItem);

        g_signal_connect(indicatorMenuQuitItem, "activate",
            G_CALLBACK(quitIndicator), this);
        g_signal_connect(indicatorMenuRestoreItem, "activate",
            G_CALLBACK(restoreIndicator), this);

        gtk_widget_show(indicatorMenuRestoreItem);
        gtk_widget_show(indicatorMenuQuitItem);

        indicator = app_indicator_new("ckb", "indicator-messages", APP_INDICATOR_CATEGORY_APPLICATION_STATUS);

        app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE);
        app_indicator_set_menu(indicator, GTK_MENU(indicatorMenu));
        app_indicator_set_icon(indicator, "ckb");
    } else
#endif // USE_LIBAPPINDICATOR
    {
        trayIconMenu = new QMenu(this);
        trayIconMenu->addAction(restoreAction);
        trayIconMenu->addAction(closeAction);
        trayIcon = new QSystemTrayIcon(QIcon(":/img/ckb-logo.png"), this);
        trayIcon->setContextMenu(trayIconMenu);
        connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconClicked(QSystemTrayIcon::ActivationReason)));
     }
     toggleTrayIcon(!CkbSettings::get("Program/SuppressTrayIcon").toBool());

#ifdef Q_OS_MACX
    // Make a custom "Close" menu action for OSX, as the default one brings up the "still running" popup unnecessarily
    QMenuBar* menuBar = new QMenuBar(this);
    setMenuBar(menuBar);
    this->menuBar()->addMenu("ckb")->addAction(closeAction);
#else
    // On linux, add a handler for Ctrl+Q
    new QShortcut(QKeySequence("Ctrl+Q"), this, SLOT(quitApp()));
#endif

    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(quitApp()));
    connect(closeAction, SIGNAL(triggered()), this, SLOT(quitApp()));
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showWindow()));
    connect(qApp, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(stateChange(Qt::ApplicationState)));

    connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(cleanup()));

    ui->tabWidget->addTab(settingsWidget = new SettingsWidget(this), configLabel);
    settingsWidget->setVersion("ckb " CKB_VERSION_STR);
}
Example #27
0
bool SipPhoneProxy::initRegistrationData( void )
{
	//QSettings settings;

	SipRegistrationData regData;
	//{
	//  // Адрес SIP сервера для регистрации
	//  // Остается пустым если задан sipUserUri
	//  QString sipServerUri;
	//  // Порт SIP сервера
	//  int sipServerPort;
	//  // Время действия регистрации
	//  int registrationExpiresTime;
	//  // URI текущего пользователя
	//  QString sipUserUri;
	//  // Логин и пароль для регистрации
	//  QString userName;
	//  QString password;
	//  // Флаг использования STUN сервера
	//  bool useStun;
	//  // Адрес STUN сервера включая порт в формате stunserver.domen:3478
	//  QString stunServerWithPort;
	//  // Значение qValue
	//  QString qValue;
	//  // Флаг авторегистрации
	//  bool autoRegister;
	//};

	//QString pp = "/settings/local/";

	regData.registrationExpiresTime = constRegistrationExpiresTime;// settings.value( pp + "/RegistrationExpiresTime", constRegistrationExpiresTime ).toInt();
	if( regData.registrationExpiresTime == 0 )
	{
		regData.registrationExpiresTime = -1;
	}

	//pp = "/settings/Registration/";
	////regData.sipUserUri = _pSipUser->getUri().getRegisterUri();//  settings.value( pp + "/SipUri" ).toString();

	SipUri uri = _pSipUser->getUri();
	regData.sipUserUri = uri.nameAddr_noTag();
	//regData.sipUserUri = _pSipUser->getUri().nameAddr_noTag();

	//SipUri userURI = _pSipUser->getUri();
	//QString res;
	//res = "userURI: " + _pSipUser->getUri().nameAddr_noTag() + " pass: "******"debug", res);

	regData.useStun = false;
	//if( settings.value( "/settings/STUN/UseStun", "No" ).toString() == "Yes" )
	//{
	//	regData.useStun = true;
	//}

	if(regData.useStun)
	{
		regData.stunServerWithPort = "talkpad.ru:5065";// settings.value( "/settings/STUN/StunServer", constStunServer ).toString();
		if( regData.stunServerWithPort.isEmpty() )
		{
			QString dname = _pSipUser->getMyUri()->getHostname();
			regData.stunServerWithPort = dname;
			QString srv = _pSipClient->getSRV( QString( "_stun._udp." ) + dname );
			if( !srv.isEmpty() )
			{
				regData.stunServerWithPort = srv;
			}
			regData.stunServerWithPort += ":3478";
		}
		else
		{
			if( !regData.stunServerWithPort.contains( ':' ) )
			{
				regData.stunServerWithPort += ":3478";
			}
		}
	}

	//if( settings.value( pp + "/SipServer", "" ).toString() != "" )
	//{
	//	regData.sipServerUri = settings.value( pp + "/SipServer" ).toString();
	//}
	//regData.sipServerUri = "81.19.69.224";
	//regData.sipServerUri = "81.19.70.71";//"81.19.70.76";
	regData.sipServerUri = "81.19.70.76";
	//regData.sipServerUri = "81.19.80.213";

	regData.qValue = "";// settings.value( pp + "/qValue", "" ).toString();
	//regData.userName = settings.value( pp + "/UserName" ).toString();
	//regData.password = settings.value( pp + "/Password" ).toString();
	//QString str = settings.value( pp + "/AutoRegister" ).toString();
	//regData.autoRegister = ( str == "Yes" ) ? true : false;
	regData.autoRegister = false;


	//connect(this, SIGNAL(proxyTrueRegistrationStatus(bool)), this, SLOT(registrationStatus(bool)));

	registrations = new RSipRegistrations(regData, _pSipClient, this);

	if(registrations == NULL)
		return false;

	connect(registrations, SIGNAL(proxyTrueRegistrationStatus(bool)), this, SLOT(registrationStatus(bool)));
	//connect(registrations, SIGNAL(proxyTrueRegistrationStatus(bool)), this, SLOT(trueRegistrationStatusSlot(bool)));

	// Кнопки регистрации
	//connect(ui.buttonRegister, SIGNAL(clicked()), registrations, SLOT(makeRegister()));
	//connect(ui.buttonUnRegister, SIGNAL(clicked()), registrations, SLOT(clearRegister()));

	//identities( registrations );


	if( registrations->getUseStun() )
	{
		//view->setStunSrv( registrations->getStunSrv() );
		setStunSrv( registrations->getStunSrv() );
		_pSipClient->sendStunRequest( registrations->getStunSrv() );
		QTimer *stun_timer = new QTimer( this );
		connect( stun_timer, SIGNAL( timeout() ), this, SLOT( stun_timerTick() ) );
		//QString p = "/settings/Registration/";
		//int timeout = settings.value( p + "RequestPeriod", constStunRequestPeriod ).toInt();
		int timeout = constStunRequestPeriod;
		if( timeout > 0 )
		{
			stun_timer->start( timeout * 1000 );
		}
	}

	QTimer *timer = new QTimer( this );
	connect( timer, SIGNAL( timeout() ), this, SLOT( timerTick() ) );

	timer->start( 20 );

	return true;
}
void ProtocolController::Initialize()
{
    if(!this->initialized)
    {
        //Defines the center of the screen
        this->centerX = this->parent->geometry().width()/2;
        this->centerY = this->parent->geometry().height()/2;

        //Defines the position of the origin
        this->originX = this->centerX;
        this->originY = this->centerY + this->distanceTarget;

        //Defines the position of the target
        this->targetX = this->centerX;
        this->targetY = this->centerY - this->distanceTarget;

        //Sets the cursor to the center of the screen
        QCursor::setPos(this->centerX,this->centerY);

        //Creates a new mutex
        this->mutex = new QMutex();
        //Creates a new thread
        this->workerThread = new QThread;
        //Starts the thread
        this->workerThread->start();
        //Creates a new timer
        this->timer = new QTimer(0);
        //Precise timer is prefered
        this->timer->setTimerType(Qt::PreciseTimer);
        //Finds the timer interval (ms) according to the sampling frequency
        int interval = (int)(1000 * (1.0 / ((double)this->samplingFrequency)));
        this->timer->setInterval(interval);
        //Connects the timer to the processing event
        connect(this->timer,SIGNAL(timeout()),this,SLOT(timerTick()));
        //Moves the protocol controller to a different Thread
        this->timer->moveToThread(workerThread);

        //Connects an event to the rest timer
        this->timerRest = new QTimer(0);
        this->timerRest->setInterval(this->restInterval);
        connect(this->timerRest,SIGNAL(timeout()),this,SLOT(timerRestTick()));

        //Connects events to the timer
        connect(this,SIGNAL(start()),this->timer,SLOT(start()),
                Qt::QueuedConnection);
        connect(this,SIGNAL(stop()),this->timer,SLOT(stop()),
                Qt::QueuedConnection);

        //Initializes the cursor controller
        this->cursorController = new CursorController();
        if(this->perturbation)
        {
            this->cursorController->setPerturbation(this->perturbationDegree);
            this->cursorController->setOriginX(this->originX);
            this->cursorController->setOriginY(this->originY);
        }

        //Counter for the number of trials
        this->trialCounter=0;
        //Counter for the number of sessions
        this->sessionCounter=1;

        //Aux variables
        double x=0;
        double y=0;

        //Creates the object representing the origin                
        this->objOrigin = new GUIObject();
        x = this->originX;
        y = this->originY;
        this->objOrigin->point = new QPointF(x,y);
        this->objOrigin->pen = new QPen(Qt::blue);
        this->objOrigin->pen->setWidth(0);
        this->objOrigin->width = this->objWidth;
        this->objOrigin->height = this->objHeight;
        this->objOrigin->type = GUIObject::Ellipse;

        //Creates the object representing the target
        this->targetColor = Qt::red;
        this->objTarget = new GUIObject();
        x = this->targetX;
        y = this->targetY;
        this->objTarget->point = new QPointF(x,y);
        this->objTarget->pen = new QPen(this->targetColor);
        this->objTarget->pen->setWidth(0);
        this->objTarget->width = this->objWidth;
        this->objTarget->height = this->objHeight;
        this->objTarget->type = GUIObject::Ellipse;

        this->objFeedbackCursor = new GUIObject();
        this->feedbackCursorColor = Qt::green;
        this->objCursor = new GUIObject();

        //Writes the header file
        this->writeHeader();

        QCursor::setPos(this->originX,this->originY);

        this->initialized = true;
    }
}
Example #29
0
void
handleInterrupt(irq_t irq)
{
    if (unlikely(irq > maxIRQ)) {
        /* mask, ack and pretend it didn't happen. We assume that because
         * the interrupt controller for the platform returned this IRQ that
         * it is safe to use in mask and ack operations, even though it is
         * above the claimed maxIRQ. i.e. we're assuming maxIRQ is wrong */
        printf("Received IRQ %d, which is above the platforms maxIRQ of %d\n", (int)irq, (int)maxIRQ);
        maskInterrupt(true, irq);
        ackInterrupt(irq);
        return;
    }
    switch (intStateIRQTable[irq]) {
    case IRQSignal: {
        cap_t cap;

        cap = intStateIRQNode[irq].cap;

        if (cap_get_capType(cap) == cap_notification_cap &&
                cap_notification_cap_get_capNtfnCanSend(cap)) {
            sendSignal(NTFN_PTR(cap_notification_cap_get_capNtfnPtr(cap)),
                       cap_notification_cap_get_capNtfnBadge(cap));
        } else {
#ifdef CONFIG_IRQ_REPORTING
            printf("Undelivered IRQ: %d\n", (int)irq);
#endif
        }
        maskInterrupt(true, irq);
        break;
    }

    case IRQTimer:
        timerTick();
        resetTimer();
        break;

    case IRQReserved:
#ifdef CONFIG_IRQ_REPORTING
        printf("Received reserved IRQ: %d", (int)irq);
#endif
        handleReservedIRQ(irq);
        break;

    case IRQInactive:
        /*
         * This case shouldn't happen anyway unless the hardware or
         * platform code is broken. Hopefully masking it again should make
         * the interrupt go away.
         */
        maskInterrupt(true, irq);
#ifdef CONFIG_IRQ_REPORTING
        printf("Received disabled IRQ: %d\n", (int)irq);
#endif
        break;

    default:
        /* No corresponding haskell error */
        fail("Invalid IRQ state");
    }

    ackInterrupt(irq);
}
Example #30
0
void MasterTimer::run()
{
	/* How long to wait each loop */
	int tickTime = 1000000 / KFrequency;

	/* Allocate this from stack here so that GCC doesn't have
	   to do it everytime implicitly when gettimeofday() is called */
	int tod = 0;

	/* Allocate all the memory at the start so we don't waste any time */
	timeval* finish = static_cast<timeval*> (malloc(sizeof(timeval)));
	timeval* current = static_cast<timeval*> (malloc(sizeof(timeval)));
	timespec* sleepTime = static_cast<timespec*> (malloc(sizeof(timespec)));
	timespec* remainingTime = static_cast<timespec*> (malloc(sizeof(timespec)));

	sleepTime->tv_sec = 0;

	/* This is the start time for the timer */
	tod = gettimeofday(finish, NULL);
	if (tod == -1)
	{
		qWarning() << "Unable to get the time accurately:"
			   << strerror(errno)
			   << "- Stopping MasterTimer";
		m_running = false;
	}
	else
	{
		m_running = true;
	}

	while (m_running == true)
	{
		/* Increment the finish time for this loop */
		finish->tv_sec += (finish->tv_usec + tickTime) / 1000000;
		finish->tv_usec = (finish->tv_usec + tickTime) % 1000000;

		tod = gettimeofday(current, NULL);
		if (tod == -1)
		{
			qWarning("Unable to get the current time: %s",
				 strerror(errno));
			m_running = false;
			break;
		}

		/* Do a rough sleep using the kernel to return control.
		   We know that this will never be seconds as we are dealing
		   with jumps of under a second every time. */
		sleepTime->tv_nsec =
			((finish->tv_usec - current->tv_usec) * 1000) +
			((finish->tv_sec - current->tv_sec) * 1000000000) - 1000;
		if (sleepTime->tv_nsec > 0)
		{
			tod = nanosleep(sleepTime, remainingTime);
			while (tod == -1 && sleepTime->tv_nsec > 100) {
				sleepTime->tv_nsec = remainingTime->tv_nsec;
				tod = nanosleep(sleepTime, remainingTime);
			}
		}

		/* Now take full CPU for precision (only a few nanoseconds,
		   at maximum 1000 nanoseconds) */
		while (finish->tv_usec - current->tv_usec +
		       (finish->tv_sec - current->tv_sec) * 1000000 > 5)
		{
			tod = gettimeofday(current, NULL);
			if (tod == -1)
			{
				qWarning("Unable to get the current time: %s",
					 strerror(errno));
				m_running = false;
				break;
			}
		}

		/* Execute the next timer event */
		timerTick();
	}

	free(finish);
	free(current);
	free(sleepTime);
	free(remainingTime);
}