Exemple #1
0
int main(){
    FILE *fileToPrint;
    fileToPrint = fopen("Solutions.out","w");

    /** Create Interface of Program */
    while(!Start){
        GameOver = false;
        system("CLS");
        Intro();

        Ask();

        int puzzle[SizeOfPuzzle][SizeOfPuzzle];
        int copy[SizeOfPuzzle][SizeOfPuzzle];
        int i, j;
        /** Here is generated the puzzle full with 0 */
        for(i = 0; i < SizeOfPuzzle; i++){
            for(j = 0; j < SizeOfPuzzle; j++){
                puzzle[i][j] = 0;
            }
        }
        while(!GameOver){
            system("CLS");

            Intro();
            AskSize(SizeOfPuzzle, puzzle);
            ChoseOptions();

            scanf("%d",&choice);

            switch(choice){
                case 1:
                    main();
                    break;
                case 2:
                    InsertNumberInPozitionChoice(puzzle, copy, SizeOfPuzzle);
                    break;
                case 3:
                    GenerateRandomPuzzle(puzzle, copy, fileToPrint, SizeOfPuzzle);
                    break;
                case 4:
                    SolvePuzzle(puzzle, fileToPrint, SizeOfPuzzle);
                    break;
                case 5:
                    Back(puzzle, copy, SizeOfPuzzle);
                    break;
                case 6:
                    GameOver = true;
                    Start = true;
                    break;
                default:
                    printf("\t\t Wrong choice try again :");
                    scanf("%d",&choice);
                    break;
            }
        }
    }

	return 0;
}
Exemple #2
0
void main()
{
	int mainChoice = 0;

	int whosWin = 3;

	srand((unsigned)time(NULL));

	while (1)//무한 루프
	{
		if (Intro() == 1)
			break;

		whosWin = OnTheGame();

		if (whosWin == 0)
			printf("\n딜러가 승리하였습니다!\n==============================\n\n");
		else if (whosWin == 1)
			printf("\n사용자가 승리하였습니다!\n==============================\n\n");
		else if (whosWin == 2)
			printf("\n무승부입니다!\n==============================\n\n");
	}



	return;
}
Exemple #3
0
void Game::Go(){
	//pWnd->ShowMouseCursor(false);

	//objeto para recibir eventos
	Event evt;

	//Inicializa los objetos del juego
	Init();
	
	if(pWnd->IsOpened())
	{
		Intro();
		ShowMenu();		
	}
	while(pWnd->IsOpened()){
		//procesar eventos
		while (pWnd->GetEvent(evt))
			ProcessEvent(evt);

		//procesar colisiones
		ProcessCollisions();
		
		//actualizar estados de objetos
		UpdateGame();
		
		pWnd->Clear();
		
		DrawGame();
		
		pWnd->Display();
	}
	StopMusic();	
}
Exemple #4
0
//===================================================================================
void __fastcall Hooked_PaintTraverse( PVOID pPanels, int edx, unsigned int vguiPanel, bool forceRepaint, bool allowForce )
{
	try
	{
		VMTManager& hook = VMTManager::GetHook(pPanels); //Get a pointer to the instance of your VMTManager with the function GetHook.
		hook.GetMethod<void(__thiscall*)(PVOID, unsigned int, bool, bool)>(gOffsets.iPaintTraverseOffset)(pPanels, vguiPanel, forceRepaint, allowForce); //Call the original.

		static unsigned int vguiMatSystemTopPanel;

		if (vguiMatSystemTopPanel == NULL)
		{
			const char* szName = gInts.Panels->GetName(vguiPanel);
			if( szName[0] == 'M' && szName[3] == 'S' ) //Look for MatSystemTopPanel without using slow operations like strcmp or strstr.
			{
				vguiMatSystemTopPanel = vguiPanel;
				Intro();
			}
		}
		
		if ( vguiMatSystemTopPanel == vguiPanel ) //If we're on MatSystemTopPanel, call our drawing code.
		{

			// TODO maybe make this the users decision??
			if( gInts.Engine->IsDrawingLoadingImage() || !gInts.Engine->IsInGame( ) || !gInts.Engine->IsConnected() || gInts.Engine->Con_IsVisible( ) || ( ( GetAsyncKeyState(VK_F12) || gInts.Engine->IsTakingScreenshot( ) ) ) )
			{
				return; //We don't want to draw at the menu.
			}

			////This section will be called when the player is not at the menu game and can see the screen or not taking a screenshot.
			//gInts.DrawManager->DrawString( (gScreenSize.iScreenWidth / 2) - 55, 200, gInts.DrawManager->dwGetTeamColor(3), "Welcome to Darkstorm"); //Remove this if you want.

			////Test ESP code.

			//CBaseEntity* pBaseLocalEnt = gInts.EntList->GetClientEntity(me);  //Grab the local player's entity.

			//if (pBaseLocalEnt == NULL) //Always check for null pointers.
			//	return;

			//Vector vecWorld, vecScreen; //Setup the Vectors.

			//pBaseLocalEnt->GetWorldSpaceCenter(vecWorld); //Get the center of the player.

			//if ( gInts.DrawManager->WorldToScreen(vecWorld, vecScreen) ) //If the player is visble.
			//{
			//	gInts.DrawManager->DrawString( vecScreen.x, vecScreen.y, 0xFFFFFFFF, "You" ); //Draw on the player.
			//}

			gLuaEngine->runPaintTraverseCallbacks( );

			for ( int i = 0; i < gInts.EntList->GetHighestEntityIndex( ); i++ )
			{
				gLuaEngine->runEntityLoopCallbacks( i );
			}
		}
	}
	catch(...)
	{
		Log::Fatal("Failed PaintTraverse");
	}
}
Exemple #5
0
int main()
{
    Intro();
    int input;
    int no;
    scanf("%d", &no);
 
 
    printf("\n옵션 1: 10진수\n옵션 2: 16진수\n\n");
    scanf("%d", &input);
 
 
    switch(input)
    {
    case 1 :
        printf("\n10진수를 선택하셨습니다.\n");
        printf("결과 : %d\n\n", no);
        break;
    case 2:
        printf("\n16진수를 선택하셨습니다.\n");
        printf("결과 : %x\n\n", no);
        break;
    default :
        printf("\n잘못된 선택을 하셨습니다.\n");
    }
 
 
    return 0;
}
void MyPS2Application::Update()
{
	// Tell DMAC to send previous graphics data to Graphics Synthesiser (GS)
	VIFDynamicDMA.Fire();
	
	// Read the control pad into data buffer
	pad_update(PAD_0);
	
	// Check for exit condition
	if((pad[0].buttons & PAD_START)&&(pad[0].buttons & PAD_SELECT)) quitting_ = true;

	// State Handler
	switch (game_state)
	{
	case INTRO:
		Intro();
		break;
	
	case MENU:
		Menu();
		break;
		
	case GAME:
		Game();
		break;
		
	case GAME_OVER:
		GameOver();
		break;
	}
	
	DSP0.HandleAudio();
	DSP1.HandleAudio();
}
Exemple #7
0
int WolfMain(int argc, char *argv[])
{
	WaitTick();			/* Wait for a system tick to go by */
	playstate = (exit_t)setjmp(ResetJmp);	
	NumberIndex = 36;	/* Force the score to redraw properly */
	IntermissionHack = FALSE;
	if (playstate) {
		goto DoGame;	/* Begin a new game or saved game */
	}
	JumpOK = TRUE;		/* Jump vector is VALID */
	FlushKeys();		/* Allow a system event */
	Intro();			/* Do the game intro */
	for (;;) {
		if (TitleScreen()) {		/* Show the game logo */
			StartSong(SongListPtr[0]);
			ClearTheScreen(BLACK);	/* Blank out the title page */
			BlastScreen();
			SetAPalette(rBlackPal);
			if (ChooseGameDiff()) {	/* Choose your difficulty */
				playstate = EX_NEWGAME;	/* Start a new game */
DoGame:
				FadeToBlack();		/* Fade the screen */
				StartGame();		/* Play the game */
			}
		}
		/* TODO: demos or whatever here */
	}
	
	return 0;
}
Exemple #8
0
void intro_display()
{
	    std::ifstream Art ("art.txt");
	    std::ifstream Intro("intro.txt");
	    displaytext(Art);
	    displaytext_delay(Intro);
	    Art.close();
	    Intro.close();
}
Exemple #9
0
int Game::Run()
{
	isRunning = true;
	Init();
#ifdef HAVE_CONSOLE
	Intro();
#endif
	Loop();

	return 0;
}
    void UpdateAI(const uint32 uiDiff)
    {
        if (m_uiIntroTimer <= uiDiff)
            Intro();
        else m_uiIntroTimer -= uiDiff;

        if (m_pInstance)
            if(m_pInstance->GetData(DATA_LICH_KING_EVENT) != NOT_STARTED)
            {
                me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
            }
    }
Exemple #11
0
int main() {

	PhoneBook phoneBook;
	Contacts contact;

	bool ProgramOn = true;
	int option;

	while (ProgramOn) {
		Intro();
		cin >> option;
		cout << endl;
		switch (option)
		{
		case 1:
			cout << "Insert contact data : \n ";
			contact.getData(phoneBook);
			phoneBook.contacts.push_back(contact);
			break;
		case 2: {
			string contactName;
			cout << "Insert contact name : ";
			cin >> contactName;

			if (checkIfExist(phoneBook, contactName) != -1) {
				phoneBook.contacts[checkIfExist(phoneBook, contactName)].showContact();
			}
			else {
				cout << "Contact " << contactName << " doesn't exist !\n";
			}
		}
			break;
		case 3: {
			string contactName;
			cout << "\n Contacts in phoneBook : "<< phoneBook.getContactNumbers() <<"\n";
			for (int i = 0; i < phoneBook.contacts.size(); i++)
			{
				cout << phoneBook.contacts[i].getContactName();
				cout << "\n\n";
			}
		}
			break;
		case 4:
			ProgramOn = false;
			break;
		default:
			cout << "Wrong option ! ";
			break;
		}
	}

	system("PAUSE");
}
Exemple #12
0
            void UpdateAI(const uint32 diff)
    	    {
    	        if (uiTimer <= diff)
                {
                    if (bIntro)
                        Intro();

                    if (bFinal)
                        Final();
                    
                    if (instance->GetBossState(DATA_UMBRA) == DONE)
                        bFinal = true;
                }
                else (uiTimer -= diff);
    	    }
    void UpdateAI(const uint32 uiDiff)
    {
		if (m_uiIntroTimer <= uiDiff)
                Intro();
		else m_uiIntroTimer -= uiDiff;

		if (m_pInstance && m_pInstance->GetData(DATA_LICH_KING_EVENT) == IN_PROGRESS || m_pInstance->GetData(DATA_LICH_KING_EVENT) == DONE)
		{
			me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
		}

		if (m_pInstance && m_pInstance->GetData(DATA_LICH_KING_EVENT) == NOT_STARTED)
		{
			me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
		}
    }
Exemple #14
0
int main(int argc, char* argv[])
{
	Intro(stdout);

	if(argc != 2)
	{
		printf("Usage: ratom name\n\n");
		return 1;
	}

	try
	{
		ks::NonLinKs ks(argv[1]);
		return ks.Run();
	}
	catch(std::exception& e)
	{
		printf("ERROR! %s\n", e.what());
		return 1;
	}
}
Exemple #15
0
int main(int argc, char **argv) 
{
	MK_InitLibraries();
	MK_LoadGfx();

	Intro();
	
	while(1)/// Infinite Loop ///
	{
		ExitForTheGame();
		Play_Music();
		switch(MenuIndex)
		{
			case 1: 
				MainMenu();
				break;
			case 2:
				InGame();
				break;
			case 3:
				SelectMenu();
				break;
			case 4:
				SelectSlot();
				break;
			case 5:
				CreatingMenu();
				break;
			case 6:
				SelectSlot2();
				break;
			case 7:
				DrawTitle();
				break;
		}
		ML_Refresh();
	} 
	return 0;
}
void main()
{
   int i;
   G();
   Intro();
   Background();
   DrawBoard();
   Marble(320,220,0);
   board[3][3]=0;
   Init();
   setcolor(0);
   for(i=0;i<=220;i++)
   {
   rectangle(0+i,0+i,640-i,480-i);
   delay(10);
   }
   for(i=0;i<=220;i++)
   {
   rectangle(100+i,100,540-i,380);
   delay(8);
   }
   closegraph();
   getch();
}
Exemple #17
0
int main(int argc, char *argv[])
{
#if CONFOPT_EMBED_NOUNDER == 1
    _qdgdf_embedded_tar_start = &binary_splumber_tar_start;
    _qdgdf_embedded_tar_end = &binary_splumber_tar_end;
#else
    _qdgdf_embedded_tar_start = &_binary_splumber_tar_start;
    _qdgdf_embedded_tar_end = &_binary_splumber_tar_end;
#endif

    if (argc >= 2 && *argv[1] == '3')
        _qdgdfv_scale = 3;

    GrxStartup();

    Intro();

    MainLoop();

    GrxShutdown();

    return (0);

}
    void UpdateAI(const uint32 diff)
    {
        if (bDefeat)
        {
            if (!bRagTele)
            {
                if (uiDefeatTimer <= diff)
                {
                    me->SetReactState(REACT_AGGRESSIVE);
                    DoCast(me, SPELL_TELEPORT_RAG);
                    bRagTele = true;
                }
                else
                    uiDefeatTimer -= diff;
            }

            if (bRagIntro)
                Intro(diff);
        }

        if (!UpdateVictim())
            return;

        //Cast Ageis if less than 50% hp
        if (m_creature->GetHealth()*100 / m_creature->GetMaxHealth() < 50)
        {
            DoCast(m_creature, SPELL_AEGIS);
        }

        if (uiTeleportTimer <= diff)
        {
            if (Unit *pTarget = me->SelectNearestTarget(100))
                pTarget->CastSpell(pTarget, SPELL_TELEPORT, false);

            DoResetThreat();

            uiTeleportTimer = urand(20000, 40000);
        } else uiTeleportTimer -= diff;

        //MagicReflection_Timer
        if (MagicReflection_Timer <= diff)
        {
    //        DoCast(m_creature, SPELL_MAGIC_REFLECTION);
            me->AddAura(SPELL_MAGIC_REFLECTION, me);

            //60 seconds until we should cast this again
            MagicReflection_Timer = 30000;
        } else MagicReflection_Timer -= diff;

        //DamageReflection_Timer
        if (DamageReflection_Timer <= diff)
        {
       //     DoCast(m_creature, SPELL_DAMAGE_REFLECTION);
            me->AddAura(SPELL_DAMAGE_REFLECTION, me);

            //60 seconds until we should cast this again
            DamageReflection_Timer = 30000;
        } else DamageReflection_Timer -= diff;

        //Blastwave_Timer
        if (Blastwave_Timer <= diff)
        {
            DoCast(SPELL_BLASTWAVE);
            Blastwave_Timer = 10000;
        } else Blastwave_Timer -= diff;

        DoMeleeAttackIfReady();
    }
Exemple #19
0
//---------------------------------------------------------------------------
void Calc()
{
    mecChar_t szLine[100];
    mecFloat_t fVal = 0,
               afVarVal[] = { 1, 2, 7.2f, -2.1f }; // Values of the parser variables
    mecParserHandle_t hParser;
    mecEvalFun_t pFunEval = NULL;

    hParser = mecCreate();              // initialize the parser
    Intro(hParser);

    // Set an error handler [optional]
    // the only function that does not take a parser instance handle
    mecSetErrorHandler(hParser, OnError);

    //#define GERMAN_LOCALS
#ifdef GERMAN_LOCALS
    mecSetArgSep(hParser, ';');
    mecSetDecSep(hParser, ',');
    mecSetThousandsSep(hParser, '.');
#else
    mecSetArgSep(hParser, ',');
    mecSetDecSep(hParser, '.');
#endif

    // Define parser variables and bind them to C++ variables [optional]
    mecDefineConst(hParser, _T("const1"), 1);
    mecDefineConst(hParser, _T("const2"), 2);

    // Define parser variables and bind them to C++ variables [optional]
    mecDefineVar(hParser, _T("a"), &afVarVal[0]);
    mecDefineVar(hParser, _T("b"), &afVarVal[1]);
    mecDefineVar(hParser, _T("c"), &afVarVal[2]);
    mecDefineVar(hParser, _T("d"), &afVarVal[3]);

    // Define infix operator [optional]
    mecDefineInfixOprt(hParser, _T("!"), Not, 0);

    // Define functions [optional]
    mecDefineFun0(hParser, _T("zero"), ZeroArg, 0);
    mecDefineFun1(hParser, _T("rnd"), Rnd, 0);             // Add an unoptimizeable function
    mecDefineFun2(hParser, _T("dump"), DebugDump, 0);

    // Define binary operators [optional]
    mecDefineOprt(hParser, _T("add"), Add, 0, mecOPRT_ASCT_LEFT, 0);
    mecDefineOprt(hParser, _T("mul"), Mul, 1, mecOPRT_ASCT_LEFT, 0);

#ifdef _DEBUG
    mecDebugDump(1, 0);
#endif

    while (myfgets(szLine, 99, stdin))
    {
        szLine[mystrlen(szLine) - 1] = 0; // overwrite the newline

        switch (CheckKeywords(szLine, hParser))
        {
        case  0:  break;       // no keyword found; parse the line
        case  1:  continue;    // A Keyword was found do not parse the line
        case -1:  return;      // abort the application
        }

        // Set the expression
        mecSetExpr(hParser, szLine);


        // Compile the expression and get the pointer to the 
        // just in time compiled eval function
        pFunEval = mecDbgCompile(hParser, -1);
        if (pFunEval == NULL)
        {
            continue;
        }

        // calculate the expression
        fVal = pFunEval();

        /* alternative:
            fVal = mecEval(hParser); // 1st time parse from string and compile expression
            fVal = mecEval(hParser); // 2nd time parse from JIT code (handled internally)
            */
        // Without an Error handler function 
        // you must use this for error treatment:
        //if (mecError(hParser))
        //{
        //  printf("\nError:\n");
        //  printf("------\n");
        //  printf("Message:  %s\n", mecGetErrorMsg(hParser) );
        //  printf("Token:    %s\n", mecGetErrorToken(hParser) );
        //  printf("Position: %s\n", mecGetErrorPos(hParser) );
        //  printf("Errc:     %s\n", mecGetErrorCode(hParser) );
        //  continue;
        //}

        if (!mecError(hParser))
        {
            myprintf(_T("%f\n"), fVal);
        }

    } // while 

    // finalle free the parser ressources
    mecRelease(hParser);
}
 void StartEvent()
 {
     m_uiIntroTimer = 1000;
     m_uiIntroPhase = 1;
     Intro();
 }
Exemple #21
0
//---------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  Intro();
  Calc();
}
Exemple #22
0
int main(int ac, char **av)
{
	if(!C2D2_Inicia(800, 600, C2D2_JANELA, C2D2_DESENHO_OPENGL, "Chien 2D v2.0 Megademo"))
	{
		printf("Nao conseguiu iniciar a tela. Encerrando.\n");
		return 1;
	}
	// Inicia o áudio
	CA2_Inicia();
	// Inicia o desenho de primitivas
	C2D2P_Inicia();
	// Obtém o teclado
	C2D2_Botao *teclado = C2D2_PegaTeclas();
	// Indica se deve encerrar o demo
	bool encerra = false;
	// Indica o estado do demo
	int estado = 0;
	// Carrega os recursos
	if(Carrega())
	{
		// Toca a música
		CA2_TocaMusica(mfundo, 1);
		while(!encerra && !teclado[C2D2_ESC].pressionado && !teclado[C2D2_ENCERRA].pressionado)
		{
			switch(estado)
			{
			case 0:
				Intro();
				estado++;
				break;
			case 1:
				Primitivas();
				estado++;
				break;
			case 2:
				Sprites();
				estado++;
				break;
			case 3:
				Estrela();
				estado++;
				break;
			case 4:
				Creditos();
				estado++;
				break;
			case 5:
				C2D2_TrocaCorLimpezaTela(0,0,0);
				C2D2_LimpaTela();
				if(RelogioDigital(692,552) > 119000)
					estado++;
				C2D2_Sincroniza(C2D2_FPS_PADRAO);
				break;
			default:
				encerra=true;
			}
			
		}
		CA2_PausaMusica();
		// DEscarrega os recursos
		Descarrega();
	}
	else
		printf("Opa! Falhou algo. Encerrando.\n");
	// Encerra tudo
	CA2_Encerra();
	C2D2_Encerra();
	return 0;
}
Exemple #23
0
int main(int argc, char *argv[])
{

	//Projektwerkstatt
	if(argc != 4) {
		ErrorAndExit("Illegal number of Parameters");
	}
	//Projektwerkstatt

	int key=0;
	int  Reading;
	char OCR[20];
	char Version[20];

	int iReadRequest=0;

	int ReadingPeriod=10;
	int ReadingTimer=ReadingPeriod+1;

	uint16_t Data = 0;
	uint32_t Build = 0;
	uint32_t OCRData = 0;

	int iRetry = 3;
	int iTimeout = 0;

	int sock;
	int connected;

	Intro(ReadingPeriod);

	if (wiringPiSetup () == -1) {
		fprintf (stderr, "Not running on raspberry pi - now ending\n") ;
		exit(0);
	}

	EnergyCamOpen(0);  //open serial port

	//get Status & wakeup
	iRetry = 3;
	do {
	if(iRetry-- < 0 ) break;
	}while(MODBUSERROR == EnergyCam_GetManufacturerIdentification(&Data));

	if(Data == SAIDENTIFIER) {
		Colour(PRINTF_GREEN,false);
		printf("EnergyCAM Sensor connected ");
		Colour(0,true);
	} else {
		ErrorAndExit("EnergyCAM not found ");
	}

	//Read Buildnumber
	if (MODBUSOK == EnergyCam_GetAppFirmwareBuildNumber(&Build)) {
	  printf("Build %d \n",Build);
	}

	//Check Buildnumber, GetResultOCRInt requires Build 8374
	if (Build < 8374) {
	  ErrorAndExit("This App requires a Firmwareversion >= 8374. ");
	}

	//Is EnergyCam installed
	Data = DisplayInstallationStatus();

	//try to install the device if not installed
	if((Data == INSTALLATION_NODIGITS) || (Data == INSTALLATION_NOTDONE)){
		EnergyCam_TriggerInstallation();
		usleep(2000*1000);   //sleep 2000ms - wait for Installation
		printf("Installing ");
		iTimeout = 20;
		do {
			usleep(500*1000);   //sleep 500ms
			printf(".");
			if (MODBUSERROR == EnergyCam_GetResultOCRInstallation(&Data)) {
				Data = 0xFFFD; //retry if MODBUS returns with an Error
			}
		}
		while((iTimeout-->0) && (Data == 0xFFFD));
		printf("\n");

		//Is EnergyCam installed
		Data = DisplayInstallationStatus();
	}

	if((Data == INSTALLATION_NODIGITS) || (Data == INSTALLATION_NOTDONE) || (Data == INSTALLATION_FAILED) || (Data == INSTALLATION_ONGOING)){
		ErrorAndExit("EnergyCAM not installed ");
	}




	//get last Reading
	EnergyCam_TriggerReading();
	sleep(4);
	iRetry = 3;
	do{
		if(iRetry-- < 0) break;
	}while(MODBUSERROR == EnergyCam_GetStatusReading(&Data));
	if (MODBUSOK == EnergyCam_GetResultOCRInt(&OCRData,&Data)) {
	  time_t t = time(NULL);
	  struct tm tm = *localtime(&t);
	  printf("(%02d:%02d:%02d) Reading %04d.%d \n",tm.tm_hour,tm.tm_min,tm.tm_sec,OCRData,Data);
	  //Projektwerkstatt
	  sendDataToServer(argv[1],argv[2],argv[3],OCRData,Data);
	  //Projektwerkstatt
	  EnergyCam_Log2CSVFile("/var/www/ecpi/data/ecpi.csv",OCRData,Data);
	}

	IsNewMinute();
	ReadingTimer=ReadingPeriod+1;

	while (!((key == 0x1B) || (key == 'q')))
	{
		usleep(500*1000);   //sleep 500ms

		key = getkey();

		/*if(key == 'r')   {
		  iReadRequest++; //Read now
		}
		if(key == 'R')   {
			ReadingTimer=1;  //read in 1 minute

		  //get Status & wakeup
			iRetry = 3;
			do {
				if(iRetry-- < 0 ) break;
			}while(MODBUSERROR == EnergyCam_GetStatusReading(&Data));
			printf("GetStatusReading %04X \n",Data);

			//trigger new reading
			EnergyCam_TriggerReading();
		}*/


		if(IsNewMinute()){
		  if(--ReadingTimer<=1)iReadRequest++;
		  printf("%02d ",ReadingTimer);
		  fflush(stdout);
		  iRetry = 3;
                  do {
                      if(iRetry-- < 0 ) break;
                  }while(MODBUSERROR == EnergyCam_GetStatusReading(&Data));

                  //trigger new reading
		  EnergyCam_TriggerReading();
		}

		if(iReadRequest > 0) {
		  iReadRequest=0;
		  printf("%02d \n",ReadingTimer);
		  ReadingTimer=ReadingPeriod+1;

		  //get Status & wakeup
	  	  iRetry = 3;
		  do {
		    if(iRetry-- < 0 ) break;
		  }while(MODBUSERROR == EnergyCam_GetStatusReading(&Data));
		    //printf("GetStatusReading %04X \n",Data);
		    EnergyCam_GetOCRPicDone(&Data);
		    //printf("Pictures %04d \n",Data);
		    if (MODBUSOK == EnergyCam_GetResultOCRInt(&OCRData,&Data)) {
		    time_t t = time(NULL);
		    struct tm tm = *localtime(&t);
	    	    printf("(%02d:%02d:%02d) Reading %04d.%d \n",tm.tm_hour,tm.tm_min,tm.tm_sec,OCRData,Data);
		    //Projektwerkstatt
		    sendDataToServer(argv[1],argv[2],argv[3],OCRData,Data);
		    //Projektwerkstatt
		    EnergyCam_Log2CSVFile("/var/www/ecpi/data/ecpi.csv",OCRData,Data);
		  }
		}

	} // end while

	EnergyCamClose();

	return 0;
}
int main(int argc, char *argv[]) {
    int      key    = 0;
    int      iCheck = 0;
    int      iX;
    int      iK;
    char     KeyInput[_MAX_PATH];
    char     Key[3];
    char     CommandlineDatPath[_MAX_PATH];
    double   csvValue;
    int      Meters = 0;
    unsigned long ReturnValue;
    FILE    *hDatFile;

    uint16_t InfoFlag = SILENTMODE;
    uint16_t Port = 0;
    uint16_t Mode = RADIOT2;
    uint16_t LogMode = LOGTOCSV;
    uint16_t wMBUSStick = iM871AIdentifier;

    char     comDeviceName[100];
    int      hStick;
//Variables added for CIVIS project
    FILE *fp;
    char row[100], word1[50], word2[50];
    char *res;
    int i=1;
    char filepath[50]="/home/pi/sw/civis_config.txt\0";
//----
    ecwMBUSMeter ecpiwwMeter[MAXMETER];
    memset(ecpiwwMeter, 0, MAXMETER*sizeof(ecwMBUSMeter));

    memset(CommandlineDatPath, 0, _MAX_PATH*sizeof(char));



    if(argc > 1)
      parseparam(argc, argv, CommandlineDatPath, &InfoFlag, &Port, &Mode, &LogMode);

    //read config back
    if ((hDatFile = fopen("meter.dat", "rb")) != NULL) {
        Meters = fread((void*)ecpiwwMeter, sizeof(ecwMBUSMeter), MAXMETER, hDatFile);
        fclose(hDatFile);
    }

    Intro();

//Gets ApartmentID for CIVIS project
    
    fp=fopen(filepath, "r");
    do {
	memset(row, 0, 100);
	memset(word1,0, 50);
	memset(word2,0, 50);
	strcpy(row,"");
	strcpy(word1,"");
	strcpy(word2,"");
	res=fgets(row, 99, fp);
	sscanf(row, "%s %s", word1, word2);
		if (strcmp(word1, "ID")==0){
			strcpy(ApartmentID,word2);
			break;
		}
	} while (res!=NULL);
    printf("ApartmentID=%s\n", ApartmentID);
    fclose(fp);

//------
    //open wM-Bus Stick #1
    wMBUSStick = iM871AIdentifier;
    sprintf(comDeviceName, "/dev/ttyUSB%d", Port);
    hStick = wMBus_OpenDevice(comDeviceName, wMBUSStick);

    if(hStick <= 0) { //try 2.Stick
        wMBUSStick = iAMB8465Identifier;
        usleep(500*1000);
        hStick = wMBus_OpenDevice(comDeviceName, wMBUSStick);
    }

    if(hStick <= 0) {
         ErrorAndExit("no wM-Bus Stick not found\n");
    }

    if((iM871AIdentifier == wMBUSStick) && (APIOK == wMBus_GetStickId(hStick, wMBUSStick, &ReturnValue, InfoFlag)) && (iM871AIdentifier == ReturnValue)) {
        if(InfoFlag > SILENTMODE) {
            printf("IMST iM871A Stick found\n");
        }
    }
    else {
        wMBus_CloseDevice(hStick, wMBUSStick);
        //try 2. Stick
        wMBUSStick = iAMB8465Identifier;
        hStick = wMBus_OpenDevice(comDeviceName,wMBUSStick);
        if((iAMB8465Identifier == wMBUSStick) && (APIOK == wMBus_GetStickId(hStick, wMBUSStick, &ReturnValue, InfoFlag)) && (iAMB8465Identifier == ReturnValue)) {
            if(InfoFlag > SILENTMODE) {
                printf("Amber Stick found\n");
            }
        }
        else {
            wMBus_CloseDevice(hStick, wMBUSStick);
            ErrorAndExit("no wM-Bus Stick not found\n");
        }
    }

    if(APIOK == wMBus_GetRadioMode(hStick, wMBUSStick, &ReturnValue, InfoFlag)) {
        if(InfoFlag > SILENTMODE) {
            printf("wM-BUS %s Mode\n", (ReturnValue == RADIOT2) ? "T2" : "S2");
        }
        if (ReturnValue != Mode)
           wMBus_SwitchMode(hStick, wMBUSStick, (uint8_t) Mode, InfoFlag);
    }
    else
        ErrorAndExit("wM-Bus Stick not found\n");

    wMBus_InitDevice(hStick, wMBUSStick, InfoFlag);

    UpdateMetersonStick(hStick, wMBUSStick, Meters, ecpiwwMeter, InfoFlag);

    IsNewMinute();

    while (!((key == 0x1B) || (key == 'q'))) {
        usleep(500*1000);   //sleep 500ms

        key = getkey();

        /*key =fgetc(stdin);
        while(key!='\n' && fgetc(stdin) != '\n');
        printf("Key=%d",key);*/


        //add a new Meter
        if (key == 'a') {
            iX=0;
            while(0 != ecpiwwMeter[iX].manufacturerID) {
                iX++;
                if(iX == MAXMETER-1)
                  continue;
              }
            //check entry in list of meters
            if(iX < MAXMETER) {
                printf("\nAdding Meter #%d \n",iX+1);
                printf("Enter Meter Ident (12345678): ");
                if(fgets(KeyInput, _MAX_PATH,stdin))
                    ecpiwwMeter[iX].ident=CalcUIntBCD(atoi(KeyInput));

                printf("Enter Meter Type (2 = Electricity ; 3 = Gas ; 7 = Water) : ");
                if(fgets(KeyInput, _MAX_PATH,stdin)) {
                    switch(atoi(KeyInput)) {
                        case METER_GAS  :        ecpiwwMeter[iX].type = METER_GAS;          break;
                        case METER_WATER:        ecpiwwMeter[iX].type = METER_WATER;        break;
                        default: printf(" - wrong Type ; default to Electricity");
                        case METER_ELECTRICITY : ecpiwwMeter[iX].type = METER_ELECTRICITY;  break;
                    }
                }
                ecpiwwMeter[iX].manufacturerID = FASTFORWARD;
                ecpiwwMeter[iX].version        = 0x01;

                printf("Enter Key (0 = Zero ; 1 = Default ; 2 = Enter the 16 Bytes) : ");
                if(fgets(KeyInput, _MAX_PATH, stdin)) {
                    switch(atoi(KeyInput)) {
                        case 0  : for(iK = 0; iK<AES_KEYLENGHT_IN_BYTES; iK++)
                                    ecpiwwMeter[iX].key[iK] = 0;
                        break;

                        default:
                        case 1  : for(iK = 0; iK<AES_KEYLENGHT_IN_BYTES; iK++)
                                    ecpiwwMeter[iX].key[iK] = (uint8_t)(0x1C + 3*iK);
                        break;

                        case 2  :
                                printf("Key:");
                                fgets(KeyInput, _MAX_PATH, stdin);
                                    for(iK = 0; iK<AES_KEYLENGHT_IN_BYTES; iK++)
                                        ecpiwwMeter[iX].key[iK] = 0;
                                if((strlen(KeyInput)-1) < AES_KEYLENGHT_IN_BYTES*2)
                                    printf("Key is too short - default to Zero\n");
                                else {
                                    memset(Key,0,sizeof(Key));
                                    for(iK = 0; iK<(int)(strlen(KeyInput)-1)/2; iK++) {
                                        Key[0] =  KeyInput[2*iK];
                                        Key[1] =  KeyInput[2*iK+1];
                                        ecpiwwMeter[iX].key[iK] = (uint8_t) strtoul(Key, NULL, 16);
                                    }
                                }
                        break;
                    }
                }

                Meters++;
                Meters = min(Meters, MAXMETER);
                DisplayListofMeters(Meters, ecpiwwMeter);
                UpdateMetersonStick(hStick, wMBUSStick, Meters, ecpiwwMeter, InfoFlag);
            } else
                printf("All %d Meters defined\n", MAXMETER);
        }

        // display list of meters
        if(key == 'l')
            DisplayListofMeters(Meters, ecpiwwMeter);

        //remove a meter from the list
        if(key == 'r') {
            printf("Enter Meterindex to remove: ");
            if(fgets(KeyInput, _MAX_PATH, stdin)) {
                iX = atoi(KeyInput);
                if(iX-1 <= Meters-1) {
                    printf("Remove Meter #%d\n",iX);
                    memset(&ecpiwwMeter[iX-1], 0, sizeof(ecwMBUSMeter));
                    DisplayListofMeters(Meters, ecpiwwMeter);
                    UpdateMetersonStick(hStick, wMBUSStick, Meters, ecpiwwMeter, InfoFlag);
                 }
                 else
                    printf("Index not defined\n");
            }
        }

        // switch to S2 mode
        if(key == 's')
            wMBus_SwitchMode( hStick,wMBUSStick, RADIOS2,InfoFlag);

        // switch to T2 mode
        if(key == 't')
            wMBus_SwitchMode( hStick,wMBUSStick, RADIOT2,InfoFlag);

        //check whether there are new data from the EnergyCams
        if (IsNewMinute() || (key == 'u')) {
            if(wMBus_GetMeterDataList() > 0) {
                iCheck = 0;
                for(iX=0; iX<Meters; iX++) {
                    if((0x01<<iX) & wMBus_GetMeterDataList()) {
                        ecMBUSData RFData;
                        int iMul=1;
                        int iDiv=1;
                        wMBus_GetData4Meter(iX, &RFData);

                        if(RFData.exp < 0) {  //GAS
                            for(iK=RFData.exp; iK<0; iK++)
                               iDiv=iDiv*10;
                            csvValue = ((double)RFData.value)/iDiv;
                        } else {
                            for(iK=0; iK<RFData.exp; iK++)
                                iMul=iMul*10;
                            csvValue = (double)RFData.value*iMul;
                        }
                        if(InfoFlag > SILENTMODE) {
                            Colour(PRINTF_GREEN, false);
                            printf("Meter #%d : %4.1f %s", iX+1, csvValue, (ecpiwwMeter[iX].type == METER_ELECTRICITY) ? "Wh" : "m'3");
                        }
                        if(ecpiwwMeter[iX].type == METER_ELECTRICITY)
                            csvValue = csvValue/1000.0;

                        if(InfoFlag > SILENTMODE) {
                            if((RFData.pktInfo & PACKET_WAS_ENCRYPTED)      ==  PACKET_WAS_ENCRYPTED)     printf(" Decryption OK");
                            if((RFData.pktInfo & PACKET_DECRYPTIONERROR)    ==  PACKET_DECRYPTIONERROR)   printf(" Decryption ERROR");
                            if((RFData.pktInfo & PACKET_WAS_NOT_ENCRYPTED)  ==  PACKET_WAS_NOT_ENCRYPTED) printf(" not encrypted");
                            if((RFData.pktInfo & PACKET_IS_ENCRYPTED)       ==  PACKET_IS_ENCRYPTED)      printf(" is encrypted");
                            printf(" RSSI=%i dbm, #%d \n", RFData.rssiDBm, RFData.accNo);
                            Colour(0,false);
                        }

                        Log2File(CommandlineDatPath, LogMode, iX, InfoFlag, csvValue, &RFData, ecpiwwMeter[iX].ident);

                    }
                }
            }
            else {
              if(InfoFlag > SILENTMODE) {
                  Colour(PRINTF_YELLOW, false);
                  printf("%02d ", iCheck);
                  Colour(0, false);
                  if((++iCheck % 20) == 0) printf("\n");
                }
            }
        }
    } // end while

    if(hStick >0) wMBus_CloseDevice(hStick, wMBUSStick);

    //save Meter config to file
    if(Meters > 0) {
        if ((hDatFile = fopen("meter.dat", "wb")) != NULL) {
            fwrite((void*)ecpiwwMeter, sizeof(ecwMBUSMeter), MAXMETER, hDatFile);
            fclose(hDatFile);
        }
    }
    return 0;
}
Exemple #25
0
int CBGA::main(int argc, char **argv)
{
#ifdef _DEBUG
	// создаём консоль
	CL_ConsoleWindow console("BGA Console");
	console.redirect_stdio();
#endif

	try
	{
		//инициализация
		CL_SetupCore::init();
		CL_SetupDisplay::init();
		CL_SetupGL::init();
		CL_SetupNetwork::init();
		CL_SetupSound::init();
		CL_SetupVorbis::init();
		CL_SoundOutput output(44100);

		LOG<<"Bad Guys on Autos\nВерсия "<<VERSION<<endl;		
		LOG<<LOG.Time()<<"Старт игры\n";

		LOG<<"Установка  графического режима...\n";

		//окно
#ifdef _DEBUG
		CL_DisplayWindow window("BGA v"VERSION, SCR_W, SCR_H, false, true);
#else
		CL_DisplayWindow window("BGA v"VERSION, SCR_W, SCR_H, true);
#endif
		window.hide_cursor();

		//получаем текущий режим
		DEVMODE cur_devmode;
		EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &cur_devmode);

		LOG<<"Установлен графический режим "<<cur_devmode.dmPelsWidth<<"x"<<cur_devmode.dmPelsHeight<<"x";
		LOG<<cur_devmode.dmBitsPerPel<<"@"<<cur_devmode.dmDisplayFrequency<<endl;

		//контекст
		CL_GraphicContext *gc = window.get_gc();

		srand(CL_System::get_time());
		
		CGame Game;
#ifndef _DEBUG
		Intro(Game.GetResman());

		CGameMenu game_menu(&Game);
		game_menu.Intro();
		game_menu.MainLoop();
#else
		//CGameMenu game_menu(&Game);
		//game_menu.MainLoop();
		Game.SetLimits(3,0);
		Game.SetLocalNames("Tosha","Hitman","Crash","Doom");
		Game.NewGame(BGA_GAME_DEATHMATCH,2,"platetown");
		Game.MainLoop();
#endif


		LOG<<LOG.Time()<<"Завершение игры\n";

		//деинициализация
		CL_SetupVorbis::deinit();
		CL_SetupSound::deinit();
		CL_SetupNetwork::deinit();
	 	CL_SetupCore::deinit();
		CL_SetupDisplay::deinit();
		CL_SetupGL::deinit();
	}
	catch (CL_Error err)
	{
		std::cout << "Exception caught: " << err.message.c_str() << std::endl;
		LOG<<endl<<LOG.Time()<<"ОШИБКА! "<< err.message.c_str() <<endl;

#ifdef _DEBUG
		// Display console close message and wait for a key
		console.display_close_message();
#endif
	}
	catch (...)
	{
		LOG<<endl<<LOG.Time()<<"ОШИБКА! Необработанное исключение!"<<endl;
	}

	LOG<<"\n\n\nThe time of Bad Guys will come soon...";
	//console.display_close_message();
	return 0;
} 
	void StartEvent()
    {
		m_uiIntroTimer = 1*IN_MILISECONDS;
		m_uiIntroPhase = 1;
		Intro(); 
    }
Exemple #27
0
int main(int argc, char **argv) {

#ifdef _OPENMP    		/* Compilation with OMP */
  int numthreads;
  numthreads = omp_get_max_threads();
  omp_set_num_threads(numthreads);
#endif  

  time_t t;   struct tm *tm;  t = time(NULL); tm = localtime(&t);
  if((argc >1) && (argv[1][1] == 'd')) {debug = 1; d_level = 1;} /* Initial debugging */

  srand(time(NULL));
  gsl_rng_env_setup();		/* Random generator initialization */
  gsl_rng_default_seed = rand()*RAND_MAX;
  sprintf(mesg,"Seed: %ld ",gsl_rng_default_seed);
  DEBUG(mesg);
  
  /* Declaration of variables */
  /* Contadores */
  int i, time, tr_TT = 0;
  int Nscan = 0;
  /* Others */
  int def = 1;			/* Default = 1 */
  int temporal_correction = 1;
  int total_spikes1 = 0, total_spikes2 = 0;

  double var_value;
  double *final_conf,  *final_conf2;

  /* Date variables */
  char day[100], hour[100];
  strftime(day, 100, "%m-%d-%Y",tm);
  sprintf(hour,"%d.%02d",tm->tm_hour,tm->tm_min);

  /* Data store */
  Create_Dir("results");
  FILE *file[8];
  
  /* System variables (magnitudes) */
  t_th *th;			/* neuron vector */
  double R = 0;			/* Kuramoto order parameter */

  double fr_volt[2];		/* Stores width and center of the Lorentzian distr. (R) */
  double fr_x;			/* Center of the Lorentzian distr. */
  double fr_y;			/* Width  " " " " */
  double perturbation = 0;

  double fr, fr2;		/* Mean field (firing rate) */
  double avg_fr1,avg2_fr1;
  int medida;
  double inst_fr_avg;
  int intervalo;
  int total_spikes_inst;

  double avg_v1 = 0, avg_v2 = 0;
  long double v1_center = 0, v2_center = 0;

  double dt, *p, phi = 0;

  double rh_final = 1, vh_final = 1; /* FR *** initial conds. for r and v ( FR equations) */

  t_data *d, *data;
  d = malloc(sizeof(*d));
  data = malloc(sizeof(*data));

  d->scan = 0;			/* Exploring is unabled by default */
  d->MaxDim = 5000000;		/* Raster plot will be disabled for higher dim */
  
  sprintf(d->file,"%s_%s",day,hour);
  sprintf(mesg2,"results/%s",d->file);
  Create_Dir(mesg2);
  Create_Dir("temp");
  sprintf(mesg2,"cp volt_avg.R ./temp");
  system(mesg2);

  /*********************************/
  /* Program arguments assignation */
  /*********************************/
  *data = Scan_Data(DATA_FILE,*d);
  d = data;

  while((argc--) != 1) {	/* Terminal arguments can be handled */
    *data = Arg(argv[argc], *d);
    d = data;
    if(argv[1][0] != '-') def = 0;
  }

#ifdef _OPENMP			/* Work is divided between the cores */
  int chunksize = d->N/numthreads;
  if(chunksize > 10) chunksize = 10;
#endif

  /* Initial tunning: step size, and scanning issues */
  Intro(d,&Nscan,&tr_TT);
  if(d_level == 4){ temporal_correction = 0; DEBUG("Temporal correction is OFF");}
  d->var_value = d->eta;
  d->scan_max = Nscan;
  d->pert = 0;

  if(d->scan_mode == 3) {
    d->pert = 1;
    d->scan_mode = 2;
  }
  double dTT = d->TT;
  double dTT2 = d->TT*2.0;

  /* Configuration at the end of simulation */
  final_conf  = (double*) malloc (d->N*sizeof(double));
  final_conf2 = (double*) malloc (d->N*sizeof(double));

  /**********************************/
  /* New simulations can start here */
  /**********************************/
  do {    
    if(d->scan_mode >= 1) 
      d = Var_update(d);
    Data_Files(&file,*d,0);
    Data_Files(&file,*d,4);
    total_spikes1 = 0;
    total_spikes2 = 0;
    
    /********************/
    /* Oscillator setup */
    /********************/
    th  = (t_th*) calloc (d->N,sizeof(t_th)); 
    for(i=0 ;i<d->N ;i++ ) {		/* The total number (N) is stored in each package */
      th[i].N = d->N;
    }
    th[0].pert = 0;
    th[0].rh = 1;
    th[0].vh = 1;                       /* FR **** Initial condition for the FR equations */

    p = (double*) malloc ((d->N+1)*sizeof(double));

    /* QIF: vr and vp and g */
    for(i=0 ;i<d->N ;i++ ) {
      th[i].vr = d->vr;
      th[i].vp = d->vp;
      th[i].g = d->g;
    }
    
    
    if(d->scan_mode == 2 && d->scan > 0) {
      for(i=0 ;i<d->N ;i++ ) {
	th[i].v = final_conf[i];                /* We mantain the last configuration of voltages */
	th[i].th = final_conf2[i];
      }
    } else {
      InitialState(th,d->init_dist);		/* Initial state configuration */
      /* InitialState(th,d->init_dist+1); */
    }

    for(i=0 ;i<d->N ;i++ ) {
      th[i].spike = 0;		                /* Spike */
      th[i].tr = 0;
      th[i].tr2 = 0;
      th[i].ph = VarChange(th[i]);
    }
    
    dt = d->dt;

    if(def == 0)		/* Debug message: data display */
      DEBUG2(DataDebug(*d,&file));

    if(d->scan_mode == 2 && d->scan > 0) {
      th[0].rh = rh_final;	/* FR **** final configuration of the pevious ... */
      th[0].vh = vh_final;	/* ... simulation is taken as the initial configuration */
    }
    
    /** Distributions *******************/   

    /* QIF: J */
    sprintf(mesg,"Building distribution for J_i. J0 = %lf ",d->J );
    if(d->J_dist == 1)  DEBUG(mesg);
    p = InitCond(p,d->N,2,d->J,d->J_sigma);
    if(d->J_dist == 0) {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].J = d->J;
    } else
      for(i=0 ;i<d->N ;i++ ) 
	th[i].J = p[i];
  
    /* QIF: eta */
    sprintf(mesg,"Building distribution for eta_i. eta0 = %lf ",d->eta );
    if(d->eta_dist == 1)  DEBUG(mesg);
    p = InitCond(p,d->N,2,d->eta,d->eta_sigma);
    if(d->eta_dist == 0) {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].eta = d->eta;
    } else {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].eta = p[i];
    }

    /* QIF: V0 */
    sprintf(mesg,"Building distribution for V0_i. V0 = %lf ",d->v0 );
    if(d->v0_dist == 1)  DEBUG(mesg);
    p = InitCond(p,d->N,2,d->v0,d->v0_sigma);
    if(d->v0_dist == 0) {
      for(i=0 ;i<d->N ;i++ ) 
	th[i].V0 = d->v0;
    } else
      for(i=0 ;i<d->N ;i++ ) 
	th[i].V0 = p[i];


    /* Simulation */
    sprintf(mesg,"Simulating dynamics of: v' = v² + I ");    DEBUG(mesg);
    sprintf(mesg,"I = J*r + n - g*r(v - v0)");    DEBUG(mesg);
    sprintf(mesg,"I = %.3lf*r + %.3lf - %.3lf*r(v - %.3lf) ",d->J,d->eta,d->g,d->v0);    DEBUG(mesg);

    time = 0; fr = 0; fr2 = 0;  avg_fr1 = 0; 
    avg2_fr1 = 0; medida = 0;
    v1_center = 0; v2_center = 0; 
    d->voltdist = 0;
    intervalo = 0;
    inst_fr_avg = 0;
    total_spikes_inst = 0;

    do {
      /* In each step we must compute the mean field potential (r) */
      if(time%((int)((float)d->TT/(10.0*dt))) == 0) { /* Control point */
	sprintf(mesg,"%d%% ",(int)(((time*dt)/(float)d->TT)*100) );
	DEBUG(mesg);
      }
      /* Parallelizable, watch out with pointers and shared variables */
#pragma omp parallel for schedule(dynamic,chunksize)
      for(i=0 ;i<d->N ;i++ ) {	/* i represents each oscillator */
	th[i].r = fr;	
	if(th[0].pert == 1) 
	  th[i].r = th[0].FR;
	th[i].r2 = fr2;
	th[i].spike = 0;
	th[i].spike2 = 0;

	if(temporal_correction == 1) {
	  if(th[i].tr == 1) {
	    th[i].tr = 2;
	    th[i].spike = 1;
	  } else if(th[i].tr == 2) {
	    th[i].tr = 0;
	  } else 
	    th[i] = QIF(*d,th[i]);
	} else {
	  th[i] = QIF(*d, th[i]);
	  if(th[i].tr == 1) th[i].spike = 1;
	  th[i].tr = 0;
	}

	th[i] = THETA(*d,th[i]);

	if(time*dt >= (d->TT/4.0)*3.0) 
	  th[i].total_spikes += th[i].spike;
      }
      /* Simulation of rate equations */
      th[0] = Theory(*d,th[0]);
      /* Ends here */

      fr = MeanField(th,d->dt,1);   fr2 = MeanField(th,d->dt,2);
      if((time*d->dt)/d->TT > 0.9) {
	total_spikes1 += th[0].global_s1;
	total_spikes2 += th[0].global_s2;
	for(i=0 ;i<d->N ;i++ ) {
	  v1_center += th[i].v;
	  v2_center += th[i].th;
	}

	v1_center /= d->N;
	v2_center /= d->N;
	medida++;
	avg_v1 += v1_center;
	avg_v2 += v2_center;
      }
      /* Inst FR */
      total_spikes_inst += th[0].global_s1;
      intervalo++;

      if(abs(time - (int)(d->TT/d->dt)) <= 50) {
	d->voltdist++;
	Data_Files(&file,*d,2);
	for(i=0 ;i<d->N ;i++ ) 
	  fprintf(file[6],"%lf\n",th[i].v);
	Data_Files(&file,*d,3);
      }

      if(d->disable_raster == 0)
	for(i=0 ;i<d->N ;i++ ) {
	  if(th[i].spike == 1)
	    fprintf(file[2] ,"%lf\t%d\t-1\n",time*d->dt,i);
	  if(th[i].spike2 == 1)
	    fprintf(file[2] ,"%lf\t-1\t%d\n",time*d->dt,i);
	}
      R = OrderParameter(th,&phi);
      th[0].FR = 0;
      th[0].pert = 0;
      /* Perturbation introduced here */
      if((time > (d->TT/d->dt)-100) && d->pert == 1 && d->dx >= 0) {
	if(time == (d->TT/d->dt)-100 +1) {
	  avg_fr1 = (double)total_spikes1/((double)medida*d->dt);
	  avg_fr1 /= d->N;
	  printf("\n Average FR 0: %.8lf",avg_fr1);
	  fflush(stdout);	  
	}
	if(abs(time-(int)((d->TT/d->dt)-100))%5 == 0) {
	  Perturbation(&th,*d,1);
	  th[0].pert = 1;
	  printf("\nPerturbation: %lf!!",d->pert_amplitude);
	  perturbation = d->pert_amplitude;
	}
	if(time == (d->TT/d->dt)-1) {
	  d->TT = dTT2;
	  d->pert = 2;
	}
      } else if((time == (d->TT/d->dt)-1) && d->pert == 1) {
	Perturbation(&th,*d,0);
	th[0].vh += d->perturbation_FR; /* FR *** Perturbation for FR equations */
	th[0].pert = 1;
	printf("\nPerturbation: %lf!!",d->pert_amplitude);
	perturbation = d->pert_amplitude;
	d->TT = dTT2;
	avg_fr1 = (double)total_spikes1/((double)medida*d->dt);
	avg_fr1 /= d->N;
	printf("\n Average FR 0: %.8lf",avg_fr1);
	fflush(stdout);
	d->pert = 2;
      }
      fprintf(file[3] ,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",time*dt,fr,R,phi,fr2,R,phi,th[0].rh,th[0].vh);
      fprintf(file[0] ,"%lf\t%lf\t%lf\t%lf\n",time*d->dt,th[d->N/4].v,th[d->N/4].th,perturbation);

      if(time%50 == 0) {
	inst_fr_avg  = (double)total_spikes_inst/(double)intervalo;
	inst_fr_avg  = inst_fr_avg/(d->N*d->dt);
	intervalo = 0;
	fprintf(file[7],"%lf\t%lf\n",time*d->dt,inst_fr_avg);
	inst_fr_avg = 0;
	total_spikes_inst = 0;
      }
      perturbation = 0;

      time++;    
    } while(time*d->dt< d->TT);

    if(d->pert == 2) {
      d->TT = dTT;
      d->pert = 1;
    }
    avg_fr1 = (double)total_spikes1/((double)medida*d->dt);
    avg_fr1 /= d->N;
    printf("\n Average FR 1: %.8lf",avg_fr1);

    avg2_fr1 = (double)total_spikes2/((double)medida*d->dt);
    avg2_fr1 /= d->N;
    printf("\n Average FR Theta: %.8lf\n",avg2_fr1);

    avg_v1 /= medida;
    avg_v2 /= medida;
    avg_v2 = tan(avg_v2*0.5);

    R_script(*d,avg2_fr1,avg_v2);
    R_calc(*d,&fr_x,&fr_y); /* fr: 0  voltage: 1 */
    fr_volt[0] = fr_x;
    fr_volt[1] = fr_y;
    fr_x = 2*fr_x/(PI);
    fr_y = 2*fr_y;

    printf("\n Average Voltage (v) : %lf\n Average Voltage (Theta) : %lf",avg_v1, avg_v2);
    printf("\n Average Voltage (v) using v distribution: %lf\n Average FR using v dist : %lf\n",fr_volt[1]*2,fr_volt[0]*(2.0/(PI)));

    
    if(d->scan_mode >= 1) {
      switch(d->variable) {
      case 1:
	var_value = d->J;
	break;
      case 2:
	var_value = d->eta;
	break;
      case 3:
	var_value = d->g;
	break;
      case 4:
	var_value = d->v0;
	break;
      }
      fprintf(file[4] ,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",var_value,avg_fr1,avg2_fr1,avg_v1, avg_v2,fr_x,fr_y);
    }
    
    printf("\n");
    free(p);
    for(i=0 ;i<d->N ;i++ ) {
      fprintf(file[1] ,"%d\t%lf\t%lf\n",i,th[i].v,th[i].th);
      final_conf[i]  = th[i].v;
      final_conf2[i] = th[i].th;
    }

    free(th);
    d->scan++;
    Data_Files(&file,*d,1);
    Data_Files(&file,*d,5);
    if(d->scan_mode == 0)
      break;

  } while (d->scan < Nscan);
  /* Simulation ends here */


  free(final_conf);
  free(final_conf2);

  /* system("R -f histogram.R --quiet --slave"); */
  /* Gnuplot_Init(*d,day,hour); */
  system("rm -r ./temp");
  printf("\n");
  return 0;  
}
Exemple #28
0
//---------------------------------------------------------------------------
void Calc()
{
  muChar_t szLine[100];
  muFloat_t fVal = 0,
            afVarVal[] = { 1, 2 }; // Values of the parser variables
  muParserHandle_t hParser;

  hParser = mupCreate(muBASETYPE_FLOAT);              // initialize the parser
  Intro(hParser);

  // Set an error handler [optional]
  // the only function that does not take a parser instance handle
  mupSetErrorHandler(hParser, OnError);

//#define GERMAN_LOCALS
#ifdef GERMAN_LOCALS
  mupSetArgSep(hParser, ';');
  mupSetDecSep(hParser, ',');
  mupSetThousandsSep(hParser, '.');
#else
  mupSetArgSep(hParser, ',');
  mupSetDecSep(hParser, '.');
#endif

  // Set a variable factory
  mupSetVarFactory(hParser, AddVariable, NULL);

  // Define parser variables and bind them to C++ variables [optional]
  mupDefineConst(hParser, "const1", 1);  
  mupDefineConst(hParser, "const2", 2);
  mupDefineStrConst(hParser, "strBuf", "Hallo welt");

  // Define parser variables and bind them to C++ variables [optional]
  mupDefineVar(hParser, "a", &afVarVal[0]);  
  mupDefineVar(hParser, "b", &afVarVal[1]);

  // Define postfix operators [optional]
  mupDefinePostfixOprt(hParser, "M", Mega, 0);
  mupDefinePostfixOprt(hParser, "m", Milli, 0);

  // Define infix operator [optional]
  mupDefineInfixOprt(hParser, "!", Not, 0);

  // Define functions [optional]
//  mupDefineStrFun(hParser, "query", SampleQuery, 0); // Add an unoptimizeable function 
  mupDefineFun0(hParser, "zero", ZeroArg, 0);
  mupDefineFun1(hParser, "rnd", Rnd, 0);             // Add an unoptimizeable function
  mupDefineFun1(hParser, "rnd2", Rnd, 1); 
  mupDefineMultFun(hParser, "_sum", Sum, 0);  // "sum" is already a default function

  // Define binary operators [optional]
  mupDefineOprt(hParser, "add", Add, 0, muOPRT_ASCT_LEFT, 0);
  mupDefineOprt(hParser, "mul", Mul, 1, muOPRT_ASCT_LEFT, 0);

  while ( fgets(szLine, 99, stdin) )
  {
    szLine[strlen(szLine)-1] = 0; // overwrite the newline

    switch(CheckKeywords(szLine, hParser))
    {
    case  0:  break;       // no keyword found; parse the line
    case  1:  continue;    // A Keyword was found do not parse the line
    case -1:  return;      // abort the application
    }

    mupSetExpr(hParser, szLine);

    fVal = mupEval(hParser);

  
    // Without an Error handler function 
    // you must use this for error treatment:
    //if (mupError(hParser))
    //{
    //  printf("\nError:\n");
    //  printf("------\n");
    //  printf("Message:  %s\n", mupGetErrorMsg(hParser) );
    //  printf("Token:    %s\n", mupGetErrorToken(hParser) );
    //  printf("Position: %s\n", mupGetErrorPos(hParser) );
    //  printf("Errc:     %d\n", mupGetErrorCode(hParser) );
    //  continue;
    //}

    if (!mupError(hParser))
      printf("%f\n", fVal);

  } // while 

  // finalle free the parser ressources
  mupRelease(hParser);
}