示例#1
0
int main() {

    initSystem();
    initSystemClock();
    I2cMaster::start();

    setGpioPinModeOutput(pPin13);
    setGpioPinLow(pPin13);

    lcd.init();
    lcd.clear();
    lcd.home();
    lcd.autoscrollOff();
    lcd.setBacklight(0);
    delayMilliseconds(1000);
    lcd.setBacklight(I2cLcd::kBacklight_Green);
    lcd.displayTopRow("Hello, World!");
    delayMilliseconds(1000);
    lcd.setBacklight(I2cLcd::kBacklight_White);
    long counter = 0;

    for(;;) {
        for(uint8_t color = 0; color < 8 ; color++) {
            lcd.displayBottomRow(ltoa(counter, number, 10));
            writeGpioPinDigital(pPin13, color % 2);
            counter++;
        }
    }

}
bool PUParticleSystem3D::initWithFilePath( const std::string &filePath )
{
    std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
    convertToUnixStylePath(fullPath);
    std::string::size_type pos = fullPath.find_last_of("/");
    std::string materialFolder = "materials";
    if (pos != std::string::npos){
        std::string temp = fullPath.substr(0, pos);
        pos = temp.find_last_of("/");
        if (pos != std::string::npos){
            materialFolder = temp.substr(0, pos + 1) + materialFolder;
        }
    }
    static std::vector<std::string> loadedFolder;
    if (std::find(loadedFolder.begin(), loadedFolder.end(), materialFolder) == loadedFolder.end())
    {
        PUMaterialCache::Instance()->loadMaterialsFromSearchPaths(materialFolder);
        loadedFolder.push_back(materialFolder);
    }

    if (!initSystem(fullPath)){
        return false;
    }
    return true;
}
示例#3
0
文件: main.c 项目: n0p/Osomcom-Pocsag
/******************************************************************************
 * Function:        void main(void)
 * PreCondition:    None
 * Input:           None
 * Output:          None
 * Side Effects:    None
 * Overview:        Main program entry point.
 * Note:            None
 *****************************************************************************/
void main(void) {

    //char numero[] = {'3','1','3','3','7','1','3','3','7',0};
    char numero[] = {'1','3','3','7','0'};
    //char numero[] = {'0','1','7','2','4'};

    initSystem();

     
    rs232_putString("OsomCom POCSAG 0.1\nRamiro Pareja ([email protected])\n");
    


    //pocsagPhy_sendMsg(pocsag_createNumericMsg(1519073, numero));
    ////pocsagPhy_sendMsg(pocsag_createNumericMsg(RIC, numero));
    //pocsagPhy_sendMsg(pocsag_createAlphaMsg(1111709, numero));
    //pocsagPhy_sendMsg(pocsag_createIdleMsg());

    //pocsagPhy_test();

    // Process Loop
    while (1) {

        led_processLoop();
        pocsagPhy_processLoop();
        rs232_processLoop();
      
    }


}
int main(void)
{
	initSystem();

	  while (1)
	  {
		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_SET);
		  HAL_Delay(100);
		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_RESET);

		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_SET);
		  HAL_Delay(100);
		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_RESET);

		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_SET);
		  HAL_Delay(100);
		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_RESET);

		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_SET);
		  HAL_Delay(100);
		  HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_RESET);


	  }
}
示例#5
0
bool init(HWND hWnd)
{
    g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

    if(!g_pD3D) {
        return false;
    }

    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;

    g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice);

    if(!g_pd3dDevice) {
        return false;
    }

    bool res = initFont();
    initSystem();

    return res;
}
示例#6
0
void main()
{

    initSystem();
    initSC1602();
    initPSW();

    while(1)
    {
        if(10 =< SysTick - PrevSysTick)
        {
            PushedSW = diffsw(PORTB());
            if(PORTBbits.RB5 == 1)  IfSettingPSW = IfSettingPSW ^ 1;
            PrevSysTick = SysTick;
        }

        if(IfSettingPSW == 1)
        {
            settingPSW(PushedSW);
        }
        else
        {
            PSW(PushedSW);
        }
    }
}
示例#7
0
void* hi_wol_thread(void* arg)
{
    int err, ret, sock;
    int port = 9528;
    char* machine = "hisilicon";

printf(">>>> %s ,%d \n",__FUNCTION__,__LINE__);
    //pthread_t httper;
#ifdef H18E9732
    initSystem("18E_OV9732", machine);
#else
    initSystem("dv_board", machine);
#endif
    initMsg();
    (HI_VOID)prctl(PR_SET_NAME, (unsigned long)"hi_wol_thread", 0, 0, 0);


    for (;;)
    {
        err = createSrv();

        if (err == 0)
        { break; }

        sleep(1);
    }

    sta_on_flag = 1;

    pthread_attr_t attr;
    memset(&attr, 0, sizeof(attr));
    attr.schedparam.sched_priority = 9;
    pthread_create(&ping_thread_pid, &attr, &pingThread, NULL);

    //pthread_join(httper,NULL);

    ret = createWolServer(NULL, port);

    if (ret )
    {
        printf("create tcp 9528 fail ------------\n");
    }

    return NULL;
}
示例#8
0
int main(void)
{
	unsigned char c;
initSystem();
/*while(1)
testTimer();*/
DDRD |= 1 << 4;
DDRD |= 1 << 5;
DDRD |= 1 << 6;
DDRD |= 1 << 7;
DDRD |= (1 << 3);
DDRB &= ~(1 << 4);
DDRB |= 1 << 0;
DDRB |= 1 << 1;
DDRB |= 1 << 2;
DDRB |= 1 << 3;
_delay_milli(3000);
//testTimer();
/*testgsmSimul();*/
//testMotor();
bootTest();
//Serialflush();
while(1)
{
app();	
//testReadSensors();
//testSesnors();
//testReadSensors();
//_delay_milli(100);
}

/*while (1)
{
	testMotor();
}*/
/*DDRD |= 1 << 4;
DDRD |= 1 << 5;
DDRD |= 1 << 6;
DDRD |= 1 << 7;
while(1)
{

PORTD |= 1 << 4;
PORTD &= ~(1 << 5);
PORTD |= 1 << 6;
PORTD &= ~(1 << 7);	
_delay_milli(500);

PORTD |= 1 << 5;
PORTD &= ~(1 << 4);
PORTD |= 1 << 7;
PORTD &= ~(1 << 6);
_delay_milli(500);
}*/

}
示例#9
0
int Model::GreedyAlgo()
{
	_start = clock();
	initSystem();
	for (t = 0; t < T; t++){	
		startAssignment();	
		bool assignComplete = false;					//flag to indicate whether all requests are satisfied or pending for next time period
		while(1)
		{
			reviewSystem();					 
			//assignment: assign the highest arc delay/demand to a candidate vehicle
			Arc* pArc;
			Vehicle* pVeh;
			bool isVehtoArcAssigned = assignVehtoArc(pArc, pVeh);
			updateSystem(pArc, pVeh, isVehtoArcAssigned);
			
			assignComplete = true;
			k = 0;
			for (vector<Arc>::iterator iArc = arc.begin(); iArc != arc.end(); iArc++, k++){
				if(iArc->from == iArc->to) continue;
				if(!arcIsAssigned[&(*iArc)]){
					assignComplete = false;				//assign is complete only if all arcs are assigned
					break;
				}	
			}
			if(assignComplete) 
				break;
			//if node load maximum is reached -- cancel vehicles toward this station and/or cancel previous route		
		} //done while loop

		k = 0;
		for (vector<Arc>::iterator iArc = arc.begin(); iArc != arc.end(); iArc++, k++){
			if (iArc->from != iArc->to)	continue;
			v = 0;
			for (vector<Vehicle>::iterator iVeh = sys.vehicle.begin(); iVeh != sys.vehicle.end(); ++iVeh, v++){
				if (!(iVeh->assigned) && iVeh->to == iArc->to && iVeh->time == t){
					sys.route[k][v][t] = 1;						//stay in the station if the vehicle is not assigned toward any other stations
					sys.NodeLoad[iArc->to][t]++;				//update node load
					iVeh->time = t + 1;							//update time
					iVeh->powLvl += maxC;						//update battery level
				}
			}
		}
	}
	// compute the total cost
	computeTotalCost();

	_end = clock();
	cmp_time = (double)(_end - _start) / CLOCKS_PER_SEC;

	sprintf(path, "%soutput/GreedyAlgo_%dV_%dN_%dArc_%dT.txt", directoryPath.c_str(), nVeh, N, nArc, T);
	heuristicSol();

	return 1;
}
bool PUParticleSystem3D::initWithFilePathAndMaterialPath( const std::string &filePath, const std::string &materialPath )
{
    std::string matfullPath = FileUtils::getInstance()->fullPathForFilename(materialPath);
    convertToUnixStylePath(matfullPath);
    PUMaterialCache::Instance()->loadMaterials(matfullPath);
    std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
    convertToUnixStylePath(fullPath);
    if (!initSystem(fullPath)){
        return false;
    }
    return true;
}
示例#11
0
/*
 * Main function. Parses command line arguments and launchs the simulator.
 */
int main (int argc, char **argv){
  int opt;

  // Default values
  NodesFct f = BasicBroadcast;
  int nb_nodes = 4;
  int nb_rounds = 20;

  // Parsing arguments
  while(-1 != (opt = getopt(argc, argv, "N:R:hibtpLTX"))){
    switch(opt){
      case 'N':
        nb_nodes = atoi(optarg);
        break;
      case 'R':
        nb_rounds = atoi(optarg);
        break;
      case 'h':
        display_help(stdout, argv[0]);
        return 0;
      case 'b':
        f = BasicBroadcast;
        break;
      case 't':
        f = TreeBroadcast;
        break;
      case 'p':
        f = PipelineBroadcast;
        break;
      case 'L':
        f = TOBLatencyBroadcast;
        break;
      case 'T':
        f = TOBThroughputBroadcast;
        break;
      case 'X':
        f = TOBThroughputRodBroadcast;
        break;
      default: /* WTF ? */
        fprintf(stderr, "Argument error...\n");
        display_help(stderr, argv[0]);
        exit(EXIT_FAILURE);
      }
  }

  // Do the simulation
  initSystem(nb_nodes, nb_rounds, f);
  LaunchSimulation();
  deleteSystem();
  return 0;
}
示例#12
0
bool SceneDemo::init()
{
    if(!initSystem("Scene Demo 4", 800, 600, false))
        return false;

    if(!map.load("graphics/map.map", "graphics/tiles.bmp"))
        return false;

    player = new MapNode(0, 10, 10, 50, 50, true, &map);

    scene.addNode(player);

    camera.set(0,0,800,600);

    return true;
}
示例#13
0
bool SceneDemo::init()
{
    if(!initSystem("Maze", 32 * 29, 32 * 29, false))
        return false;

    if(!map.load("graphics/map.map", "graphics/tiles.bmp"))
        return false;

    player = new MapNode(0, 14 * SPRITE_DIM, 0 * SPRITE_DIM, SPRITE_DIM, SPRITE_DIM, true, &map);

    scene.addNode(player);

    camera.set(0,0,928,928);

    return true;
}
示例#14
0
int main (int argc, char *argv[])
{
	char *configFile = NULL;
	char *outputFile = NULL;

	// Declare objects
	struct system System;
	struct tip Tip;
	struct space Space;
	struct graphene Graphene;
	struct substrate Substrate;

	initSystem(&System, &Tip, &Space, &Graphene, &Substrate);
	parseOptions(argc, argv, &configFile, &outputFile, &System, &Tip);
	parseFile(configFile, &System, &Tip, &Space, &Graphene, &Substrate);

	createSystem(&System, &Tip);
	createGraphene(&System, &Graphene);
//	transformCylindric(&System);
//	createSpace(&System, &Space);
	createTip(&System, &Tip);
	createSubstrate(&System, &Substrate);

	// Spheroidal Tip
	assignPointers(&System, &Tip, &Space, &Graphene, &Substrate);
	assignPotential(&System, &Tip, &Space, &Graphene, &Substrate);

	laplaceSpheroidal(&System, &Tip);

	retransformSpheroidal(&Tip);
	retransformCylindric(&System);

	saveData(outputFile, &System);

	// Visualize System if necessary
	if (System.visual)
	{
		initVisual();
		drawObjects(&System, &Tip, &Space, &Graphene, &Substrate);
	}

	free(System.points); // Free all points

	return EXIT_SUCCESS;
}
//! Initialize JDFTx.
//! The lattice vectors, sample counts and the scalar fields in fluidminimize.
//! are in the same order as in Fortran, and specified in Angstroms.
//! This interface takes care of giving the core of JDFTx reversed lattice directions
//! and sample counts, and for all unit conversions (energies in eV, distances in Angstrom etc.)
//! @param Rx (in, 3-vector) First lattice direction
//! @param Ry (in, 3-vector) Second lattice direction
//! @param Rz (in, 3-vector) Third lattice direction
//! @param Sx (in, integer) Number of FFT points along first lattice direction
//! @param Sy (in, integer) Number of FFT points along second lattice direction
//! @param Sz (in, integer) Number of FFT points along third lattice direction
DeclareFortranFunction(initjdftx)(double* Rx, double* Ry, double* Rz, int* Sx, int* Sy, int* Sz)
{
	//Open log file
	globalLog = fopen("FLULOG", "w");
	if(!globalLog)
	{	globalLog = stdout;
		logPrintf("WARNING: Could not open log file 'FLULOG' for writing, using standard output.\n");
	}
	
	//Initialize environment and print banner:
	const char* execName = "N/A (Running as a shared library providing fluid solvers)";
	initSystem(1, (char**)&execName);
	
	//Write a wrapper input file:
	FILE* fpWrap = fopen("FLUCAR.in", "w");
	if(!fpWrap) die("Could not write input-file wrapper. JDFTx-VASP interface needs write access to current directory.\n");
	fprintf(fpWrap,
		"lattice \\\n"
		"    %.15lf %.15lf %.15lf \\\n"
		"    %.15lf %.15lf %.15lf \\\n"
		"    %.15lf %.15lf %.15lf \n"
		"fftbox %d %d %d\n"
		"elec-cutoff 0\n"
		"symmetries none\n"
		"include FLUCAR\n",
		 Rz[0]*Angstrom, Ry[0]*Angstrom, Rx[0]*Angstrom,
		 Rz[1]*Angstrom, Ry[1]*Angstrom, Rx[1]*Angstrom,
		 Rz[2]*Angstrom, Ry[2]*Angstrom, Rx[2]*Angstrom,
		 *Sz, *Sy, *Sx);
	fclose(fpWrap);
	
	//Initialize system:
	parse("FLUCAR.in", e);
	system("rm FLUCAR.in");
	if(e.eVars.fluidParams.fluidType == FluidNone) die("No fluid model specified in FLUCAR.\n");
	if(e.iInfo.ionWidthMethod == IonInfo::IonWidthEcut)
	{	logPrintf("JDFTx interface does not have access to VASP energy cutoff:\n"
			"\tUsing FFTbox to determine nuclear width instead.\n");
		e.iInfo.ionWidthMethod = IonInfo::IonWidthFFTbox;
	}
	e.setup();
	Citations::add("JDFTx-VASP interface",
		"K. Mathew, R. Sundararaman, K. Letchworth-Weaver, T.A. Arias and R.G. Hennig (under preparation)");
	Citations::print();
}
示例#16
0
文件: cruise.cpp 项目: 33d/scummvm
void CruiseEngine::initialize() {
	PCFadeFlag = 0;
	_gameSpeed = GAME_FRAME_DELAY_1;
	_speedFlag = false;

	/*volVar1 = 0;
	 * fileData1 = 0; */

	/*PAL_fileHandle = -1; */

	// video init stuff

	initSystem();
	gfxModuleData_Init();

	// another bit of video init

	readVolCnf();
	_vm->_polyStruct = NULL;
}
示例#17
0
myWizard::myWizard(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::myWizard)
{
    setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowOpacity(1);
    ui->setupUi(this);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
    QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
    ui->label_show_gif->setHidden(true);
    ui->label_show_info->setHidden(true);
    ui->comboBox_phone_brife->setHidden(true);
    ui->comboBox_phone_detail->setHidden(true);
    ui->pushButton_complete->setHidden(true);
    ui->pushButton_set_phone->setHidden(true);
    ui->lineEdit_pass_confirm->setHidden(true);
    ui->lineEdit_other_phone->setHidden(true);
    ui->lineEdit_mail->setHidden(true);
    initSystem();
}
示例#18
0
//----------------------------------------------------------
//      Main entry point
//----------------------------------------------------------
int main(void)
{
    initSystem();

// ------------------------------------------
#ifdef USE_THREADS
    MESSAGE("Using threads");

    // never returns
    startThreads(appMain, systemMain);

    // if we're here, something went wrong
    ASSERT(!"systemMain returned?!");

// ------------------------------------------
#else

    ENABLE_INTS();

#ifdef USE_PROTOTHREADS
    startProtoSched();
#else
    MESSAGE("Not using threads");
    appMain();
#endif

    //
    // Do not allow to return from this function. The reason:
    // GCC 4.5+ disables interrupts after completion of main() function,
    // but MansOS applications may want to return from appMain()
    // and do all the "real work" in interrupt handlers.
    // Therefore, interrupts must be kept enabled.
    //
    for (;;) {}
#endif // USE_THREADS

    return 0;
}
示例#19
0
// A process dispatcher program
// @par: int                number of arguments
// @par: pointer pointer    process list file
// @ret: int
int main(int argc, char **argv) {
    if (argc != 2) {
        // Print directions if the file is not supplied and exit
        printf("You must supply a file to the program:\n"
                "$ hostd filename.txt\n");
        exit(0);
    }

    initSystem();

    char *filename = argv[1];
    readFile(filename, dispatcher);
    if (VERBOSE) printf("Done processing %s!\n", filename);

    // Set CPU start time to 0
    int time = 0;

    // Flag when a real time process is added to the real time queue
    int rtUpdated;

    // The system is running
    /*while (time < runtime) {*/
    while (time < 20) {
        printf("===============================================================================================================================\n");
        printf("Time (Quantum): %d\n", time);
        printf("===============================================================================================================================\n");

        rtUpdated = updateDispatcher(time);

        if (VERBOSEMEMMAP) {
            printf("Current %d MByte memory map (each line is 64 Mbyte).\n", host.memSpaceMax);
            int memUnit;
            for(memUnit = 0; memUnit < MAX_MEMSPACE; memUnit++) {
                if (host.memSpace[memUnit] != 0) {
                    printf("%d ", host.memSpace[memUnit]);
                } else {
                    if (memUnit < MAX_RTMEMSPACE) {
                        printf(". ");
                    } else {
                        printf("_ ");
                    }
                }

                if ((memUnit + 1) % 64 == 0) {
                    printf("\n");
                }
            }
            printf("\n");
        }

        if (VERBOSEQ) {
            printf("REAL TIME QUEUE:  ");
            printQueue(realTimeQueue);

            printf("PRIORITY 1 QUEUE: ");
            printQueue(p1Queue);

            printf("PRIORITY 2 QUEUE: ");
            printQueue(p2Queue);

            printf("PRIORITY 3 QUEUE: ");
            printQueue(p3Queue);

            //TODO
            //print info about system resources and per process resources?
        }

        doProcessing(time, rtUpdated);

        time++;

        sleep(1);
        printf("\n");
    }

    printf("===============================================================================================================================\n");
    printf("Time (Quantum): %d, program terminating\n", time);
    printf("===============================================================================================================================\n");

    closeSystem();

    return 0;
}
示例#20
0
int main(int argc, char** argv)
{	initSystem(argc, argv);

	//Parse command-line
	S2quadType quadType = QuadEuler;
	int nBeta = 12;
	if(argc > 1)
	{	if(!S2quadTypeMap.getEnum(argv[1], quadType))
			die("<quad> must be one of %s\n", S2quadTypeMap.optionList().c_str());
		if(quadType==QuadEuler)
		{	if(argc < 3) die("<nBeta> must be specified for Euler quadratures.\n")
			nBeta = atoi(argv[2]);
			if(nBeta <= 0) die("<nBeta> must be non-negative.")
		}
	}
	
	//Setup simulation grid:
	GridInfo gInfo;
	gInfo.S = vector3<int>(1, 1, 4096);
	const double hGrid = 0.0625;
	gInfo.R = Diag(hGrid * gInfo.S);
	gInfo.initialize();

	double T = 298*Kelvin;
	FluidComponent component(FluidComponent::H2O, T, FluidComponent::ScalarEOS);
	component.s2quadType = quadType;
	component.quad_nBeta = nBeta;
	component.representation = FluidComponent::Pomega;
	FluidMixture fluidMixture(gInfo, T);
	component.addToFluidMixture(&fluidMixture);
	double p = 1.01325*Bar;
	logPrintf("pV = %le\n", p*gInfo.detR);
	fluidMixture.initialize(p);

	//Initialize external potential (repel O from a cube)
	double Dfield = 1.0 * eV/Angstrom;
	const double zWall = 8.0 - 1e-3;
	const double& gridLength = gInfo.R(2,2);
	ScalarField phiApplied(ScalarFieldData::alloc(gInfo)), phiWall(ScalarFieldData::alloc(gInfo));
	applyFunc_r(gInfo, setPhi, phiApplied->data(), phiWall->data(), gridLength, Dfield, zWall);
	const double ZO = component.molecule.sites[0]->chargeKernel(0);
	component.idealGas->V[0] = ZO * phiApplied + phiWall;
	component.idealGas->V[1] = -0.5*ZO * phiApplied + phiWall;

	//----- Initialize state -----
	fluidMixture.initState(0.01);

	//----- FDtest and CG -----
	MinimizeParams mp;
	mp.fpLog = globalLog;
	mp.nDim = gInfo.nr * fluidMixture.get_nIndep();
	mp.energyLabel = "Phi";
	mp.nIterations=1500;
	mp.energyDiffThreshold=1e-16;
	
	fluidMixture.minimize(mp);
	
	//------ Outputs ---------
	ostringstream quadName;
	quadName << S2quadTypeMap.getString(quadType);
	if(quadType == QuadEuler) quadName << nBeta;
	
	ScalarFieldArray N;
	fluidMixture.getFreeEnergy(FluidMixture::Outputs(&N));
	FILE* fp = fopen((quadName.str()+".Nplanar").c_str(), "w");
	double* NOdata = N[0]->data();
	double* NHdata = N[1]->data();
	double nlInv = 1./component.idealGas->get_Nbulk();
	for(int i=0; i<gInfo.S[2]/2; i++)
		fprintf(fp, "%le\t%le\t%le\n", i*hGrid, nlInv*NOdata[i], 0.5*nlInv*NHdata[i]);
	fclose(fp);
	
	finalizeSystem();
	return 0;
}
示例#21
0
文件: goahead.c 项目: houzhenggang/MT
int main(int argc, char** argv)
{
/*
 *	Initialize the memory allocator. Allow use of malloc and start 
 *	with a 60K heap.  For each page request approx 8KB is allocated.
 *	60KB allows for several concurrent page requests.  If more space
 *	is required, malloc will be used for the overflow.
 */
	bopen(NULL, (60 * 1024), B_USE_MALLOC);
	signal(SIGPIPE, SIG_IGN);

	if (writeGoPid() < 0)
		return -1;
	if (initSystem() < 0)
		return -1;

/*
 *	Initialize the web server
 */
	if (initWebs() < 0) {
		return -1;
	}

#ifdef CONFIG_DUAL_IMAGE
/* Set stable flag after the web server is started */
	set_stable_flag();
#endif

#ifdef WEBS_SSL_SUPPORT
	websSSLOpen();
#endif

/*
 *	Basic event loop. SocketReady returns true when a socket is ready for
 *	service. SocketSelect will block until an event occurs. SocketProcess
 *	will actually do the servicing.
 */
	while (!finished) {
		if (socketReady(-1) || socketSelect(-1, 1000)) {
			socketProcess(-1);
		}
		websCgiCleanup();
		emfSchedProcess();
	}

#ifdef WEBS_SSL_SUPPORT
	websSSLClose();
#endif

#ifdef USER_MANAGEMENT_SUPPORT
	umClose();
#endif

/*
 *	Close the socket module, report memory leaks and close the memory allocator
 */
	websCloseServer();
	socketClose();
#ifdef B_STATS
	memLeaks();
#endif
	bclose();
	return 0;
}
示例#22
0
int Model::Heuristic()
{
	_start = clock();
	initSystem();
	for (t = 0; t < T; t++){
		for (v = 0; v < nVeh; v++){
			sys.vehicle[v].assigned = false;															//assigned is false by default: true if either assigned at the current time or moving
		}
		for (k = 0; k < nArc; k++){
			if (arc[k].from == arc[k].to) continue;
			if (t)	sys.Demand[t][k] += sys.Demand[t - 1][k];
			if (!(sys.Demand[t][k]))	continue;
			for (v = 0; v < nVeh; v++){
				if (sys.vehicle[v].to != arc[k].from)	continue;									//don't assign the vehicle if it is not in the station
				if (sys.vehicle[v].time != t){														//don't use the vehicle if it is moving											
					sys.vehicle[v].assigned = true;
					continue;
				}
				if (sys.vehicle[v].powLvl < arc[k].fcost + min(sys.Demand[t][k], sys.vehicle[v].cap) * arc[k].cost)	continue;	//don't use the vehicle if battery level is not enough
				if (!(sys.Demand[t][k]))	break;																					//break if demand is none
				bool overload = false;
				for (vector<int>::iterator itr = arc[k].track.begin(); itr != arc[k].track.end(); itr++){
					tau = t + abs(track[*itr].from - arc[k].from);
					if (tau < T && sys.TrackLoad[*itr][tau] >= maxL){
						overload = true;
						break;
					}
				}
				if (overload)	break;

				sys.route[k][v][t] = 1;																			//assign the vehicle which is available
				sys.customer[k][v][t] = min(sys.Demand[t][k], sys.vehicle[v].cap);								//the number of customers sent out
				sys.vehicle[v].powLvl -= arc[k].fcost + arc[k].cost * sys.customer[k][v][t];					//update vehicle status: battery level
				sys.vehicle[v].to = arc[k].to;																	//update vehicle status: arriving station
				sys.vehicle[v].time = t + arc[k].time;															//update vehicle status: arriving time
				sys.vehicle[v].assigned = true;																	//update vehicle status: assigned or not				
				sys.Demand[t][k] -= sys.customer[k][v][t];														//update demand	
				for (vector<int>::iterator itr = arc[k].track.begin(); itr != arc[k].track.end(); itr++){		//update track load
					tau = t + abs(track[*itr].from - arc[k].from);
					if (tau < T)	sys.TrackLoad[*itr][tau]++;
				}
			}
		}
		for (k = 0; k < nArc; k++){
			if (arc[k].from != arc[k].to)	continue;
			for (v = 0; v < nVeh; v++){
				if (!(sys.vehicle[v].assigned) && sys.vehicle[v].to == arc[k].to && sys.vehicle[v].time == t){
					sys.route[k][v][t] = 1;						//stay in the station if the vehicle is not assigned toward any other stations
					sys.NodeLoad[arc[k].to][t]++;				//update node load
					sys.vehicle[v].time = t + 1;					//update time
					sys.vehicle[v].powLvl += maxC;
				}
			}
		}
		//if node load maximum is reached -- cancel vehicles toward this station and/or cancel previous route
	}
	// compute the total cost
	sys.cost = 0;
	for (k = 0; k < nArc; k++){
		if (arc[k].from == arc[k].to)	continue;
		for (t = 0; t < T; t++){
			int val_y = sys.Demand[t][k];
			for (v = 0; v < nVeh; v++){
				sys.cost += arc[k].fcost * sys.route[k][v][t] + arc[k].cost * sys.customer[k][v][t];
				for (tau = t + 1; tau <= t + TimeWindow && tau < T; tau++){
					val_y -= sys.customer[k][v][tau];
				}
			}
			val_y = max(val_y, 0);
			sys.cost += penalty * arc[k].cost * val_y;
		}
	}

	for (v = 0; v < nVeh; v++){
		double rCost = 0;
		for (k = 0; k < nArc; k++){
			for (t = 0; t < T; t++){
				rCost += arc[k].fcost * sys.route[k][v][t] + arc[k].cost * sys.customer[k][v][t];
			}
		}
		sys.routeCost.push_back(rCost);
	}

	_end = clock();
	cmp_time = (double)(_end - _start) / CLOCKS_PER_SEC;

	sprintf(path, "%soutput/heuristic_%dV_%dN_%dArc_%dT.txt", directoryPath.c_str(), nVeh, N, nArc, T);
	heuristicSol();

	return 1;
}
示例#23
0
//################ Droplet on attractive wall ####################
int main(int argc, char** argv)
{	initSystem(argc, argv);

	GridInfo gInfo;
	gInfo.S = vector3<int>(64, 64, 64); double hGrid=1.0;
	//gInfo.S = vector3<int>(128, 128, 128); double hGrid=0.5;
	gInfo.R = Diag(gInfo.S * hGrid);
	gInfo.initialize();

	double T = 298*Kelvin;
	FluidComponent component(FluidComponent::H2O, T, FluidComponent::ScalarEOS);
	component.s2quadType = QuadOctahedron;
	component.Nnorm = 270;
	
	PreconditionedFluidMixture fluidMixture(gInfo, T, 1.0);
	component.addToFluidMixture(&fluidMixture);
	double p = 1.01325*Bar;
	logPrintf("pV = %le\n", p*gInfo.detR);
	fluidMixture.initialize(p);

	#define geomName "AttractiveWall-3bohr-3.0kT/drop_plane"

	bool loadState=false;
	const char stateFilename[] = "TestFixedN/" geomName "_state.bin";

	//Initialize potential: planar wall with attractive well:
	nullToZero(component.idealGas->V, gInfo);
	double xWall = 0.5*gInfo.R(0,0)-21.0;
	double dxWall = 2.0;
	applyFunc_r(gInfo, initAttractiveWall, xWall, dxWall, 100*T, 3.*T, component.idealGas->V[0]->data());

	if(loadState)
		fluidMixture.loadState(stateFilename);
	else
	{	//Initialize state biased towards center of cell
		const double muSet=-5.0;
		const double Rdroplet = 22.0; //guess droplet size:
		nullToZero(fluidMixture.state, gInfo, fluidMixture.get_nIndep());
		applyFunc_r(gInfo, initSphere, gInfo.R*vector3<>(0.5,0.5,0.5), Rdroplet, 0.0, muSet, fluidMixture.state[0]->data());

		RealKernel gauss(gInfo); initGaussianKernel(gauss, 2.0);
		fluidMixture.state[0] = I(gauss*J(fluidMixture.state[0]));

		ScalarField wallMask(ScalarFieldData::alloc(gInfo));
		applyFunc_r(gInfo, initAttractiveWall, xWall, 2*dxWall, 0.0, 1.0, wallMask->data());
		fluidMixture.state[0] *= (wallMask+1.0);
	}

	MinimizeParams mp;
	mp.fpLog = globalLog;
	mp.nDim = 2*gInfo.nr;
	mp.nIterations=10;
	mp.knormThreshold=1e-11;
	mp.dirUpdateScheme = MinimizeParams::FletcherReeves;
	//mp.dirUpdateScheme = MinimizeParams::SteepestDescent;
	//mp.updateTestStepSize = false;
	mp.fdTest = !loadState;

	int sysRet=system("mkdir -p TestFixedN/" geomName "_img");
	if(sysRet) { logPrintf("Error making image directory\n"); mpiUtil->exit(sysRet); }

	for(int loopCount=0; loopCount<100; loopCount++)
	{
		ScalarFieldArray N;
		TIME("getOmega calculation (with gradient)", globalLog,
			double omega = fluidMixture.getFreeEnergy(FluidMixture::Outputs(&N));
			if(std::isnan(omega)) break; //Don't save state after it has become nan
		);
		logPrintf("Ntot = %lf\n", gInfo.dV*sum(N[0]));

		logPrintf("Saving state:\n");
		fluidMixture.saveState(stateFilename);
		saveDX(N[0], "TestFixedN/" geomName "_nO");
		saveDX(N[1], "TestFixedN/" geomName "_nH");
		saveSphericalized(&N[0], 2, "TestFixedN/" geomName "_n.spherical", 0.25);
		//Invoke octave to create an image:
		FILE* pp = popen("octave -q", "w");
		fprintf(pp, "imwrite( waterSlice(\"TestFixedN/" geomName "_n%%s.bin\", [%d %d %d], 1, %d, 1e-2),", gInfo.S[0], gInfo.S[1], gInfo.S[2], gInfo.S[2]/2);
		fprintf(pp, " \"TestFixedN/" geomName "_img/img%04d.png\"); exit;\n", loopCount);
		fflush(pp); pclose(pp);

		logPrintf("Starting CG:\n");
		TIME("minimize", globalLog,
			fluidMixture.minimize(mp);
		);
示例#24
0
文件: pkg.c 项目: Laukien/Linux-Tools
int main(int argc, char *argv[]) {
	int ret = EXIT_SUCCESS;                     /* return value */

	/* check parameter */
	if (argc < 2) {
		fprintf(stderr, "ERROR: You need to give some command.\n");
		showHelp();
		return (EXIT_FAILURE);
	}

	initSystem();
	if (gSystem == SYSTEM_ERROR) {
		fprintf(stderr, "ERROR: No package-system found (yum, apt).\n");
		exit(EXIT_FAILURE);
	}

	initCommand(argv[1]);
	initList(argc - 2, (char **)argv + 2);

	switch (gCommand) {
		case COMMAND_HELP:
			showHelp();
			break;
		case COMMAND_VERSION:
			showVersion();
			break;
		case COMMAND_INSTALL:
			if (gList == NULL) {
				fprintf(stderr, "Error: Need to pass a list of pkgs to install.\n");
				showHelp();
				ret = EXIT_FAILURE;
				break;
			}
			doInstall();
			break;
		case COMMAND_REMOVE:
			if (gList == NULL) {
				fprintf(stderr, "Error: Need to pass a list of pkgs to remove.\n");
				showHelp();
				ret = EXIT_FAILURE;
				break;
			}
			doRemove();
			break;
		case COMMAND_SEARCH:
			if (gList == NULL) {
				fprintf(stderr, "Error: Need to pass a list of pkgs to search.\n");
				showHelp();
				ret = EXIT_FAILURE;
				break;
			}
			doSearch();
			break;
		case COMMAND_LIST:
			if (gList == NULL) {
				fprintf(stderr, "Error: Need to pass a list of pkgs to lisst.\n");
				showHelp();
				ret = EXIT_FAILURE;
				break;
			}
			doList();
			break;
		case COMMAND_UPDATE:
			if (gList == NULL) {
				fprintf(stderr, "Error: Need to pass a list of pkgs to update.\n");
				showHelp();
				ret = EXIT_FAILURE;
				break;
			}
			doUpdate();
			break;
		default:
			fprintf(stderr, "ERROR: No such command '%s'. Please use '%s --help'.\n", argv[1], PRG_NAME);
			ret = EXIT_FAILURE;
	}

	destroy();

	return (ret);
}
static void LaplacianDeformModifier_do(
        LaplacianDeformModifierData *lmd, Object *ob, DerivedMesh *dm,
        float (*vertexCos)[3], int numVerts)
{
	float (*filevertexCos)[3];
	int sysdif;
	LaplacianSystem *sys = NULL;
	filevertexCos = NULL;
	if (!(lmd->flag & MOD_LAPLACIANDEFORM_BIND)) {
		if (lmd->cache_system) {
			sys = lmd->cache_system;
			deleteLaplacianSystem(sys);
			lmd->cache_system = NULL;
		}
		lmd->total_verts = 0;
		MEM_SAFE_FREE(lmd->vertexco);
		return;
	}
	if (lmd->cache_system) {
		sysdif = isSystemDifferent(lmd, ob, dm, numVerts);
		sys = lmd->cache_system;
		if (sysdif) {
			if (sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_ANCHORS || sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_GROUP) {
				filevertexCos = MEM_mallocN(sizeof(float[3]) * numVerts, "TempModDeformCoordinates");
				memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts);
				MEM_SAFE_FREE(lmd->vertexco);
				lmd->total_verts = 0;
				deleteLaplacianSystem(sys);
				lmd->cache_system = NULL;
				initSystem(lmd, ob, dm, filevertexCos, numVerts);
				sys = lmd->cache_system; /* may have been reallocated */
				MEM_SAFE_FREE(filevertexCos);
				if (sys) {
					laplacianDeformPreview(sys, vertexCos);
				}
			}
			else {
				if (sysdif == LAPDEFORM_SYSTEM_CHANGE_VERTEXES) {
					modifier_setError(&lmd->modifier, "Vertices changed from %d to %d", lmd->total_verts, numVerts);
				}
				else if (sysdif == LAPDEFORM_SYSTEM_CHANGE_EDGES) {
					modifier_setError(&lmd->modifier, "Edges changed from %d to %d", sys->total_edges, dm->getNumEdges(dm));
				}
				else if (sysdif == LAPDEFORM_SYSTEM_CHANGE_NOT_VALID_GROUP) {
					modifier_setError(&lmd->modifier, "Vertex group '%s' is not valid", sys->anchor_grp_name);
				}
			}
		}
		else {
			sys->repeat = lmd->repeat;
			laplacianDeformPreview(sys, vertexCos);
		}
	}
	else {
		if (lmd->total_verts > 0 && lmd->total_verts == numVerts) {
			if (isValidVertexGroup(lmd, ob, dm)) {
				filevertexCos = MEM_mallocN(sizeof(float[3]) * numVerts, "TempDeformCoordinates");
				memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts);
				MEM_SAFE_FREE(lmd->vertexco);
				lmd->total_verts = 0;
				initSystem(lmd, ob, dm, filevertexCos, numVerts);
				sys = lmd->cache_system;
				MEM_SAFE_FREE(filevertexCos);
				laplacianDeformPreview(sys, vertexCos);
			}
		}
		else {
			if (isValidVertexGroup(lmd, ob, dm)) {
				initSystem(lmd, ob, dm, vertexCos, numVerts);
				sys = lmd->cache_system;
				laplacianDeformPreview(sys, vertexCos);
			}
		}
	}
	if (sys->is_matrix_computed && !sys->has_solution) {
		modifier_setError(&lmd->modifier, "The system did not find a solution");
	}
}
示例#26
0
int Model::Heuristic2()
{
	_start = clock();
	initSystem();
	for (t = 0; t < T; t++){
		//sort the arcs according to its demand
		vector<pair<int, double>> ArcDmd;
		for (k = 0; k < nArc; k++){
			if (arc[k].from == arc[k].to)	continue;
			if (t)	sys.Demand[t][k] += sys.Demand[t - 1][k];
			ArcDmd.push_back(pair<int, double>(k, penalty * arc[k].cost * sys.Demand[t][k]));
		}
		sort(ArcDmd.begin(), ArcDmd.end(),
			[](const pair<int, double>& lhs, const pair<int, double>& rhs) {
			return lhs.second > rhs.second; });
		//sort the vehicle battery level
		vector<pair<int, double>> Elvl;
		for (v = 0; v < nVeh; v++){
			sys.vehicle[v].assigned = false;															//reset all vehicles
			Elvl.push_back(pair<int, double>(v, sys.vehicle[v].powLvl));
		}
		sort(Elvl.begin(), Elvl.end(),
			[](const pair<int, double>& lhs, const pair<int, double>& rhs) {
			return lhs.second > rhs.second; });

		for (vector<pair<int, double>>::iterator vecItr = ArcDmd.begin(); vecItr != ArcDmd.end(); vecItr++){
			k = vecItr->first;
			if (arc[k].from == arc[k].to) continue;
			if (!(sys.Demand[t][k]))	continue;
			for (vector<pair<int, double>>::iterator vecItr2 = Elvl.begin(); vecItr2 != Elvl.end(); vecItr2++){
				v = vecItr2->first;
				if (sys.vehicle[v].to != arc[k].from)	continue;									//don't assign the vehicle if it is not in the station
				if (sys.vehicle[v].time != t){														//don't use the vehicle if it is moving											
					sys.vehicle[v].assigned = true;
					continue;
				}
				if (sys.vehicle[v].powLvl < arc[k].fcost + min(sys.Demand[t][k], sys.vehicle[v].cap) * arc[k].cost)	continue;	//don't use the vehicle if battery level is not enough
				if (!(sys.Demand[t][k]))	break;																					//break if demand is none
				bool overload = false;
				for (vector<int>::iterator itr = arc[k].track.begin(); itr != arc[k].track.end(); itr++){
					tau = t + abs(track[*itr].from - arc[k].from);
					if (tau < T && sys.TrackLoad[*itr][tau] >= maxL){
						overload = true;
						break;
					}
				}
				if (overload)	break;																			//no more vehicle assignment for this arc if overloaded

				sys.route[k][v][t] = 1;																			//assign the vehicle which is available
				sys.customer[k][v][t] = min(sys.Demand[t][k], sys.vehicle[v].cap);								//the number of customers sent out
				sys.vehicle[v].powLvl -= arc[k].fcost + arc[k].cost * sys.customer[k][v][t];					//update vehicle status: battery level
				sys.vehicle[v].to = arc[k].to;																	//update vehicle status: arriving station
				sys.vehicle[v].time = t + arc[k].time;															//update vehicle status: arriving time
				sys.vehicle[v].assigned = true;																	//update vehicle status: assigned or not

				sys.Demand[t][k] -= sys.customer[k][v][t];														//update demand	
				for (vector<int>::iterator itr = arc[k].track.begin(); itr != arc[k].track.end(); itr++){		//update track load
					tau = t + abs(track[*itr].from - arc[k].from);
					if (tau < T)	sys.TrackLoad[*itr][tau]++;
				}
			}
		}
		for (k = 0; k < nArc; k++){
			if (arc[k].from != arc[k].to)	continue;
			for (v = 0; v < nVeh; v++){
				if (!(sys.vehicle[v].assigned) && sys.vehicle[v].to == arc[k].to && sys.vehicle[v].time == t){
					sys.route[k][v][t] = 1;						//stay in the station if the vehicle is not assigned toward any other stations
					sys.NodeLoad[arc[k].to][t]++;				//update node load
					sys.vehicle[v].time = t + 1;					//update time
					sys.vehicle[v].powLvl += maxC;				//update battery level
				}
			}
		}
		//if node load maximum is reached -- cancel vehicles toward this station and/or cancel previous route
	}
	// compute the total cost
	sys.cost = 0;
	for (k = 0; k < nArc; k++){
		if (arc[k].from == arc[k].to)	continue;
		for (t = 0; t < T; t++){
			int val_y = sys.Demand[t][k];
			for (v = 0; v < nVeh; v++){
				sys.cost += arc[k].fcost * sys.route[k][v][t] + arc[k].cost * sys.customer[k][v][t];
				for (tau = t + 1; tau <= t + TimeWindow && tau < T; tau++){
					val_y -= sys.customer[k][v][tau];
				}
			}
			val_y = max(val_y, 0);
			sys.cost += penalty * arc[k].cost * val_y;
		}
	}

	for (v = 0; v < nVeh; v++){
		double rCost = 0;
		for (k = 0; k < nArc; k++){
			for (t = 0; t < T; t++){
				rCost += arc[k].fcost * sys.route[k][v][t] + arc[k].cost * sys.customer[k][v][t];
			}
		}
		sys.routeCost.push_back(rCost);
	}

	_end = clock();
	cmp_time = (double)(_end - _start) / CLOCKS_PER_SEC;

	sprintf(path, "%soutput/heuristic2_%dV_%dN_%dArc_%dT.txt", directoryPath.c_str(), nVeh, N, nArc, T);
	heuristicSol();

	return 1;
}
示例#27
0
/*********************************************************************//*!
 * @brief  The main program
 * 
 * Opens the camera and reads pictures as fast as possible
 * Makes a debayering of the image
 * Writes the debayered image to a buffer which can be read by
 * TCP clients on Port 8111. Several concurrent clients are allowed.
 * The simplest streaming video client looks like this:
 * 
 * nc 192.168.1.10 8111 | mplayer - -demuxer rawvideo -rawvideo w=376:h=240:format=bgr24:fps=100
 * 
 * Writes every 10th picture to a .jpg file in the Web Server Directory
 *//*********************************************************************/
int main(const int argc, const char * argv[])
{
	struct OSC_PICTURE calcPic;
	struct OSC_PICTURE rawPic;
	unsigned char *tmpbuf;
	int loops=0;	
	int numalarm=0;
	char filename[100];
	
	initSystem(&sys);

	ip_start_server();

	/* setup variables */
	rawPic.width = OSC_CAM_MAX_IMAGE_WIDTH;
	rawPic.height = OSC_CAM_MAX_IMAGE_HEIGHT;
	rawPic.type = OSC_PICTURE_GREYSCALE;

	/* calcPic width, height etc. are set in the debayering algos */
	calcPic.data = malloc(3 * OSC_CAM_MAX_IMAGE_WIDTH * OSC_CAM_MAX_IMAGE_HEIGHT);
	if (calcPic.data == 0)
		fatalerror("Did not get memory\n");
	tmpbuf = malloc(500000);
	if (tmpbuf == 0)
		fatalerror("Did not get memory\n");

	
	#if defined(OSC_TARGET)
		/* Take a picture, first time slower ;-) */
		usleep(10000); OscGpioTriggerImage(); usleep(10000);
		OscLog(DEBUG,"Triggered CAM ");
	#endif

	while(true) {

		OscCamReadPicture(OSC_CAM_MULTI_BUFFER, (void *) &rawPic.data, 0, 0);
		/* Take a picture */
		usleep(2000);
		OscCamSetupCapture(OSC_CAM_MULTI_BUFFER); 

		#if defined(OSC_TARGET)
			OscGpioTriggerImage();
		#else
			usleep(10000);
		#endif

		if (is_alarm(&rawPic)) {
			OscGpioSetTestLed(TRUE);
			printf("alarm\n");
			sprintf(filename, "/home/httpd/alarm_pic%02i.jpg", numalarm%16);
			writeJPG(&calcPic, tmpbuf, filename);
			numalarm++;
		} else {
			OscGpioSetTestLed(FALSE);
		}

		fastdebayerBGR(rawPic, &calcPic, NULL);

		ip_send_all((char *)calcPic.data, calcPic.width*calcPic.height*
                        OSC_PICTURE_TYPE_COLOR_DEPTH(calcPic.type)/8);

		loops+=1;
		if (loops%20 == 0) {
			writeJPG(&calcPic, tmpbuf, "/home/httpd/liveimage.jpg");
		}


                ip_do_work();
	
	}

	ip_stop_server();

	cleanupSystem(&sys);

	return 0;
} /* main */
示例#28
0
int main(void)
{
	/* Initialize System */
	initSystem();

	/* switch Spektrum Receiver ON */
	/* no Bind at the moment */
	*SPEKTRUM_BIND = 1;

	/* Init virtual EEPROM */
	initEEPROM();
	
  
	print_uart1("CorvusM3 FC - Version 0.1\r\n");
	
	// for test
	//char x [80];
	//sprintf(x,"%d:%d:%d\r\n",smoothValue(100,150,0),smoothValue(100,150,100),smoothValue(100,150,40));
	//print_uart1(x);
	
	
	// read sensors for calibration
	setLEDStatus(LED_FLASH);
	
	// read parameters from flash
	loadParameter();
	
	// function open ....
	setLEDStatus(LED_BLINK);
	
	
	// Controlloop --> statemachine() --> Timer 3
	TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
  
	while (1)
	{

		// test accu
		if (getParameter(PARA_VOLT) > ADCSensorValue[VOLT])
		{
			// low accu
			errorCode |= ERROR_AKKU; // set bit
		}
		else
		{
			// accu OK
			errorCode &= ~ERROR_AKKU; // delete bit
		}
		
		// if something in RxBuffer
		if (is_read_uart1())
		{
			getComm();
		}
		
		/* Debug Output 20Hz ---------------------------------------------------*/
		if (msCount % 50 == 0)
		{
			doDebug();
			
			// for test
			//char x [80];
			//sprintf(x,"%d\r\n",errorCode);
			//print_uart1(x);
		}
		

		
		/* do LED -----------------------------------------------------------*/
		if (errorCode == 0)
		{
			setLEDStatus(LED_ON);
		}
		else if (errorCode < 2) // akku
		{
			setLEDStatus(LED_BLINK);
		}
		else if (errorCode < 8) // rc and sensor
		{
			setLEDStatus(LED_FLASH);
		}
		
	}
}
示例#29
0
int main(void){
	state currentState = STATE_MM1;
	action actionToDo = NO_ACTION;
	
	// FSM state/action matrix
	stateElement stateMatrix[7][8] = {
		// MM1
		{{STATE_MM1, NO_ACTION}, {STATE_OFF, SWITCH_OFF}, {STATE_CHARGING, CHARGING}, {STATE_MM1, NO_ACTION}, {STATE_MM2, SHOW_MM2}, {STATE_MM2, SHOW_MM2}, {STATE_MM1, NO_ACTION}, {STATE_HISTORY, SHOW_HISTORY}},
		
		// OFF
		{{STATE_MM1, SHOW_MM1}, {STATE_OFF, NO_ACTION}, {STATE_OFF, NO_ACTION}, {STATE_OFF, NO_ACTION}, {STATE_OFF, NO_ACTION}, {STATE_OFF, NO_ACTION}, {STATE_OFF, NO_ACTION}, {STATE_OFF, NO_ACTION}},
		
		// CHARING
		{{STATE_CHARGING, NO_ACTION}, {STATE_CHARGING, NO_ACTION}, {STATE_CHARGING, NO_ACTION}, {STATE_MM1, SHOW_MM1}, {STATE_CHARGING, NO_ACTION}, {STATE_CHARGING, NO_ACTION}, {STATE_CHARGING, UPDATE_CHARGE}, {STATE_CHARGING, NO_ACTION}},
		
		// MM2
		{{STATE_MM2, NO_ACTION}, {STATE_OFF, SWITCH_OFF}, {STATE_CHARGING, CHARGING}, {STATE_MM2, NO_ACTION}, {STATE_MM1, SHOW_MM1}, {STATE_MM1, SHOW_MM1}, {STATE_MM2, NO_ACTION}, {STATE_RECORD, SHOW_RECORD}},
		
		// HISTORY
		{{STATE_HISTORY, NO_ACTION}, {STATE_OFF, SWITCH_OFF}, {STATE_CHARGING, CHARGING}, {STATE_HISTORY, NO_ACTION}, {STATE_SHOWLAP, SHOW_NEXT_LENGTH}, {STATE_SHOWLAP, SHOW_PREV_LENGTH}, {STATE_HISTORY, NO_ACTION}, {STATE_MM1, SHOW_MM1}},
		
		// SHOWLAP
		{{STATE_SHOWLAP, NO_ACTION}, {STATE_OFF, SWITCH_OFF}, {STATE_CHARGING, CHARGING}, {STATE_HISTORY, NO_ACTION}, {STATE_SHOWLAP, SHOW_NEXT_LENGTH}, {STATE_SHOWLAP, SHOW_PREV_LENGTH}, {STATE_HISTORY, NO_ACTION}, {STATE_HISTORY, SHOW_HISTORY}},
		
		// RECORD
		{{STATE_RECORD, NO_ACTION}, {STATE_OFF, SWITCH_OFF}, {STATE_CHARGING, CHARGING}, {STATE_RECORD, NO_ACTION}, {STATE_MM1, SHOW_MM1}, {STATE_MM1, SHOW_MM1}, {STATE_RECORD, UPDATE_RECORD}, {STATE_RECORD, ADD_LENGTH}}
	};
	
	initSystem();
	showMM1();
	
	while(1){
		event e = getEvent();
		
		// Obtain the next action
		stateElement stateEvaluation = stateMatrix[currentState][e];
		currentState = stateEvaluation.nextState;
		actionToDo = stateEvaluation.actionToDo;
		
		switch(actionToDo){
			case NO_ACTION:
				break;
			case SHOW_MM1:
				getBatteryPercentage();
				showMM1();
				break;
			case SWITCH_OFF:
				getBatteryPercentage();
				showOffScreen();
				_delay_ms(2000);
				switchOff();
				break;
			case CHARGING:
				initTimer();
				getBatteryPercentage();
				showChargingScreen();
				break;
			case SHOW_MM2:
				getBatteryPercentage();
				showMM2();
				break;
			case UPDATE_CHARGE:
				getBatteryPercentage();
				showChargingScreen();
				break;
			case SHOW_HISTORY:
				showHistoryTotal();
				break;
			case SHOW_NEXT_LENGTH:
				getNextLength();
				showLength();
				break;
			case SHOW_PREV_LENGTH:
				getPreviousLength();
				showLength();
				break;
			case SHOW_RECORD:
				initTimer();
				currentLength = 0;
				totLenTime = 0;
				showRecordScreen();
				break;
			case UPDATE_RECORD:
				totLenTime++;
				curLenTime++;
				showRecordScreen();
				break;
			case ADD_LENGTH:
				//curLenTime = 0;
				recordCurrentLength();
				showRecordScreen();
				break;
			default:
				break;
		}
	}
}