int main() {
  // Example 1 [-1,1]
  a = -1.0;
  b = 1.0;
  n = 1000;
  int curr_num_threads[3] = {2, 50, 100};
  for (int i=0; i<3; i++)
  {
    approx = 0;
    thread_count = curr_num_threads[i];
    printf("\nRun with %d threads\n", thread_count);
    timerStart();
    run_threads();
    printf("Took %ld ms\n", timerStop());
    printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, NEG_1_TO_POS_1, approx);
  }

  // Example 2 [0,10]
  a = 0.0;
  b = 10.0;
  n = 1000;
  for (int i=0; i<3; i++)
  {
    approx = 0;
    thread_count = curr_num_threads[i];
    printf("\nRun with %d threads\n", thread_count);
    timerStart();
    run_threads();
    printf("Took %ld ms\n", timerStop());
    printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, ZERO_TO_POS_10, approx);
  }

  return 0;
}
예제 #2
0
bool videoVBL()
{
	if(!videoPlaying) return false;
	
	while(videoFrames == 0) swiWaitForVBlank();
	videoFrames--;
	
	printf("\x1b[13;1HOVERHEAD:  %d         ", videoFrames);
	
	timerStart(0, ClockDivider_1024, 0, NULL);
	bool ok = videoReadFrame();
	int dd = timerElapsed(0)/ (BUS_CLOCK / 100 / 60 / 1024);
	printf("\x1b[11;1HREAD TIME:  %d %%        ", dd);
	timerStop(0);
	
	if(!ok) return false;
	timerStart(0, ClockDivider_1024, 0, NULL);
	videoDecodeFrame();
	dd = timerElapsed(0)/ (BUS_CLOCK / 100 / 60 / 1024);
	printf("\x1b[12;1HDISP TIME:  %d %%        ", dd);
	timerStop(0);
	printf("\x1b[14;1HFRAME SIZE: %d        ", videoFrameLen);
	
	return true;
}
예제 #3
0
DBusAdaptorRecorder::DBusAdaptorRecorder(RecorderCore *recorder,
                                         DaemonMain *daemon)
    : QDBusAbstractAdaptor(daemon),
    _core(recorder)
{
    connect(_core, SIGNAL(elapsed(int)), this, SIGNAL(elapsed(int)));
    connect(_core, SIGNAL(timer(QString, QString)), this, SIGNAL(timer(QString, QString)));
    connect(_core, SIGNAL(timerStop()), this, SIGNAL(timerStop()));
}
예제 #4
0
int main()
{
	consoleDemoInit();

	uint ticks = 0;
	TimerStates state = timerState_Stop;
	int down = keysDown();

	while(!(down & KEY_START))
	{
		swiWaitForVBlank();
		consoleClear();
		scanKeys();
		down = keysDown();

		if(state == timerState_Running)
		{
			ticks += timerElapsed(0);
		}

		if(down & KEY_A)
		{
			if(state == timerState_Stop)
			{
				timerStart(0, ClockDivider_1024, 0, NULL);
				state = timerState_Running;
			}
			else if(state == timerState_Pause)
			{
				timerUnpause(0);
				state = timerState_Running;
			}
			else if(state == timerState_Running)
			{
				ticks += timerPause(0);
				state = timerState_Pause;
			}
		}
		else if(down & KEY_B)
		{
			timerStop(0);
			ticks = 0;
			state = timerState_Stop;
		}

		iprintf("Press A to start and pause the \ntimer, B to clear the timer \nand start to quit the program.\n\n");
		iprintf("ticks:  %u\n", ticks);
		iprintf("second: %u:%u\n", ticks/TIMER_SPEED, ((ticks%TIMER_SPEED)*1000) /TIMER_SPEED);
	}

	if(state != timerState_Stop)
	{
		timerStop(0);
	}

	return 0;
}
예제 #5
0
// Main method
int main(int argc, char* argv[]) {
  int N;
  double elapsedTime;

  // checking parameters
  if (argc != 2 && argc != 4) {
    printf("Parameters: <N> [<fileA> <fileB>]\n");
    return 1;
  }
  N = atoi(argv[1]);
  initMatrixes(N);

  // reading files (optional)
  if(argc == 4){
    readMatrixFile(A,N,argv[2]);
    readMatrixFile(B,N,argv[3]);
  } else {
    // Otherwise, generate two random matrix.
    for (int i=0; i<N; i++) {
      for (int j=0; j<N; j++) {
	A[i][j] = rand() % 5;
	B[i][j] = rand() % 5;
      }
    }
  }

  // Do simple multiplication and time it.
  timerStart();
  simpleMM(N);
  printf("Simple MM took %ld ms\n", timerStop());

  // Do strassen multiplication and time it.
  timerStart();
  strassenMM(N);
  printf("Strassen MM took %ld ms\n", timerStop());

  if (compareMatrix(C, R, N) != 0) {
    if (N < 20) {
      printf("\n\n------- MATRIX C\n");
      printMatrix(C,N);
      printf("\n------- MATRIX R\n");
      printMatrix(R,N);
    }
    printf("Matrix C doesn't match Matrix R, if N < 20 they will be printed above.\n");
  }

  // stopping timer
  
  cleanup();
  return 0;
}
/* Main function */
int main(int argc, char** argv){
	char* trainingFile, * trainingTargetFile, * testingFile;
	double duration = 0;

	verbose = 0;

	if(getenv("VERBOSE") != 0)
	{
		verbose = atoi(getenv("VERBOSE"));
	}

	/* read num inputs/outputs nodes */
	numInputNodes = atoi(argv[1]);

	numOutputNodes = atoi(argv[2]);

	numTrainingSamples = atoi(argv[3]);

	numTestSamples = atoi(argv[4]);

	/* read the number of Hidden layers in net */
	numHiddenLayers = atoi(argv[5]);

	neuronsPerLayer = atoi(argv[6]);

	/* read learning rate */
	learningRate = atof(argv[7]);

	/* read testing data file */
	testingFile = argv[8];

	/* read training data file */
	trainingFile = argv[9];

	/* read training target data  */
	trainingTargetFile = argv[10];

	/* initialize the neural network */
	InitNeuralNet();
	InitSamples(numTrainingSamples, numTestSamples);

	ReadFile(trainingFile, numInputNodes, numTrainingSamples, trainingSamples);
	ReadFile(trainingTargetFile, numOutputNodes, numTrainingSamples, trainingTargets);
	ReadFile(testingFile, numInputNodes, numTestSamples, testSamples);


	/* train the neural network */
	timerStart();

	Train();

	duration = timerStop();
	printf("Duration: %f seconds\n", (duration));

	Test();

	cleanUp();

	return 0;
}
예제 #7
0
파일: progress.c 프로젝트: dukesrg/rxTools
uint_fast8_t progressSetPos(uintmax_t pos) {
	statusDrawStart();
	uint32_t timeleft = 0;
	if ((pos += progress_offset) >= progress_posmax) {
		pos = progress_posmax;
		timerStop();
		wcscpy(status_value, lang(S_COMPLETED));
		status_features |= STATUS_FINISHED;
	}
	if (pos != progress_pos || !pos) {
		if ((progress_pos = pos) && pos) {
			timeleft = timerGet();
			timeleft = progress_posmax * timeleft / progress_pos - timeleft;
		}
		DrawProgress(progress_screen, &progress_rect, progress_frame, progress_done, progress_back, progress_textcolor, progress_fontsize, progress_posmax, progress_pos, timeleft);
	}
	if (pos != progress_posmax && status_features & STATUS_CANCELABLE && GetInput() & keys[KEY_B].mask) {
		wcscpy(status_value, lang(S_CANCELED));
		status_features |= STATUS_WAIT | STATUS_FINISHED | STATUS_FAILED;
	}
	if (status_features & STATUS_FINISHED) {
		wcscat(status_value, L" ");
		swprintf(status_value + wcslen(status_value), _MAX_LFN + 1, lang(SF2_PRESS_BUTTON_ACTION), lang(S_ANY_BUTTON), lang(S_CONTINUE));
	}
	DrawStringRect(&bottomScreen, status_value, &style.activityStatusRect, style.activityColor, style.activityStatusAlign, 16);
	statusDrawFinish();
	if (status_features & STATUS_WAIT && status_features & STATUS_FINISHED)
		InputWait();
	return !(status_features & STATUS_FAILED);
}
예제 #8
0
void videoStop()
{
	fclose(videoFile);
	videoFile = NULL; //just in case :P
	timerStop(3);
	videoPlaying = false;
}
예제 #9
0
int IndexDbLevelDb::insert_overriden_value(const string& usr, const string& name, const string& filename, int line, int col, const string& usrOverrider, int isDef)
{
    timerResume(TIMER_INS_OVERRIDEN);
    //printf("overriden: %s, %s, %s, line=%d, col=%d\n", usr.c_str(), filename.c_str(), name.c_str(), line, col);
    FileContext& fctx = m_fileContextMap[filename];

    int nameId = fctx.m_nameIdTbl.GetId(name);
    int usrId = fctx.m_usrIdTbl.GetId(usr);
    int usrIdOverrider = fctx.m_usrIdTbl.GetId(usrOverrider);
    // usrId -> decl info
    encItemInfo(m_CharBuff1, sizeof(m_CharBuff1), nameId, line, col);
    if(!fctx.m_usrId2overrideeMap[usrId].empty()) {
        fctx.m_usrId2overrideeMap[usrId].append(string(",") + string(m_CharBuff1));
    }
    else {
        fctx.m_usrId2overrideeMap[usrId] = string(m_CharBuff1);
    }

    fctx.m_usrId2overriderMap[usrIdOverrider][usrId] = 0;

    if(!usr.empty()) {
        m_usr2overriderFileMap[usr].push_back(filename);
    }
    // pos -> usr
    fctx.m_positition2usrList[Position(line, col)][Token(name, usrIdOverrider)] = 1;

    timerStop(TIMER_INS_OVERRIDEN);
    return 0;
}
예제 #10
0
void SIMClientSocket::slotError(int err)
{
    if (err)
        log(L_DEBUG, "Slot error %u", err);
    timerStop();
    if (notify) notify->error_state(I18N_NOOP("Socket error"));
}
예제 #11
0
void SIMClientSocket::slotConnected()
{
    log(L_DEBUG, "Connected");
    timerStop();
    if (notify) notify->connect_ready();
    getSocketFactory()->setActive(true);
}
예제 #12
0
int IndexDbLevelDb::insert_decl_value(const string& usr, const string& filename, const string& name, int line, int col, int isDef)
{
    FileContext& fctx = m_fileContextMap[filename];

    //printf("DECL: %s, %s, %d, %d, %d\n", usr.c_str(), filename.c_str(), line, col, isDef);
    if(m_finishedFiles.find(filename) != m_finishedFiles.end()) {
        // already done
        return 0;
    }
    timerResume(TIMER_INS_DECL);
    int nameId = fctx.m_nameIdTbl.GetId(name);
    int usrId = fctx.m_usrIdTbl.GetId(usr);
    if(isDef) {
        // usrId -> def info
        setKeyValueUsr2Def(m_CharBuff0, m_CharBuff1, sizeof(m_CharBuff0), nameId, line, col, usrId);
        fctx.m_declList.push_back(SsPair(m_CharBuff0, m_CharBuff1));
        if(!usr.empty()) {
            m_usr2defineFileMap[usr].push_back(filename);
        }
    }
    else {
        // usrId -> decl info
        setKeyValueUsr2Decl(m_CharBuff0, m_CharBuff1, sizeof(m_CharBuff0), nameId, line, col, usrId);
        fctx.m_declList.push_back(SsPair(m_CharBuff0, m_CharBuff1));
    }

    // pos -> usr
    fctx.m_positition2usrList[Position(line, col)][Token(name, usrId)] = 1;
    timerStop(TIMER_INS_DECL);
    return 0;
}
예제 #13
0
void UserInterface::stateInit(void)
{
    FastLED.clear(true);
    timerStop();
    Display::blank();

    if (!Display::isAwake())
        Display::wake();

    switch (_ui_state)
    {
        case UI_STATE__COUNT:
            _count = 0;
            Display::count(_total_count);
            break;

        case UI_STATE__SET:
            _minutes = _default_minutes;
            Display::time(0, _default_minutes);
            break;

        case UI_STATE__TIMER:
            _timer_state = TIMER_STATE__INIT;
            _timer_pause = 1;
            Display::time(0, _minutes);
            break;

        case UI_STATE__PASS:
            break;
    }
}
예제 #14
0
void GLWindow::setFrame(int pos) {

    if (pos == slider->maximum()) {

        timerStop();
    }

    widget->setFrame(pos);
}
예제 #15
0
int IndexDbLevelDb::insert_ref_value(const string& usr, const string& filename, const string& name, int line, int col)
{
    FileContext& fctx = m_fileContextMap[filename];

    //printf("REF: %s, %s, %s, %d, %d\n", usr.c_str(), filename.c_str(), name.c_str(), line, col);

    if(m_finishedFiles.find(filename) != m_finishedFiles.end()) {
        // already done
        return 0;
    }
    timerResume(TIMER_INS_REF);

#ifdef TIMER
    m_timers[TIMER_INS_REF_1].resume();
#endif
    int nameId = fctx.m_nameIdTbl.GetId(name);
    int usrId = fctx.m_usrIdTbl.GetId(usr);
    encItemInfo(m_CharBuff0, sizeof(m_CharBuff0), nameId, line, col);
    {
        IsMap& mapRef = fctx.m_usrId2refMap;
        auto itr = mapRef.find(usrId);
        if(itr == mapRef.end()){ 
            mapRef[usrId] = string(m_CharBuff0);
        }
        else {
            itr->second.append(string(",") + m_CharBuff0);
        }
    }

    if(!usr.empty()) {
        m_usr2referenceFileMap[usr].push_back(filename);
    }
#ifdef TIMER
    m_timers[TIMER_INS_REF_1].stop();
#endif

    // pos -> usr
    timerResume(TIMER_INS_REF_2);
    fctx.m_positition2usrList[Position(line, col)][Token(name, usrId)] = 1;
    timerStop(TIMER_INS_REF_2);
    timerStop(TIMER_INS_REF);
    return 0;
}
예제 #16
0
JNIEXPORT void JNICALL Java_com_yichou_test_jni_MainActivity_exit(JNIEnv * env, jobject self)
{
	char *msg;

	timerStop();
	pthread_join(pid, (void **)&msg);
	LOGD("pthread_join finish, msg=%s", msg);
	delete_queue(mQueue);

	mHandler->exit();
}
void Control::onStatusChanged(bool s)
{
    switch(s){
    case true:
        timerStart();
        break;
    case false:
        timerStop();
        break;
    }
}
예제 #18
0
void GLWindow::toggleAnimationState() {

    if (timer->isActive()) {

        timerStop();
    }
    else {

        timerStart();
    }
}
int main() {
  // Example 1 [-1,1]
  a = -1.0;
  b = 1.0;
  n = 1000000000;
  int current_number_of_threads[3] = {2, 50, 100};
  pthread_mutex_init(&approx_lock,NULL);
  
  int i = 0;
  for (i = 0; i<3; i++) {
     approx = 0;
     thread_amount = current_number_of_threadsi[i];
     printf("\nRan with %d threads\n", thread_amount);
     
     timerStart();
     run_threads();
     
     printf("Took %ld ms\n", timerStop());
     printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, NEG_1_TO_POS_1, approx);
  }
  
  
  // Example 2 [0,10]
  a = 0.0;
  b = 10.0;
  n = 1000000000;
  int i = 0;
  for (i = 0; i<3; i++) {
     approx = 0;
     thread_amount = current_number_of_threadsi[i];
     printf("\nRan with %d threads\n", thread_amount);
     
     timerStart();
     run_threads();
     
     printf("Took %ld ms\n", timerStop());
     printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, NEG_1_TO_POS_1, approx);
  }
  pthread_mutex_destroy(&approx_lock);
  return 0;
}
예제 #20
0
void SIMClientSocket::slotConnectionClosed()
{
    log(L_WARN, "Connection closed");
    timerStop();
    if (notify)
        notify->error_state(I18N_NOOP("Connection closed"));
#ifdef WIN32
    bool bState;
    if (get_connection_state(bState) && !bState)
        getSocketFactory()->setActive(false);
#endif
}
int main() {
  // Example 1 [-1,1]
  a = -1.0;
  b = 1.0;
  n = 1000;
  timerStart();
  trap();
  printf("Took %ld ms\n", timerStop());
  printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, NEG_1_TO_POS_1, approx);

  // Example 2 [0,10]
  a = 0.0;
  b = 10.0;
  n = 1000;
  timerStart();
  trap();
  printf("Took %ld ms\n", timerStop());
  printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, ZERO_TO_POS_10, approx);

  return 0;
}
예제 #22
0
void Remote::event()
{
	switch(bt.event)
	{
		case BT_EVENT_DISCONNECT:
			connected = 0;
			break;

		case BT_EVENT_CONNECT:
			connected = 1;
			break;

		case BT_EVENT_DATA:
			switch(bt.dataId)
			{
				case REMOTE_STATUS:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) memcpy(&status, bt.data, bt.dataSize);
					if(bt.dataType == REMOTE_TYPE_SET) memcpy(&status, bt.data, bt.dataSize);
					break;
				case REMOTE_PROGRAM:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) memcpy(&current, bt.data, bt.dataSize);
					if(bt.dataType == REMOTE_TYPE_SET)
					{
						memcpy((void*)&timer.current, bt.data, bt.dataSize);
						menu.refresh();
					}
					break;
				case REMOTE_BATTERY:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) memcpy(&battery, bt.data, 1);
					if(bt.dataType == REMOTE_TYPE_SET) memcpy(&battery, bt.data, 1);
					break;
				case REMOTE_START:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(timer.running ? REMOTE_START : REMOTE_STOP, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) running = 1;
					if(bt.dataType == REMOTE_TYPE_SET) runHandler(FR_KEY, 1);
					break;
				case REMOTE_STOP:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(timer.running ? REMOTE_START : REMOTE_STOP, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) running = 0;
					if(bt.dataType == REMOTE_TYPE_SET) timerStop(FR_KEY, 1);
					break;
				default:
					return;
			}
			bt.event = BT_EVENT_NULL;
			break;
	}
	requestActive = 0;
}
예제 #23
0
//------------------------------------------------------------------------------
void appService(Application *app)
{
    if(asicReportValid())
    {
        uint32_t nonce = asicGetNonce();
        uint32_t nonce_reversed = 0;

        timerStop(&app->work_timer);

        asicStop();
        asicResetSpi();

        app->state.state = STATE_RESET;

        SPCR |= _BV(SPIE);

        nonce_reversed |= nonce & 0xFF;
        nonce >>= 8;
        nonce_reversed <<= 8;
        nonce_reversed |= nonce & 0xFF;
        nonce >>= 8;
        nonce_reversed <<= 8;
        nonce_reversed |= nonce & 0xFF;
        nonce >>= 8;
        nonce_reversed <<= 8;
        nonce_reversed |= nonce & 0xFF;

        nonce_reversed = nonce_reversed - 0xC0;
        app->state.nonce = nonce_reversed;
        app->state.nonce_valid = 1;

        sendCmdReply(app, 'S', (uint8_t *)&app->state, sizeof(State));
    }

    if(timerExpired(&app->work_timer))
    {
        asicStop();
        asicResetSpi();
        app->state.state = STATE_RESET;

        app->state.nonce = 0;
        app->state.nonce_valid = 0;
        sendCmdReply(app, 'S', (uint8_t *)&app->state, sizeof(State));
    }
}
예제 #24
0
void SIMClientSocket::resolveReady(unsigned long addr, const char *_host)
{
    if (strcmp(_host, host.c_str())) return;
    if (addr == INADDR_NONE){
        if (notify) notify->error_state(I18N_NOOP("Can't resolve host"));
        return;
    }
    if (notify)
        notify->resolve_ready(addr);
    in_addr a;
    a.s_addr = addr;
    host = inet_ntoa(a);
    log(L_DEBUG, "Resolve ready %s", host.c_str());
    timerStop();
    timer = new QTimer(this);
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
    timer->start(CONNECT_TIMEOUT * 1000);
    sock->connectToHost(host.c_str(), port);
}
예제 #25
0
/*
this function manages WR timeouts, each main state (except IDLE) has timeout
timeouts are "automatically" started/stopped on the transition of main states
by this function
here we also count the number of attempt on the same state, if the retry number
exccedded, we exit WR FSM, no WRPTP, sorry
*/
void wrTimetoutManage(UInteger8 enteringState, UInteger8 exitingState, RunTimeOpts *rtOpts, PtpPortDS *ptpPortDS)
{

  /*
    checking if the state is repeated,
    repeated state means that there was timeout
    so we need to increase repetition counter
  */
  if(enteringState != exitingState)
    ptpPortDS->currentWRstateCnt = 0;
  else
    ptpPortDS->currentWRstateCnt++;

  /*stop time from the state you are leaving (except IDLE)*/
  if(exitingState != WRS_IDLE)
    timerStop(&ptpPortDS->wrTimers[exitingState]);

  /*start timer in the state you are entering (except IDLE) */
  if(enteringState != WRS_IDLE)
    timerStart(&ptpPortDS->wrTimers[enteringState], ptpPortDS->wrTimeouts[enteringState]);
}
예제 #26
0
void __attribute__ ((interrupt,no_auto_psv)) _T1Interrupt ( void )
{
    _T1IF = 0;
    if ( timerValue > 0 )
    { /* reload */
        if ( timerValue < TIMER_MAX_VALUE )
	{
  	    u32 milliSec = ( ((u32)timerValue) * clkCyclesPerMSec ) / 256; /* prescaler used */
            PR1 = (u16)milliSec;  /* load timer 1 compare register */
	    timerValue = 0; /* end of outer loop */
	}    
	else /* not the last time we let timer overflow */
	{
	    timerValue -= TIMER_MAX_VALUE;
	} 
    }
    else /* timer has expired */
    {
        timerStop( );
    }
}
예제 #27
0
/*Local clock is synchronized to Ebest Table 16 (9.3.5) of the spec*/
void s1(MsgHeader *header,MsgAnnounce *announce,PtpClock *ptpClock, RunTimeOpts *rtOpts)
{

	Boolean previousLeap59 = FALSE, previousLeap61 = FALSE;
	Integer16 previousUtcOffset = 0;

	if (ptpClock->portState == PTP_SLAVE) {
		previousLeap59 = ptpClock->leap59;
		previousLeap61 = ptpClock->leap61;
		previousUtcOffset = ptpClock->currentUtcOffset;
	}

	/* Current DS */
	ptpClock->stepsRemoved = announce->stepsRemoved + 1;

	/* Parent DS */
	copyClockIdentity(ptpClock->parentPortIdentity.clockIdentity,
	       header->sourcePortIdentity.clockIdentity);
	ptpClock->parentPortIdentity.portNumber = 
		header->sourcePortIdentity.portNumber;
	copyClockIdentity(ptpClock->grandmasterIdentity,
			announce->grandmasterIdentity);
	ptpClock->grandmasterClockQuality.clockAccuracy = 
		announce->grandmasterClockQuality.clockAccuracy;
	ptpClock->grandmasterClockQuality.clockClass = 
		announce->grandmasterClockQuality.clockClass;
	ptpClock->grandmasterClockQuality.offsetScaledLogVariance = 
		announce->grandmasterClockQuality.offsetScaledLogVariance;
	ptpClock->grandmasterPriority1 = announce->grandmasterPriority1;
	ptpClock->grandmasterPriority2 = announce->grandmasterPriority2;

	/* Timeproperties DS */
	ptpClock->currentUtcOffset = announce->currentUtcOffset;

        /* "Valid" is bit 2 in second octet of flagfield */
        ptpClock->currentUtcOffsetValid = IS_SET(header->flagField1, UTCV);

	/* set PTP_PASSIVE-specific state */
	p1(ptpClock, rtOpts);

	/* only set leap state in slave mode */
	if (ptpClock->portState == PTP_SLAVE) {
		ptpClock->leap59 = IS_SET(header->flagField1, LI59);
		ptpClock->leap61 = IS_SET(header->flagField1, LI61);
	}

        ptpClock->timeTraceable = IS_SET(header->flagField1, TTRA);
        ptpClock->frequencyTraceable = IS_SET(header->flagField1, FTRA);
        ptpClock->ptpTimescale = IS_SET(header->flagField1, PTPT);
        ptpClock->timeSource = announce->timeSource;

#if defined(MOD_TAI) &&  NTP_API == 4
	/*
	 * update kernel TAI offset, but only if timescale is
	 * PTP not ARB - spec section 7.2
	 */
        if (ptpClock->ptpTimescale &&
            (ptpClock->currentUtcOffset != previousUtcOffset)) {
		setKernelUtcOffset(ptpClock->currentUtcOffset);
        }
#endif /* MOD_TAI */

	/* Leap second handling */

        if (ptpClock->portState == PTP_SLAVE) {
		if(ptpClock->leap59 && ptpClock->leap61) {
			ERROR("Both Leap59 and Leap61 flags set!\n");
			toState(PTP_FAULTY, rtOpts, ptpClock);
			return;
		}

		/* one of the leap second flags has suddenly been unset */
		if(ptpClock->leapSecondPending && 
		    !ptpClock->leapSecondInProgress &&
		    ((previousLeap59 != ptpClock->leap59) || 
		     (previousLeap61 != ptpClock->leap61))) {
			WARNING("=== Leap second event aborted by GM!");
			ptpClock->leapSecondPending = FALSE;
			ptpClock->leapSecondInProgress = FALSE;
			timerStop(LEAP_SECOND_PAUSE_TIMER, ptpClock->itimer);
      /** FIXME dumblob */
#if !defined(__APPLE__) && !defined(__QNXNTO__)
			unsetTimexFlags(STA_INS | STA_DEL,TRUE);
#endif /* apple */
		}

		/*
		 * one of the leap second flags has been set
		 * or flags are lit but we have no event pending
		 */
		if( (ptpClock->leap59 || ptpClock->leap61) && (
		    (!ptpClock->leapSecondPending && 
		    !ptpClock->leapSecondInProgress ) ||
		    ((!previousLeap59 && ptpClock->leap59) ||
		    (!previousLeap61 && ptpClock->leap61)))) {
#if !defined(__APPLE__) && !defined(__QNXNTO__)
			WARNING("=== Leap second pending! Setting kernel to %s "
				"one second at midnight\n",
				ptpClock->leap61 ? "add" : "delete");
		    if (!checkTimexFlags(ptpClock->leap61 ? STA_INS : STA_DEL)) {
			    unsetTimexFlags(ptpClock->leap61 ? STA_DEL : STA_INS,
					    TRUE);
			    setTimexFlags(ptpClock->leap61 ? STA_INS : STA_DEL,
					  FALSE);
		    }
#else
			WARNING("=== Leap second pending! No kernel leap second "
				"API support - expect a clock jump at "
				"midnight!\n");
#endif /* apple */
			/* only set the flag, the rest happens in doState() */
			ptpClock->leapSecondPending = TRUE;
		}

		if((previousUtcOffset != ptpClock->currentUtcOffset) && 
		   !ptpClock->leapSecondPending && 
		   !ptpClock->leapSecondInProgress ) {
			WARNING("=== UTC offset changed from %d to %d with "
				"no leap second pending!\n",
				previousUtcOffset, ptpClock->currentUtcOffset);
		} else if( previousUtcOffset != ptpClock->currentUtcOffset) {
			WARNING("=== UTC offset changed from %d to %d\n",
				previousUtcOffset,ptpClock->currentUtcOffset);
		}
	}
}
예제 #28
0
void CompassPort::revert()// метод для сброса датчика
{
    emit timerStop();// останавливаем прием курса
    // формируем сообщения для сброса
    QByteArray dataForWrite;
    dataForWrite.insert(0,0x0d);
    dataForWrite.insert(1,0x0a);
    dataForWrite.insert(2,0x7e);
    dataForWrite.insert(3,0x72);
    dataForWrite.insert(4,0x01);
    dataForWrite.insert(5,0x04);
    dataForWrite.insert(6,0x0c);
    bool receivedMsg = false;
    //----------------------

    if(portSensor->isOpen())
    {

        portSensor->write(dataForWrite,7);// пишем в порт сообщение о сбросе
        if(!portSensor->waitForBytesWritten(1000))
        {
        }
        while(!receivedMsg)// ждем получения сообщения о сбросе
        {

            if(portSensor->isOpen() && portSensor->waitForReadyRead(1000))
            {

                QString data;
                QByteArray ByteArray;
                qint64 byteAvail = portSensor->bytesAvailable();
                qApp->processEvents();
                if(byteAvail >=19)
                {
                    ByteArray = portSensor->readAll();
                    data = data.fromLocal8Bit(ByteArray).trimmed();
                    if(ByteArray[3]=='r'&& ByteArray[0]=='\r' && ByteArray[1]=='\n' && ByteArray[2]=='~')
                    {
                        QBitArray bitdata(152),one_byte(8);
                        for(int i = 0,j; i < 152; ++i)
                        {
                            j=i/8;
                            if(j<=19)
                                bitdata[i] = ByteArray[j] & (1 << i%8);
                            else
                                break;
                        }
                        for(int i=40,j=7;i<48 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        if(toDecInt(one_byte)==0)
                        {
                            //settings->setLabel("Compass Compensation Off");
                            //emit revertStatusChanged("Датчик сброшен");
                        }
                        else if(toDecInt(one_byte)==1)
                        {
                            //settings->setLabel("Compass Compensation Data Collection");
                            //emit revertStatusChanged("Сбор данных...");
                        }
                        else if(toDecInt(one_byte)==2)
                        {
                            //settings->setLabel("Compass Compensation Computation in Progress");
                            //emit revertStatusChanged("Вычисление...");
                        }
                        else if(toDecInt(one_byte)==3)
                        {
                            //settings->setLabel("Compass Compensation Procedure Abort");
                           // emit revertStatusChanged("Процедура прервана");
                        }
                        for(int i=48,j=7;i<56 && j>=0;i++,j--){one_byte[j]=bitdata[i];}

                        qApp->processEvents();
                        receivedMsg = true;// сообщение о сбросе получено
                    }
                }
                //запрашиваем состояние сброса
                dataForWrite.insert(5,0x02);
                dataForWrite.insert(6,0x0a);
                portSensor->write(dataForWrite,7);
                if(!portSensor->waitForBytesWritten(1000))
                {
                }
                //----------------------
            }
        }
    }
    emit timerStart(10);// продолжаем получение курса
}
예제 #29
0
void Remote::event()
{
	switch(bt.event)
	{
		case BT_EVENT_DISCONNECT:
			notify.unWatch(&remote_notify); // stop all active notifications
			//debug(STR("REMOTE::EVENT: Disconnected\r\n"));
			connected = 0;
			break;

		case BT_EVENT_CONNECT:
			connected = 1;
			//debug(STR("REMOTE::EVENT: Connected\r\n"));
			request(REMOTE_MODEL);
			break;

		case BT_EVENT_DATA:
			switch(bt.dataId)
			{
				case REMOTE_STATUS:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND && bt.dataSize == sizeof(timer_status)) memcpy(&status, bt.data, bt.dataSize);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_STATUS, (void *)&timer.status, sizeof(timer.status), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_STATUS, &remote_notify);
					break;
				case REMOTE_PROGRAM:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND && bt.dataSize == sizeof(program)) memcpy(&current, bt.data, bt.dataSize);
					if(bt.dataType == REMOTE_TYPE_SET && bt.dataSize == sizeof(program))
					{
						memcpy((void*)&timer.current, bt.data, bt.dataSize);
						menu.refresh();
					}
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_PROGRAM, (void *)&timer.current, sizeof(timer.current), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_PROGRAM, &remote_notify);
					break;
				case REMOTE_BATTERY:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) memcpy(&battery, bt.data, bt.dataSize);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_BATTERY, (void *)&battery_percent, sizeof(battery_percent), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_BATTERY, &remote_notify);
					break;
				case REMOTE_START:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(timer.running ? REMOTE_START : REMOTE_STOP, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) running = 1;
					if(bt.dataType == REMOTE_TYPE_SET) runHandler(FR_KEY, 1);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_START, (void *)&timer.running, sizeof(timer.running), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_START, &remote_notify);
					break;
				case REMOTE_STOP:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(timer.running ? REMOTE_START : REMOTE_STOP, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) running = 0;
					if(bt.dataType == REMOTE_TYPE_SET) timerStop(FR_KEY, 1);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_START, (void *)&timer.running, sizeof(timer.running), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_START, &remote_notify);
					break;
				case REMOTE_BULB_START:
					if(bt.dataType == REMOTE_TYPE_SET) timer.bulbStart();
					break;
				case REMOTE_BULB_END:
					if(bt.dataType == REMOTE_TYPE_SET) timer.bulbEnd();
					break;
				case REMOTE_CAPTURE:
					if(bt.dataType == REMOTE_TYPE_SET) timer.capture();
					break;
				case REMOTE_MODEL:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(REMOTE_MODEL, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SEND) memcpy(&model, bt.data, bt.dataSize);
					break;
				case REMOTE_FIRMWARE:
				case REMOTE_BT_FW_VERSION:
				case REMOTE_PROTOCOL_VERSION:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					break;
				case REMOTE_CAMERA_FPS:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_CAMERA_FPS, (void *)&conf.cameraFPS, sizeof(conf.cameraFPS), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_CAMERA_FPS, &remote_notify);
					break;
				case REMOTE_CAMERA_MAKE:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_CAMERA_MAKE, (void *)&conf.cameraMake, sizeof(conf.cameraMake), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_CAMERA_MAKE, &remote_notify);
					break;
				case REMOTE_DEBUG:
					if(bt.dataType == REMOTE_TYPE_SEND)
					{
						bt.data[bt.dataSize] = 0;
						debug_remote(bt.data);
					}
					break;
				case REMOTE_ISO:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SET && bt.dataSize == sizeof(uint8_t))
					{
						uint8_t tmp;
						memcpy((void*)&tmp, bt.data, bt.dataSize);
						camera.setISO(tmp);
					}
					break;
				case REMOTE_APERTURE:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SET && bt.dataSize == sizeof(uint8_t))
					{
						uint8_t tmp;
						memcpy((void*)&tmp, bt.data, bt.dataSize);
						camera.setAperture(tmp);
					}
					break;
				case REMOTE_SHUTTER:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_SET && bt.dataSize == sizeof(uint8_t))
					{
						uint8_t tmp;
						memcpy((void*)&tmp, bt.data, bt.dataSize);
						camera.setShutter(tmp);
					}
					break;
				case REMOTE_THUMBNAIL:
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					break;
				case REMOTE_VIDEO:
					if(bt.dataType == REMOTE_TYPE_SET && bt.dataSize == sizeof(uint8_t))
					{
						uint8_t tmp;
						memcpy((void*)&tmp, bt.data, bt.dataSize);
						if(tmp) camera.videoStart(); else camera.videoStop();
					}
					if(bt.dataType == REMOTE_TYPE_SEND && bt.dataSize == sizeof(uint8_t))
					{
						uint8_t tmp;
						memcpy((void*)&tmp, bt.data, bt.dataSize);
						if(tmp) recording = true; else recording = false;
					}
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_VIDEO, (void *)&camera.recording, sizeof(camera.recording), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_VIDEO, &remote_notify);
					break;
				case REMOTE_LIVEVIEW:
					if(bt.dataType == REMOTE_TYPE_SET && bt.dataSize == sizeof(uint8_t))
					{
						uint8_t tmp;
						memcpy((void*)&tmp, bt.data, bt.dataSize);
						if(tmp) camera.liveView(tmp);
					}
					if(bt.dataType == REMOTE_TYPE_SEND && bt.dataSize == sizeof(uint8_t))
					{
						uint8_t tmp;
						memcpy((void*)&tmp, bt.data, bt.dataSize);
						if(tmp) modeLiveView = true; else modeLiveView = false;
					}
					if(bt.dataType == REMOTE_TYPE_REQUEST) send(bt.dataId, REMOTE_TYPE_SEND);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_WATCH) notify.watch(REMOTE_LIVEVIEW, (void *)&camera.modeLiveView, sizeof(camera.modeLiveView), &remote_notify);
					if(bt.dataType == REMOTE_TYPE_NOTIFY_UNWATCH) notify.unWatch(REMOTE_LIVEVIEW, &remote_notify);
					break;
				default:
					return;
			}
			bt.event = BT_EVENT_NULL;
			break;
	}
	requestActive = 0;
}
예제 #30
0
void CompassPort::initComp()//инициализация компенсации
{
    emit timerStop();// останавливаем прием курса
    emit compStarted();// сообщаем о начале компенсации
    m_compInProgress = true;
    // формируем сообщение для датчика о начале компенсации
    QByteArray dataForWrite;
    dataForWrite.insert(0,0x0d);
    dataForWrite.insert(1,0x0a);
    dataForWrite.insert(2,0x7e);
    dataForWrite.insert(3,0x72);
    dataForWrite.insert(4,0x01);
    dataForWrite.insert(5,0x01);
    dataForWrite.insert(6,0x09);
    //--------------------
    if(portSensor->isOpen())// проверка открыт ли порт
    {

        portSensor->write(dataForWrite,7);// передача сообщения датчику для начала компенсации
        if(!portSensor->waitForBytesWritten(1000))
        {
        }
        while(m_compInProgress)// пока калибровка не закончится
        {

            qApp->processEvents();// магическая строчка чтобы не тупили пользовательские интерфейсы
            if(portSensor->isOpen() && portSensor->waitForReadyRead(1000))// ждем данных
            {
                QString data;
                QByteArray ByteArray;
                qint64 byteAvail = portSensor->bytesAvailable();
                qApp->processEvents();
                if(byteAvail >=19)// буфер наполнился
                {
                    ByteArray = portSensor->readAll();// читаем из порта
                    data = data.fromLocal8Bit(ByteArray).trimmed();
                    if(ByteArray[3]=='r'&& ByteArray[0]=='\r' && ByteArray[1]=='\n' && ByteArray[2]=='~')// если сообщение нужное нам( смотри даташит)
                    {
                        //формирование массива бит для парсинга
                        QBitArray bitdata(152),one_byte(8);
                        for(int i = 0,j; i < 152; ++i)
                        {
                            j=i/8;
                            if(j<=19)
                                bitdata[i] = ByteArray[j] & (1 << i%8);
                            else
                                break;
                        }
                        // парс сообщения о состоянии бинов
                        for(int i=56,j=7;i<64 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(7,toDecInt(one_byte));
                        emit dialCompProgressChanged(7,toDecInt(one_byte));
                        for(int i=64,j=7;i<72 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(6,toDecInt(one_byte));
                        emit dialCompProgressChanged(6,toDecInt(one_byte));
                        for(int i=72,j=7;i<80 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(5,toDecInt(one_byte));
                        emit dialCompProgressChanged(5,toDecInt(one_byte));
                        for(int i=80,j=7;i<88 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(4,toDecInt(one_byte));
                        emit dialCompProgressChanged(4,toDecInt(one_byte));
                        for(int i=88,j=7;i<96 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(3,toDecInt(one_byte));
                        emit dialCompProgressChanged(3,toDecInt(one_byte));
                        for(int i=96,j=7;i<104 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(2,toDecInt(one_byte));
                        emit dialCompProgressChanged(2,toDecInt(one_byte));
                        for(int i=104,j=7;i<112 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(1,toDecInt(one_byte));
                        emit dialCompProgressChanged(1,toDecInt(one_byte));
                        for(int i=112,j=7;i<120 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        //dial->setBar(0,toDecInt(one_byte));
                        emit dialCompProgressChanged(0,toDecInt(one_byte));
                        //---------------------------------------------------------
                        // состоние компенсации
                        for(int i=48,j=7;i<56 && j>=0;i++,j--){one_byte[j]=bitdata[i];}
                        if(toDecInt(one_byte)==1)
                        {
                            //dial->setLabel("Success");
                            emit dialCompStatusChanged("НОРМА");
                        }
                        else if(toDecInt(one_byte)==0)
                        {
                            //dial->setLabel("No error");
                            emit dialCompStatusChanged("");
                        }
                        else if(toDecInt(one_byte)==2)
                        {
                            //dial->setLabel("Compensation Already Started");
                            emit dialCompStatusChanged("");
                        }
                        else if(toDecInt(one_byte)==3)
                        {
                            //dial->setLabel("Compensation Not Started");
                            emit dialCompStatusChanged("ОТКАЗ");
                        }
                        else if(toDecInt(one_byte)==4)
                        {
                            //dial->setLabel("Compensation Timeout");
                            emit dialCompStatusChanged("ВРЕМЯ");
                        }
                        else if(toDecInt(one_byte)==5)
                        {
                            //dial->setLabel("Compensation Computation Failure");
                            emit dialCompStatusChanged("ОШИБКА");
                        }
                        else if(toDecInt(one_byte)==6)
                        {
                            //dial->setLabel("New Computed Parameters No Better");
                            emit dialCompStatusChanged("НОРМА");
                        }
                        else if(toDecInt(one_byte)==7)
                        {
                            //dial->setLabel("Flash Write Fail");
                            emit dialCompStatusChanged("ОТКАЗ");
                        }
                        //----------------------------
                        qApp->processEvents();
                    }

                }
                // посылаем сообщение для получения данных о калибровке
                dataForWrite.insert(5,0x02);
                dataForWrite.insert(6,0x0a);
                portSensor->write(dataForWrite,7);
                if(!portSensor->waitForBytesWritten(1000))
                {
                }
                //-----------------------
            }
        }
    }
    emit compFinished();// калибровка закончена
    emit timerStart(10);// продолжаем прием сообщений о курсе
    m_compInProgress = false;
}