void draw(){

	

	//nEvals = 0;
	int perFrame=1;
	for (int i=0; i<perFrame; i++){
		double x0 = opt1->xBest[0];
		double y0 = opt1->xBest[1];
		double dfitness = opt1->step();
		double x1 = opt1->xNew[0];
		double y1 = opt1->xNew[1];
		if( dfitness > 0 ){ 
			SDL_SetRenderDrawColor( render, 0, 128, 0, 255 ); 
			printf( " %i %f \n", nEvals, opt1->bestFitness  );
			if( -opt1->bestFitness < tolerance){  
				printf( " CONVERGENCE ACHIEVED in %i iterations, fittness = %f \n", nEvals, opt1->bestFitness  );
				STOP = true; 
				break;  
			}
		}else  { 
			SDL_SetRenderDrawColor( render, 255, 0, 0, 50  ); 
		}
		SDL_RenderDrawLine    ( render,  x2i(x0), y2i(y0), x2i(x1), y2i(y1) );
	}

	SDL_RenderPresent( render );
	SDL_UpdateWindowSurface(window);

}
Beispiel #2
0
void draw(){
	//SDL_SetRenderDrawColor(render, 128, 128, 128, 255);
    //SDL_RenderClear(render);
	SDL_RenderCopy( render, tempTex, &SrcR, &DestR);

	int mouseX,mouseY;
	SDL_GetMouseState( &mouseX, &mouseY );

	double dfdx=0,dfdy=0;
	double x = i2x( mouseX );
	double y = i2y( mouseY );
	double f = warped_function( x, y, dfdx, dfdy );
	SDL_SetRenderDrawColor(render, 255, 0, 0, 255);
	SDL_RenderDrawLine    ( render, x2i( x ), y2i( y ), x2i( x - dfdx ), y2i( y - dfdy ) ); 
	//printf( " %f %f %f %f \n", x, y, dfdx, dfdy );

	SDL_RenderPresent( render );
	SDL_UpdateWindowSurface(window);
}
std::vector<tutor::PPoint2d> read_positions(char*  file_name) {
	std::vector<tutor::PPoint2d> x_2;
	double x, y;

	std::ifstream file(file_name);
	for (int i=0; i<N; i++) {
		file >> x >> y;
		tutor::PPoint2d  x2i(x, y, 1); 
		x_2.push_back(x2i);
	}
	return x_2;
}
Beispiel #4
0
void Grid::print_indices() const {

	// check indexing:
	if (!check()) {
		print_labels();
		return;
	}

	for (unsigned int i = 0; i < indexSize(); i++) {

		// get index set:
		MultiIndexed::IndexSet is = i2x(i);

		cout << "i = " << i << " --> ";
		for (unsigned int j = 0; j < is.size(); j++) {
			cout << "x(" << j << ") = " << is[j] << "  ";
		}
		cout << "---> i = " << x2i(is);
		cout << endl;
	}

}
int main(int argc, char **argv[])
{
	
	time_in_s				= 1;
	dist_in_cm				= 6.955e7;
	mass_in_g				= 1.989e27;
	dens_in_gccm			= mass_in_g/dist_in_cm/dist_in_cm/dist_in_cm;
    energy_in_erg			= mass_in_g*dist_in_cm*dist_in_cm/time_in_s/time_in_s;
    specenergy_in_ergperg	= energy_in_erg/mass_in_g;
    pressure_in_ergperccm	= energy_in_erg/dist_in_cm/dist_in_cm/dist_in_cm;
	
	//maxrho					= 1e8;
	
	SDF *sdfp;
	SPHbody *body;
	
	if (argc < 6){
		usage();
		return 0;
	}else {
		choice = atoi(argv[2]);
		pixels = atoi(argv[3]);
		xmax = atof(argv[4]);
		maxrho = atof(argv[5]);
	}
		
	sdfp = SDFreadf(argv[1], (void **)&body, &gnobj, &nobj, sizeof(SPHbody),
					"x", offsetof(SPHbody, x), &conf,
					"y", offsetof(SPHbody, y), &conf,
					"z", offsetof(SPHbody, z), &conf,
					"mass", offsetof(SPHbody, mass), &conf,
					"vx", offsetof(SPHbody, vx), &conf,
					"vy", offsetof(SPHbody, vy), &conf,
					"vz", offsetof(SPHbody, vz), &conf,
					"u", offsetof(SPHbody, u), &conf,
					"h", offsetof(SPHbody, h), &conf,
					"rho", offsetof(SPHbody, rho), &conf,
					"pr", offsetof(SPHbody, pr), &conf,
					"drho_dt", offsetof(SPHbody, drho_dt), &conf,
					"udot", offsetof(SPHbody, udot), &conf,
					"temp", offsetof(SPHbody, temp), &conf,
					"He4", offsetof(SPHbody, He4), &conf,
					"C12", offsetof(SPHbody, C12), &conf,
					"O16", offsetof(SPHbody, O16), &conf,
					"Ne20", offsetof(SPHbody, Ne20), &conf,
					"Mg24", offsetof(SPHbody, Mg24), &conf,
					"Si28", offsetof(SPHbody, Si28), &conf,
					"S32", offsetof(SPHbody, S32), &conf,
					"Ar36", offsetof(SPHbody, Ar36), &conf,
					"Ca40", offsetof(SPHbody, Ca40), &conf,
					"Ti44", offsetof(SPHbody, Ti44), &conf,
					"Cr48", offsetof(SPHbody, Cr48), &conf,
					"Fe52", offsetof(SPHbody, Fe52), &conf,
					"Ni56", offsetof(SPHbody, Ni56), &conf,
//					"abar", offsetof(SPHbody, abar), &conf,
//					"zbar", offsetof(SPHbody, zbar), &conf,
//					"ax", offsetof(SPHbody, ax), &conf,
//					"ay", offsetof(SPHbody, ay), &conf,
//					"az", offsetof(SPHbody, az), &conf,
//					"lax", offsetof(SPHbody, lax), &conf,
//					"lay", offsetof(SPHbody, lay), &conf,
//					"laz", offsetof(SPHbody, laz), &conf,
//					"gax", offsetof(SPHbody, gax), &conf,
//					"gay", offsetof(SPHbody, gay), &conf,
//					"gaz", offsetof(SPHbody, gaz), &conf,
//					"grav_mass", offsetof(SPHbody, grav_mass), &conf,
//					"phi", offsetof(SPHbody, phi), &conf,
//					"tacc", offsetof(SPHbody, tacc), &conf,
//					"idt", offsetof(SPHbody, idt), &conf,
//					"nbrs", offsetof(SPHbody, nbrs), &conf,
//					"ident", offsetof(SPHbody, ident), &conf,
//					"windid", offsetof(SPHbody, windid), &conf,
					//"useless", offsetof(SPHbody, useless), &conf,
					NULL);
	SDFgetfloatOrDefault(sdfp, "tpos",  &tpos, (float)0.0);
	
	singlPrintf("%s has %d particles.\n", argv[1], gnobj);
	
	ymax = xmax = xmax * dist_in_cm;
	
	double **dens;
	
	dens = (double **) malloc(pixels*sizeof(double *));
	for(i=0;i<pixels;i++){
		dens[i]  = (double *) malloc(pixels*sizeof(double));
	}
	
	double **img;
	
	img = (double **) malloc(pixels*sizeof(double *));
	for(i=0;i<pixels;i++){
		img[i]  = (double *) malloc(pixels*sizeof(double));
	}
	
	//fill arrays with 0s?
	for(i = 0; i < pixels; i++)
	{
		for(j = 0; j < pixels; j++)
		{
			img[i][j]=dens[i][j]=0;
		}
	}
	
	SPHbody *p;
	i=0;
	for(p = body; p < body+gnobj; p++)
	{
		//singlPrintf("%d / %d\n",i,gnobj-1);
		//cout << p << "/" << npart-1 << endl;
		
		if (fabs(p->z) < 2.0*p->h) 
		{
			
			x = p->x * dist_in_cm;
			y = p->y * dist_in_cm;
			z = p->z * dist_in_cm;
			h = p->h * dist_in_cm;
			rho = p->rho * dens_in_gccm;
			temp = p->temp;
			mass = p->mass * mass_in_g;
			
			h = sqrt(pow(h,2.0)-pow(z,2.0));
			
			x2i();
			y2j();
			r = 2*h*(pixels/(2.0*xmax));
			
			if (r==0)
			{
				//printf("found that r was too small, filling only 1 pixel\n");
				if (ic >= 0 && ic < pixels && jc >= 0 && jc < pixels)
				{
					dens[ic][jc] += rho;
					switch( choice )
					{
						case 1 :
							img[ic][jc] +=rho*rho;
							break;
						case 2 :
							img[ic][jc] += temp*rho;
							break;
					}
				}
				
			}
			else
			{
				for(imi = ic-2*r; imi < ic+2*r+1; imi++)
				{
					for(imj = jc-2*r; imj < jc+2*r+1; imj++)
					{
						if (imi >= 0 && imi < pixels && imj >= 0 && imj < pixels) // inside the image
						{
							rr = sqrt(pow((imi-ic),2.0)+pow((imj-jc),2.0));
							//cout << rr << "," << r << endl;
							if (rr <= r) // inside the circle
							{							
								dens[imi][imj] += rho;		
								switch( choice )
								{
									case 1 :
										img[imi][imj] += rho*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0);
										break;
									case 2 :
										img[imi][imj] += temp*rho;
										break;
								}
							}
						}
						
					}
				}	
			}
		}
		i++;
	}
	
	//open the stream file
	
	switch (choice){
		case 1:
			snprintf(csvfile, sizeof(csvfile), "%s_rho.csv", argv[1]);
			break;
		case 2:
			snprintf(csvfile, sizeof(csvfile), "%s_temp.csv", argv[1]);
			break;
	}
	
	FILE *stream, *fopen(), *vsz;
	/* declare a stream and prototype fopen */ 
	
	stream = fopen(csvfile,"w");
	
//	double maxv = 0.0;
//	double minv = pow(10.0,10.0);
	for(i = 0; i < pixels; i++)
	{
		for(j = 0; j < pixels; j++)
		{
			if (dens[i][j] != 0)
			{
				fprintf(stream,"%f ", (double)img[i][j]/(double)dens[i][j]);
//				fout << img[i][j]/dens[i][j] << " ";
//				if (img[i][j]/dens[i][j] < minv) {minv = img[i][j]/dens[i][j];}
//				if (img[i][j]/dens[i][j] > maxv) {maxv = img[i][j]/dens[i][j];}
			}
			else
			{fprintf(stream,"%f ", 0.0);}
			
		}
		fprintf(stream,"\n");
	}
	
	//close the stream file
	fclose(stream);
	
	char *cwd = getcwd(NULL, 0);

	
	switch (choice) {
		case 1:
			snprintf(vszfile, sizeof(vszfile), "%s_rho.vsz", argv[1]);
			snprintf(pdffile, sizeof(pdffile), "%s_rho.png", argv[1]);
			
			vsz = fopen(vszfile,"w");
			
			fprintf(vsz,"ImportFile2D(u'%s/%s', [u'ds'], invertrows=False, invertcols=False, transpose=True, linked=True)\n",cwd,csvfile);
			fprintf(vsz,"Add('page', name='page1', autoadd=False)\n");
			fprintf(vsz,"To('page1')\n");
			fprintf(vsz,"Add('graph', name='graph1', autoadd=False)\n");
			fprintf(vsz,"To('graph1')\n");
			fprintf(vsz,"Set('leftMargin', u'0cm')\n");
			fprintf(vsz,"Set('rightMargin', u'0cm')\n");
			fprintf(vsz,"Set('topMargin', u'0cm')\n");
			fprintf(vsz,"Set('bottomMargin', u'0cm')\n");
			fprintf(vsz,"Add('axis', name='x', autoadd=False)\n");
			fprintf(vsz,"Add('axis', name='y', autoadd=False)\n");
			fprintf(vsz,"To('y')\n");
			fprintf(vsz,"Set('direction', 'vertical')\n");
			fprintf(vsz,"To('..')\n");
			fprintf(vsz,"Add('label', name='label1', autoadd=False)\n");
			fprintf(vsz,"To('label1')\n");
			fprintf(vsz,"Set('label', u't=%f')\n",tpos);
			fprintf(vsz,"Set('xPos', [0.050000000000000003])\n");
			fprintf(vsz,"Set('yPos', [0.05000000000000002])\n");
			fprintf(vsz,"Set('Text/size', u'18pt')\n");
			fprintf(vsz,"Set('Text/color', u'black')\n");
			fprintf(vsz,"To('..')\n");
			fprintf(vsz,"Add('colorbar', name='colorbar1', autoadd=False)\n");
			fprintf(vsz,"To('colorbar1')\n");
			fprintf(vsz,"Set('image', u'image1')\n");
			fprintf(vsz,"Set('label', u'rho [g/cc]')\n");
			fprintf(vsz,"Set('autoExtend', False)\n");
			fprintf(vsz,"Set('autoExtendZero', False)\n");
			fprintf(vsz,"Set('TickLabels/color', u'black')\n");
			fprintf(vsz,"Set('vertPosn', u'top')\n");
			fprintf(vsz,"To('..')\n");
			fprintf(vsz,"Add('image', name='image1', autoadd=False)\n");
			fprintf(vsz,"To('image1')\n");
			fprintf(vsz,"Set('data', u'ds')\n");
			fprintf(vsz,"Set('min', 0.01)\n");
			fprintf(vsz,"Set('max', %f)\n",maxrho);
			fprintf(vsz,"Set('colorScaling', u'log')\n");
			fprintf(vsz,"Set('colorMap', u'heat2')\n");
			fprintf(vsz,"Set('colorInvert', True)\n");
			fprintf(vsz,"Set('smooth', True)\n");
			break;
		case 2:
			snprintf(vszfile, sizeof(vszfile), "%s_temp.vsz", argv[1]);
			snprintf(pdffile, sizeof(pdffile), "%s_temp.png", argv[1]);
			
			vsz = fopen(vszfile,"w");
			
			fprintf(vsz,"ImportFile2D(u'%s/%s', [u'ds'], invertrows=False, invertcols=False, transpose=True, linked=True)\n",cwd,csvfile);
			fprintf(vsz,"Add('page', name='page1', autoadd=False)\n");
			fprintf(vsz,"To('page1')\n");
			fprintf(vsz,"Add('graph', name='graph1', autoadd=False)\n");
			fprintf(vsz,"To('graph1')\n");
			fprintf(vsz,"Set('leftMargin', u'0cm')\n");
			fprintf(vsz,"Set('rightMargin', u'0cm')\n");
			fprintf(vsz,"Set('topMargin', u'0cm')\n");
			fprintf(vsz,"Set('bottomMargin', u'0cm')\n");
			fprintf(vsz,"Add('axis', name='x', autoadd=False)\n");
			fprintf(vsz,"Add('axis', name='y', autoadd=False)\n");
			fprintf(vsz,"To('y')\n");
			fprintf(vsz,"Set('direction', 'vertical')\n");
			fprintf(vsz,"To('..')\n");
			fprintf(vsz,"Add('label', name='label1', autoadd=False)\n");
			fprintf(vsz,"To('label1')\n");
			fprintf(vsz,"Set('label', u't=%f')\n",tpos);
			fprintf(vsz,"Set('xPos', [0.050000000000000003])\n");
			fprintf(vsz,"Set('yPos', [0.90000000000000002])\n");
			fprintf(vsz,"Set('Text/size', u'18pt')\n");
			fprintf(vsz,"Set('Text/color', u'white')\n");
			fprintf(vsz,"To('..')\n");
			fprintf(vsz,"Add('colorbar', name='colorbar1', autoadd=False)\n");
			fprintf(vsz,"To('colorbar1')\n");
			fprintf(vsz,"Set('image', u'image1')\n");
			fprintf(vsz,"Set('autoExtend', False)\n");
			fprintf(vsz,"Set('autoExtendZero', False)\n");
			fprintf(vsz,"Set('TickLabels/color', u'white')\n");
			fprintf(vsz,"To('..')\n");
			fprintf(vsz,"Add('image', name='image1', autoadd=False)\n");
			fprintf(vsz,"To('image1')\n");
			fprintf(vsz,"Set('data', u'ds')\n");
			fprintf(vsz,"Set('min', 2e8)\n");
			fprintf(vsz,"Set('max', 'Auto')\n");
			fprintf(vsz,"Set('colorScaling', u'linear')\n");
			fprintf(vsz,"Set('colorMap', u'spectrum')\n");
			fprintf(vsz,"Set('colorInvert', False)\n");
			fprintf(vsz,"Set('smooth', True)\n");
			break;
	}

	fclose(vsz);
	
	return 0;
}
Beispiel #6
0
// TODO: Add the ability to set a maximum number of iterations
inline BigInt FindFactor
( const BigInt& n,
  Int a,
  const PollardRhoCtrl& ctrl )
{
    if( a == 0 || a == -2 )
        Output("WARNING: Problematic choice of Pollard rho shift");
    BigInt tmp, gcd;
    BigInt one(1);

    auto xAdvance =
      [&]( BigInt& x )
      {
        if( ctrl.numSteps == 1 )
        {
            // TODO: Determine if there is a penalty to x *= x
            /*
            tmp = x;
            tmp *= x;
            tmp += a;
            x = tmp;
            x %= n;
            */
            x *= x;
            x += a;
            x %= n;
        }
        else
        {
            PowMod( x, 2*ctrl.numSteps, n, x );
            x += a;
            x %= n;
        }
      };

    auto QAdvance =
      [&]( const BigInt& x, const BigInt& x2, BigInt& Q )
      {
        tmp = x2;
        tmp -= x;
        Q *= tmp;
        Q %= n;
      };

    Int gcdDelay = ctrl.gcdDelay;
    BigInt xi=ctrl.x0;
    BigInt x2i(xi);
    BigInt xiSave=xi, x2iSave=x2i;
    BigInt Qi(1);
    Int k=1, i=1; // it is okay for i to overflow since it is just for printing
    while( true )
    {
        // Advance xi once
        xAdvance( xi );

        // Advance x2i twice
        xAdvance( x2i );
        xAdvance( x2i );

        // Advance Qi
        QAdvance( xi, x2i, Qi );

        if( k >= gcdDelay )
        {
            GCD( Qi, n, gcd );
            if( gcd > one )
            {
                // NOTE: This was not suggested by Pollard's original paper
                if( gcd == n )
                {
                    if( gcdDelay == 1 )
                    {
                        RuntimeError("(x) converged before (x mod p) at i=",i);
                    }
                    else
                    {
                        if( ctrl.progress )
                            Output("Backtracking at i=",i);
                        i = Max( i-(gcdDelay+1), 0 );
                        gcdDelay = 1;
                        xi = xiSave;
                        x2i = x2iSave;
                    }
                }
                else
                {
                    if( ctrl.progress )
                        Output("Found factor ",gcd," at i=",i); 
                    return gcd;
                }
            }

            // NOTE: This was not suggested by Pollard's original paper
            k = 0;
            xiSave = xi;
            x2iSave = x2i;
            Qi = 1;
        }
        ++k;
        ++i;
    }
}
Beispiel #7
0
// we use morse code to transfer Security, SSID, Password, Key, REGDOMAIN, CRC8 to IRKit device
// SSID can be multi byte, so we transfer HEX 4bit as 1 ASCII character (0-9A-F),
// so we need 2 morse letters to transfer a single character.
// we might want to transfer more in the future (like static IP), so prepare reserved state
// future iOS and firmware can support more parameters, while still supporting old firmware
// [0248]/#{SSID}/#{Password}/#{Key}/#{RegDomain}//////#{CRC}
int8_t Keys::put(char code)
{
    static uint8_t  character;
    static bool     is_first_byte;
    static char    *container = 0;
    static uint8_t  max_length;

    if (code == MORSE_CREDENTIALS_SEPARATOR) {
        // null terminate
        switch (filler.state) {
        case KeysFillerStateSSID:
        case KeysFillerStatePassword:
        case KeysFillerStateKey:
            container[ filler.index ] = 0;
            break;
        default:
            break;
        }
        if (filler.state != KeysFillerStateCRC) {
            // wait for putDone() on CRC state

            filler.state = (KeysFillerState)( filler.state + 1 );

            switch (filler.state) {
            case KeysFillerStateSSID:
                container  = data->ssid;
                max_length = MAX_WIFI_SSID_LENGTH;
                break;
            case KeysFillerStatePassword:
                container  = data->password;
                max_length = MAX_WIFI_PASSWORD_LENGTH;
                break;
            case KeysFillerStateKey:
                container  = data->temp_key;
                max_length = MAX_KEY_LENGTH;
                break;
            case KeysFillerStateRegdomain:
                // defaults to 2
                regdomain = REGDOMAIN_TELEC;
                break;
            default:
                break;
            }
        }
        is_first_byte = true;
        filler.index  = 0;
        return 0;
    }
    if ( ! (('0' <= code) && (code <= '9')) &&
         ! (('A' <= code) && (code <= 'F')) ) {
        // we only use letters which match: [0-9A-F]
        KEYLOG_PRINT("!E23:"); KEYLOG_PRINTLN2( code, HEX );
        return -1;
    }
    if (filler.state == KeysFillerStateSecurity) {
        switch (code) {
        case '3':
            // start of the 1st sine wave includes envelope = fadein effect
            // so 1st short sound can be mistaken as long sound,
            // fix it (3: _ _ -> 2: . _)
            code = '2';
            // continues vv

        // we try OPEN when WEP failed, to present less options to user
        case '0': // GSwifi::GSSECURITY_NONE:
        // case '1': // GSwifi::GSSECURITY_OPEN:
        case '2': // GSwifi::GSSECURITY_WEP:
        case '4': // GSwifi::GSSECURITY_WPA_PSK:
        case '8': // GSwifi::GSSECURITY_WPA2_PSK:
            data->security = (GSSECURITY)x2i(code);
            return 0;
        default:
            KEYLOG_PRINT("!E22:"); KEYLOG_PRINTLN2( code, HEX );
            return -1;
        }
    }

    if (filler.state == KeysFillerStateRegdomain) {
        if ( (code < REGDOMAIN_MIN) ||
             (code > REGDOMAIN_MAX) ) {
            KEYLOG_PRINTLN("!E29");
            return -1;
        }
        regdomain = code;
        return 0;
    }

    if (filler.state == KeysFillerStateKey) {
        character = code;
    }
    else {
        // ssid, password might be Japanese character,
        // so we transfer utf8 bytes 0x00-0xFF as pair of [0-F] ASCII letters
        // so 2 bytes construct 1 character, network *bit* order
        // also CRC is transfered in HEX (pair of [0-F] ASCII letters)
        if (is_first_byte) {
            character       = x2i(code);
            character     <<= 4;        // F0h
            is_first_byte   = false;
            return 0;
        }
        else {
            character     += x2i(code); // 0Fh
            is_first_byte  = true;
        }
    }

    if (filler.state == KeysFillerStateCRC) {
        if (filler.index > 0) {
            KEYLOG_PRINTLN("!E21");
            return -1;
        }
        data->crc8 = character;
        filler.index ++;
        return 0;
    }

    if ( filler.index == max_length ) {
        KEYLOG_PRINTLN("!E18");
        return -1;
    }
    container[ filler.index ++ ] = character;
    return 0;
}
int main()
{
	SDF *sdfp;
	SPHbody *body;
	
	printf("SDF file: ");
	gets (sdffile);
		
	sdfp = SDFreadf(sdffile, (void **)&body, &gnobj, &nobj, sizeof(SPHbody),
					"x", offsetof(SPHbody, x), &conf,
					"y", offsetof(SPHbody, y), &conf,
					"z", offsetof(SPHbody, z), &conf,
					"mass", offsetof(SPHbody, mass), &conf,
					"vx", offsetof(SPHbody, vx), &conf,
					"vy", offsetof(SPHbody, vy), &conf,
					"vz", offsetof(SPHbody, vz), &conf,
					"u", offsetof(SPHbody, u), &conf,
					"h", offsetof(SPHbody, h), &conf,
					"rho", offsetof(SPHbody, rho), &conf,
					"pr", offsetof(SPHbody, pr), &conf,
					"drho_dt", offsetof(SPHbody, drho_dt), &conf,
					"udot", offsetof(SPHbody, udot), &conf,
					"temp", offsetof(SPHbody, temp), &conf,
					"He4", offsetof(SPHbody, He4), &conf,
					"C12", offsetof(SPHbody, C12), &conf,
					"O16", offsetof(SPHbody, O16), &conf,
					"Ne20", offsetof(SPHbody, Ne20), &conf,
					"Mg24", offsetof(SPHbody, Mg24), &conf,
					"Si28", offsetof(SPHbody, Si28), &conf,
					"S32", offsetof(SPHbody, S32), &conf,
					"Ar36", offsetof(SPHbody, Ar36), &conf,
					"Ca40", offsetof(SPHbody, Ca40), &conf,
					"Ti44", offsetof(SPHbody, Ti44), &conf,
					"Cr48", offsetof(SPHbody, Cr48), &conf,
					"Fe52", offsetof(SPHbody, Fe52), &conf,
					"Ni56", offsetof(SPHbody, Ni56), &conf,
					"abar", offsetof(SPHbody, abar), &conf,
					"zbar", offsetof(SPHbody, zbar), &conf,
					"ax", offsetof(SPHbody, ax), &conf,
					"ay", offsetof(SPHbody, ay), &conf,
					"az", offsetof(SPHbody, az), &conf,
					"lax", offsetof(SPHbody, lax), &conf,
					"lay", offsetof(SPHbody, lay), &conf,
					"laz", offsetof(SPHbody, laz), &conf,
					"gax", offsetof(SPHbody, gax), &conf,
					"gay", offsetof(SPHbody, gay), &conf,
					"gaz", offsetof(SPHbody, gaz), &conf,
					"grav_mass", offsetof(SPHbody, grav_mass), &conf,
					"phi", offsetof(SPHbody, phi), &conf,
					"tacc", offsetof(SPHbody, tacc), &conf,
					"idt", offsetof(SPHbody, idt), &conf,
					"nbrs", offsetof(SPHbody, nbrs), &conf,
					"ident", offsetof(SPHbody, ident), &conf,
					"windid", offsetof(SPHbody, windid), &conf,
					//"useless", offsetof(SPHbody, useless), &conf,
					NULL);
	
	singlPrintf("%s has %d particles.\n", sdffile, gnobj);
	
	printf("\nOutput Parameters \n-----------------\nChoose an Isotope:\n");
	printf("0)  He4 \n1)  C12 \n2)  O16 \n3)  Ne20\n4)  Mg24\n5)  Si28\n");
	printf("6)  S32 \n7)  Ar36\n8)  Ca40\n9)  Ti44\n10) Cr48\n11) Fe52\n");
	printf("12) Ni56\n13) C+O \n\nChoice:");
	scanf("%d", &choice);
	
	printf("Pixels on a side:");
	scanf("%d", &pixels);
	
	printf("xmax:");
	scanf("%f", &xmax);
	ymax = xmax;
	
	double **dens;
	
	dens = (double **) malloc(pixels*sizeof(double *));
	for(i=0;i<pixels;i++){
		dens[i]  = (double *) malloc(pixels*sizeof(double));
	}
	
	double **img;
	
	img = (double **) malloc(pixels*sizeof(double *));
	for(i=0;i<pixels;i++){
		img[i]  = (double *) malloc(pixels*sizeof(double));
	}
	
	//fill arrays with 0s?
	for(i = 0; i < pixels; i++)
	{
		for(j = 0; j < pixels; j++)
		{
			img[i][j]=dens[i][j]=0;
		}
	}
	
	SPHbody *p;
	
	for(p = body; p < body+gnobj; p++)
	{
		singlPrintf("%d / %d\n",p->ident,gnobj-1);
		
		if (fabs(p->z) < p->h) 
		{
			
			x = p->x;
			y = p->y;
			z = p->z;
			h = p->h;
			rho = p->rho;
			
			h = sqrt(pow(h,2.0)-pow(z,2.0));
			
			x2i();
			y2j();
			r = h*(pixels/(2.0*xmax));
			
			if (r==0)
			{
				printf("found that r was too small, filling only 1 pixel\n");
				if (ic >= 0 && ic < pixels && jc >= 0 && jc < pixels)
				{
					dens[ic][jc] += rho;
					switch( choice )
					{
						case 0: img[ic][jc] += p->He4*rho; break;
						case 1: img[ic][jc] += p->C12*rho; break;
						case 2: img[ic][jc] += p->O16*rho; break;
						case 3: img[ic][jc] += p->Ne20*rho; break;
						case 4: img[ic][jc] += p->Mg24*rho; break;
						case 5: img[ic][jc] += p->Si28*rho; break;
						case 6: img[ic][jc] += p->S32*rho; break;
						case 7: img[ic][jc] += p->Ar36*rho; break;
						case 8: img[ic][jc] += p->Ca40*rho; break;
						case 9: img[ic][jc] += p->Ti44*rho; break;
						case 10: img[ic][jc] += p->Cr48*rho; break;
						case 11: img[ic][jc] += p->Fe52*rho; break;
						case 12: img[ic][jc] += p->Ni56*rho; break;
						case 13: img[ic][jc] += (p->C12 + p->O16)*rho; break;
					}
				}				
			}
			else
			{
				for(imi = ic-2*r; imi < ic+2*r+1; imi++)
				{
					for(imj = jc-2*r; imj < jc+2*r+1; imj++)
					{
						if (imi >= 0 && imi < pixels && imj >= 0 && imj < pixels) // inside the image
						{
							rr = sqrt(pow((imi-ic),2.0)+pow((imj-jc),2.0));
							//cout << rr << "," << r << endl;
							if (rr <= 2*r) // inside the circle
							{							
								dens[imi][imj] += rho;		
								switch( choice )
								{
									case 0: img[imi][imj] += p->He4*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 1: img[imi][imj] += p->C12*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 2: img[imi][imj] += p->O16*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 3: img[imi][imj] += p->Ne20*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 4: img[imi][imj] += p->Mg24*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 5: img[imi][imj] += p->Si28*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 6: img[imi][imj] += p->S32*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 7: img[imi][imj] += p->Ar36*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 8: img[imi][imj] += p->Ca40*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 9: img[imi][imj] += p->Ti44*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 10: img[imi][imj] += p->Cr48*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 11: img[imi][imj] += p->Fe52*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 12: img[imi][imj] += p->Ni56*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
									case 13: img[imi][imj] += (p->C12 + p->O16)*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0); break;
								}
							}
						}
						
					}
				}	
			}
		}
	}
	
	//open the stream file
	snprintf(csvfile, sizeof(csvfile), "%d.%s.csv", choice, sdffile);
	FILE *stream, *fopen();
	/* declare a stream and prototype fopen */ 
	
	stream = fopen(csvfile,"w");
	
//	double maxv = 0.0;
//	double minv = pow(10.0,10.0);
	for(i = 0; i < pixels; i++)
	{
		for(j = 0; j < pixels; j++)
		{
			if (dens[i][j] != 0)
			{
				fprintf(stream,"%f ", (double)img[i][j]/(double)dens[i][j]);
//				fout << img[i][j]/dens[i][j] << " ";
//				if (img[i][j]/dens[i][j] < minv) {minv = img[i][j]/dens[i][j];}
//				if (img[i][j]/dens[i][j] > maxv) {maxv = img[i][j]/dens[i][j];}
			}
			else
			{fprintf(stream,"%f ", 0.0);}
			
		}
		fprintf(stream,"\n");
	}
	
	//close the stream file
	fclose(stream);
	
	return 0;
}
Beispiel #9
0
int main(int argc, char **argv[])
{
	SDF *sdfp;
	SPHbody *body;
	
	if (argc < 2){
		printf("SDF file: ");
		gets (argv[1]);
	}
		
	sdfp = SDFreadf(argv[1], (void **)&body, &gnobj, &nobj, sizeof(SPHbody),
					"x", offsetof(SPHbody, x), &conf,
					"y", offsetof(SPHbody, y), &conf,
					"z", offsetof(SPHbody, z), &conf,
					"mass", offsetof(SPHbody, mass), &conf,
					"vx", offsetof(SPHbody, vx), &conf,
					"vy", offsetof(SPHbody, vy), &conf,
					"vz", offsetof(SPHbody, vz), &conf,
					"u", offsetof(SPHbody, u), &conf,
					"h", offsetof(SPHbody, h), &conf,
					"rho", offsetof(SPHbody, rho), &conf,
					"pr", offsetof(SPHbody, pr), &conf,
//					"drho_dt", offsetof(SPHbody, drho_dt), &conf,
//					"udot", offsetof(SPHbody, udot), &conf,
					"temp", offsetof(SPHbody, temp), &conf,
					"He4", offsetof(SPHbody, He4), &conf,
					"C12", offsetof(SPHbody, C12), &conf,
					"O16", offsetof(SPHbody, O16), &conf,
					"Ne20", offsetof(SPHbody, Ne20), &conf,
					"Mg24", offsetof(SPHbody, Mg24), &conf,
					"Si28", offsetof(SPHbody, Si28), &conf,
					"S32", offsetof(SPHbody, S32), &conf,
					"Ar36", offsetof(SPHbody, Ar36), &conf,
					"Ca40", offsetof(SPHbody, Ca40), &conf,
					"Ti44", offsetof(SPHbody, Ti44), &conf,
					"Cr48", offsetof(SPHbody, Cr48), &conf,
					"Fe52", offsetof(SPHbody, Fe52), &conf,
					"Ni56", offsetof(SPHbody, Ni56), &conf,
//					"abar", offsetof(SPHbody, abar), &conf,
//					"zbar", offsetof(SPHbody, zbar), &conf,
//					"ax", offsetof(SPHbody, ax), &conf,
//					"ay", offsetof(SPHbody, ay), &conf,
//					"az", offsetof(SPHbody, az), &conf,
//					"lax", offsetof(SPHbody, lax), &conf,
//					"lay", offsetof(SPHbody, lay), &conf,
//					"laz", offsetof(SPHbody, laz), &conf,
//					"gax", offsetof(SPHbody, gax), &conf,
//					"gay", offsetof(SPHbody, gay), &conf,
//					"gaz", offsetof(SPHbody, gaz), &conf,
//					"grav_mass", offsetof(SPHbody, grav_mass), &conf,
//					"phi", offsetof(SPHbody, phi), &conf,
//					"tacc", offsetof(SPHbody, tacc), &conf,
//					"idt", offsetof(SPHbody, idt), &conf,
//					"nbrs", offsetof(SPHbody, nbrs), &conf,
//					"ident", offsetof(SPHbody, ident), &conf,
//					"windid", offsetof(SPHbody, windid), &conf,
					//"useless", offsetof(SPHbody, useless), &conf,
					NULL);
	
	SDFgetfloatOrDefault(sdfp, "tpos",  &tpos, (float)0.0);
	
	singlPrintf("%s has %d particles.\n", argv[1], gnobj);
	
	if (argc < 3){
		printf("Blocks on a side:");
		scanf("%d", &pixels);
	}
	else {
		pixels = atoi(argv[2]);
	}
	
	if (argc < 4){
		printf("xmax:");
		scanf("%f", &xmax);
	}
	else {
		xmax = atof(argv[3]);
	}

	ymax = zmax = xmax;
	
	double **outArray;
	
	outArray = (double **) malloc(pixels*pixels*pixels*sizeof(double *));
	for(i=0;i<(pixels*pixels*pixels);i++){
		outArray[i]  = (double *) malloc(6*sizeof(double));
	}
	
	for (i=0; i<pixels; i++) {
		for (j=0; j<pixels; j++) {
			for (k=0; k<pixels; k++) {
				ind = i*pixels*pixels + j*pixels + k;
				
				outArray[ind][0]=i;
				outArray[ind][1]=j;
				outArray[ind][2]=k;
				outArray[ind][3]=0;
				outArray[ind][4]=0;
				outArray[ind][5]=0;
			}
		}
	}
	
	SPHbody *p;
	
	printf("Anchoring to grid...\n");
	
	for(p = body; p < body+gnobj; p++)
	{
		//singlPrintf("%d / %d\n",p->ident,gnobj-1);
		//cout << p << "/" << npart-1 << endl;
		
		x = p->x;
		y = p->y;
		z = p->z;
		h = p->h;
		rho = p->rho;
		temp = p->temp;
		mass = p->mass;
		
		x2i();
		y2j();
		z2k();

		r = h*(pixels/(2.0*xmax));
		
		if (r==0)
		{
			//printf("found that r was too small, filling only 1 block\n");
			if (ic >= 0 && ic < pixels && jc >= 0 && jc < pixels && kc >= 0 && kc < pixels)
			{
				ind = ic*pixels*pixels + jc*pixels + kc;
				outArray[ind][5] += rho;
				outArray[ind][4] += temp*rho;
				outArray[ind][3] += rho*rho;
			}
			
		}
		else
		{
			for(imi = ic-2*r; imi < ic+2*r+1; imi++)
			{
				for(imj = jc-2*r; imj < jc+2*r+1; imj++)
				{
					for (imk = kc-2*r; imk < kc+2*r+1; imk++) {
						if (imi >= 0 && imi < pixels && imj >= 0 && imj < pixels && imk >= 0 && imk < pixels) // inside the image
						{
							rr = sqrt(pow((imi-ic),2.0)+pow((imj-jc),2.0)+pow((imk-kc),2.0));
							if (rr <= 2*r) // inside the circle
							{							
								ind = imi*pixels*pixels + imj*pixels + imk;
								outArray[ind][5] += rho;
								outArray[ind][4] += temp*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0);
								outArray[ind][3] += rho*rho*w(h,2*rr*(double)xmax/(double)pixels)*pi*pow(h,3.0);
							}
						}
					}
				}
			}	
		}
	}
	
	printf("Writing to file...\n");
	
	//open the stream file
	snprintf(csvfile, sizeof(csvfile), "%f.cube", tpos);
	FILE *stream, *fopen();
	/* declare a stream and prototype fopen */ 
	
	stream = fopen(csvfile,"w");
	
	for(i=0;i<(pixels*pixels*pixels);i++){
		if (outArray[i][5] != 0) {
			fprintf(stream,"%f %f %f %g %g\n",outArray[i][0],outArray[i][1],outArray[i][2],
										(double)outArray[i][3]/(double)outArray[i][5],
										(double)outArray[i][4]/(double)outArray[i][5]);
		}
		else {
			fprintf(stream,"%f %f %f %d %d\n",outArray[i][0],outArray[i][1],outArray[i][2],0,0);
		}
	}

	//close the stream file
	fclose(stream);
	free(outArray);
	
	return 0;
}
Beispiel #10
0
int main() {
	std::vector<cv::Point3d>x_1;
	std::vector<cv::Point3d>x_2;
	double x, y;

	std::ifstream file2("chess1.txt");
	// std::ifstream file2("chess1.txt");
	for (int i=0; i<N; i++) {
		file2 >> x >> y;
		cv::Point3d  x1i(x, y, 1);
		x_1.push_back(x1i);
	}
	std::cout << "x_1 = " <<   x_1 << endl;
	std::ifstream file3( "chess2.txt");
	// std::ifstream file3( "chess2.txt");
	for (int i=0; i<N; i++) {
		file3 >> x >> y;
		cv::Point3d  x2i(x, y, 1); 
		x_2.push_back(x2i);
	}
	std::cout << "x_2 = " <<  x_2 << endl;

	//////////  Camera1  focal length: 18mm,  sensor size:  23.5 x 15.7mm,
	Camera c1;
	c1.set_focal(18);
	c1.set_ccd(23);
	Camera c2;
	c2.set_focal(18);
	c2.set_ccd(23);

	cv::Mat A;
	for (int i=0; i<(int)x_1.size(); i++) {
		// std::cout << "i=" << i << ",  x_1=" << x_1[i] << ",  x_2=" << x_2 [i]<< std::endl;
		int x1 = x_1[i].x, y1 = x_1[i].y, w1 = x_1[i].z;
		int x2 = x_2[i].x, y2 = x_2[i].y, z2 = x_2[i].z;
		// Ai = (0   -w*X y*X
		//		 w*X 0    -x*X)
		cv::Mat  Ai = (cv::Mat_<double> (2,9)  << 0, 0,0,  -w1*x2, -w1*y2, -w1*z2,   y1*x2, y1*y2, y1*z2,
					w1*x2, w1*y2, w1*z2, 0, 0, 0,  -x1*x2, -x1*y2, -x1*z2);
		A.push_back(Ai);
	}
	std::cout << "A" << std::endl << A << std::endl << std::endl;
	cv::Mat_<double> w, u, vt;  // vt(9, 9)
	cv::SVD::compute(A, w, u, vt, cv::SVD::FULL_UV);
	////////////////////   h1, h2, h3 =  [vt00, vt10, vt20, ... , vt80]
	////////////////////   H = [h1, h2, h3]
	std::cout << "w=" 	<< w 	<< endl << endl;
	std::cout << "u=" 	<< u 	<< endl << endl;
	std::cout << "vt=" 	<< vt 	<< endl << endl;
	cv::Mat H = (cv::Mat_<double> (3, 3)  <<  vt(8,0), vt(8,1), vt(8,2), vt(8,3), vt(8,4), vt(8,5), vt(8,6), vt(8,7), vt(8,8) );
	// cv::Mat H = (cv::Mat_<double>(2,3) << vt(8,0) , vt(8,1) , vt(8,2) ,
	//  vt(8,3) , vt(8,4), vt(8,5) );
	 std::cout << "affin matrix" <<  std::endl << H << std::endl;




	 //////////////////////// image transform
	 cv::Mat img1 = cv::imread("img1.JPG", 0);
	 cv::Mat img2 = cv::imread("img2.JPG", 0);

 	 cv::Mat out_img = cv::Mat::zeros(img1.rows, img1.cols, img1.type());
	 AffinTransformer affin;
	 cv::Matx33d mat = affin.Translation(0,0);
	 // warpAffine(img, out_img, H, out_img.size());
	 out_img = affin.TransformE(img1, H, 0);
	 // out_img = affin.TransformL(img, H);
	 cv::imwrite("out.jpg", out_img);

	return 0;
}
Beispiel #11
0
void GSwifi::parseCmdResponse (char *buf) {
    GSLOG_PRINT(P("c< ")); GSLOG_PRINTLN(buf);

    if (strncmp(buf, "OK", 3) == 0) {
        gs_ok_ = true;
    }
    else if (strncmp(buf, "ERROR", 5) == 0) {
        gs_failure_ = true;
    }

    switch(gs_commandmode_) {
    case GSCOMMANDMODE_NORMAL:
        gs_response_lines_ = RESPONSE_LINES_ENDED;
        break;
    case GSCOMMANDMODE_CONNECT:
        if (strncmp(buf, P("CONNECT "), 8) == 0 && buf[9] == 0) {
            // both "AT+NSTCP=port" and "AT+NCTCP=ip,port" responds with
            // CONNECT <cid>

            // following lines are needed for client cids,
            // but won't be a problem if we run it for a server cid

            gs_response_lines_ = RESPONSE_LINES_ENDED;

            int8_t cid = x2i(buf[8]);
            ASSERT((0 <= cid) && (cid <= 16));

            setCidIsRequest(cid, false);
            content_lengths_[ cid ] = 0;

            // don't close other connections,
            // other connections close theirselves on their turn

            TIMER_STOP(timers_[cid]);
            connected_cid_ = cid;
        }
        break;
    case GSCOMMANDMODE_DHCP:
        if (gs_response_lines_ == 0 && strstr(buf, P("SubNet"))) {
            gs_response_lines_ ++;
        }
        else if (gs_response_lines_ == 1) {
            gs_response_lines_ = RESPONSE_LINES_ENDED;
        }
        break;
    case GSCOMMANDMODE_DNSLOOKUP:
        if (strncmp(buf, P("IP:"), 3) == 0) {
            sprintf( ipaddr_, "%s", &buf[3] );
            gs_response_lines_ = RESPONSE_LINES_ENDED;
        }
        break;
    case GSCOMMANDMODE_MDNS:
        if (gs_response_lines_ == 0) {
            // 1st line is just OK
            gs_response_lines_ ++;
        }
        else if (gs_response_lines_ == 1) {
            // 2nd line is something like:
            // " Registration Success!! for RR: IRKitXXXX"
            gs_response_lines_ = RESPONSE_LINES_ENDED;
        }
        break;
    case GSCOMMANDMODE_MAC:
        if ((gs_response_lines_ == 0) && (buf[2] == ':')) {
            // 1st line is something like:
            // "00:1d:c9:01:99:99"
            for (uint8_t i=0; i<17; i++) {
                if (buf[i] >= 'a') {
                    buf[i] -= 0x20; // a -> A
                }
            }
            sprintf( mac_, "%s", buf );
            gs_response_lines_ ++;
        }
        else if (gs_response_lines_ == 1) {
            // 2nd line is just "OK"
            gs_response_lines_ = RESPONSE_LINES_ENDED;
        }
        break;
#ifdef FACTORY_CHECKER
    case GSCOMMANDMODE_VERSION:
        // expects something like:
        // S2W APP VERSION=2.4.3
        // S2W GEPS VERSION=2.4.3
        // S2W WLAN VERSION=2.4.1
        if (gs_response_lines_ == 0) {
            memset(versions_, 0, sizeof(versions_));
            snprintf(versions_[0], 8, buf+16);
            gs_response_lines_ ++;
        }
        else if (gs_response_lines_ == 1) {
            snprintf(versions_[1], 8, buf+17);
            gs_response_lines_ ++;
        }
        else if (gs_response_lines_ == 2) {
            snprintf(versions_[2], 8, buf+17);
            gs_response_lines_ = RESPONSE_LINES_ENDED;
        }
        break;
#endif
    default:
        break;
    }

    return;
}
Beispiel #12
0
void GSwifi::parseLine () {
    static char buf[GS_CMD_SIZE];

    while (! ring_isempty(_buf_cmd)) {
        // received "\n"
        uint8_t i = 0;
        while ( (! ring_isempty(_buf_cmd)) &&
                (i < sizeof(buf) - 1) ) {
            ring_get( _buf_cmd, &buf[i], 1 );
            if (buf[i] == '\n') {
                break;
            }
            i ++;
        }
        if (i == 0) continue;
        buf[i] = 0;

        if ( (gs_mode_ == GSMODE_COMMAND) &&
             (gs_commandmode_ != GSCOMMANDMODE_NONE) ) {
            parseCmdResponse(buf);
        }

        if (strncmp(buf, P("CONNECT "), 8) == 0 && buf[8] >= '0' && buf[8] <= 'F' && buf[9] != 0) {
            // connect from client
            // CONNECT 0 1 192.168.2.1 63632
            // 1st cid is our http server's
            // 2nd cid is for client
            // next line will be "[ESC]Z10140GET / ..."

            int8_t cid = x2i(buf[10]); // 2nd cid = HTTP client cid
            ASSERT((0 <= cid) && (cid <= 16));

            setCidIsRequest(cid, true);
            content_lengths_[ cid ] = 0;

            // don't close other connections,
            // other connections close theirselves on their turn
            // ignore client's IP and port
        }
        else if (strncmp(buf, P("DISCONNECT "), 11) == 0) {
            int8_t cid = x2i(buf[11]);
            ASSERT((0 <= cid) && (cid <= 16));

            if (cid == server_cid_) {
                // if it's our server, this is fatal
                reset();
            }
            else if (! cidIsRequest(cid) ) {
                // request *from* us was disconnected (ex: polling)
                dispatchResponseHandler(cid, HTTP_STATUSCODE_DISCONNECT, GSREQUESTSTATE_ERROR);
            }
        }
        else if (strncmp(buf, P("DISASSOCIATED"), 13) == 0 ||
                 strncmp(buf, P("Disassociat"), 11) == 0) {
            // Disassociated
            // Disassociation Event
            clear();
            on_disconnect_();
            gs_failure_ = true;
        }
        else if (strncmp(buf, P("APP Reset"), 9) == 0 ||
                 strncmp(buf, P("Serial2WiFi APP"), 15) == 0) {
            // APP Reset-APP SW Reset
            // APP Reset-Wlan Except
            // Serial2Wifi APP
            on_reset_();
            gs_failure_ = true;
        }
        // else if (strncmp(buf, P("Out of StandBy-Timer"), 20) == 0 ||
        //          strncmp(buf, P("Out of StandBy-Alarm"), 20) == 0) {
        // }
        // else if (strncmp(buf, P("Out of Deep Sleep"), 17) == 0 ) {
        // }
    }
}
Beispiel #13
0
// received a character from UART
void GSwifi::parseByte(uint8_t dat) {
    static uint8_t  next_token; // split each byte into tokens (cid,ip,port,length,data)
    static bool     escape = false;
    char temp[GS_MAX_PATH_LENGTH+1];

    if (dat == ESCAPE) {
        // 0x1B : Escape
        GSLOG_PRINT("e< ");
    }
    else { // if (next_token != NEXT_TOKEN_DATA) {
        GSLOG_WRITE(dat);
    }

    if (gs_mode_ == GSMODE_COMMAND) {
        if (escape) {
            // esc
            switch (dat) {
            case 'O':
            case 'F':
                // ignore
                break;
            case 'Z':
            case 'H':
                gs_mode_   = GSMODE_DATA_RX_BULK;
                next_token = NEXT_TOKEN_CID;
                break;
            default:
                // GSLOG_PRINT("!E1 "); GSLOG_PRINTLN2(dat,HEX);
                break;
            }
            escape = false;
        }
        else {
            if (dat == ESCAPE) {
                escape = true;
            }
            else if (dat == '\n') {
                // end of line
                parseLine();
            }
            else if (dat != '\r') {
                if ( ! ring_isfull(_buf_cmd) ) {
                    ring_put(_buf_cmd, dat);
                }
                else {
                    GSLOG_PRINTLN("!E2");
                }
            }
        }
        return;
    }
    else if (gs_mode_ != GSMODE_DATA_RX_BULK) {
        return;
    }

    static uint16_t       len;
    static char           len_chars[5];
    static int8_t         current_cid;
    static GSREQUESTSTATE request_state;

    if (next_token == NEXT_TOKEN_CID) {
        // dat is cid
        current_cid = x2i(dat);
        ASSERT((0 <= current_cid) && (current_cid <= 16));

        next_token  = NEXT_TOKEN_LENGTH;
        len         = 0;
    }
    else if (next_token == NEXT_TOKEN_LENGTH) {
        // Data Length is 4 ascii char represents decimal value i.e. 1400 byte (0x31 0x34 0x30 0x30)
        len_chars[ len ++ ] = dat;
        if (len >= 4) {
            len_chars[ len ] = 0;
            len        = atoi(len_chars); // length of data
            next_token = NEXT_TOKEN_DATA;

            if (content_lengths_[ current_cid ] > 0) {
                // this is our 2nd bulk message from GS for this response
                // we already swallowed HTTP response headers,
                // following should be body
                request_state = GSREQUESTSTATE_BODY;
            }
            else {
                request_state = GSREQUESTSTATE_HEAD1;
            }
            ring_clear( _buf_cmd ); // reuse _buf_cmd to store HTTP request
        }
    }
    else if (next_token == NEXT_TOKEN_DATA) {
        len --;

        if (cidIsRequest(current_cid)) { // request against us
            static uint16_t error_code;
            static int8_t   routeid;

            switch (request_state) {
            case GSREQUESTSTATE_HEAD1:
                if (dat != '\n') {
                    if ( ! ring_isfull(_buf_cmd) ) {
                        ring_put( _buf_cmd, dat );
                    }
                    // ignore overflowed
                }
                else {
                    // end of request line

                    // reuse "temp" buffer to parse method and path
                    int8_t  result  = parseRequestLine((char*)temp, 7);
                    GSMETHOD method = GSMETHOD_UNKNOWN;
                    if ( result == 0 ) {
                        method = x2method(temp);
                        result = parseRequestLine((char*)temp, GS_MAX_PATH_LENGTH);
                    }
                    if ( result != 0 ) {
                        // couldn't detect method or path
                        request_state = GSREQUESTSTATE_ERROR;
                        error_code    = 400;
                        ring_clear(_buf_cmd);
                        break;
                    }

                    routeid = router(method, temp);
                    if ( routeid < 0 ) {
                        request_state = GSREQUESTSTATE_ERROR;
                        error_code    = 404;
                        ring_clear(_buf_cmd);
                        break;
                    }
                    request_state                   = GSREQUESTSTATE_HEAD2;
                    continuous_newlines_            = 0;
                    content_lengths_[ current_cid ] = 0;
                    has_requested_with_             = false;
                    ring_clear(_buf_cmd);
                }
                break;
            case GSREQUESTSTATE_HEAD2:
                if(0 == parseHead2(dat, current_cid)) {
                    request_state = GSREQUESTSTATE_BODY;
                    // dispatched once, at start of body
                    dispatchRequestHandler(current_cid, routeid, GSREQUESTSTATE_BODY_START);
                }
                break;
            case GSREQUESTSTATE_BODY:
                if (content_lengths_[ current_cid ] > 0) {
                    content_lengths_[ current_cid ] --;
                }
                if (ring_isfull(_buf_cmd)) {
                    dispatchRequestHandler(current_cid, routeid, request_state); // POST, user callback should write()
                }
                ring_put(_buf_cmd, dat);
                break;
            case GSREQUESTSTATE_ERROR:
                // skip until received whole request
                break;
            case GSREQUESTSTATE_RECEIVED:
            default:
                break;
            }

            // end of bulk transfered data
            if (len == 0) {
                gs_mode_ = GSMODE_COMMAND;

                if ( request_state == GSREQUESTSTATE_ERROR ) {
                    writeHead( current_cid, error_code );
                    writeEnd();
                    ring_put( &commands, COMMAND_CLOSE );
                    ring_put( &commands, current_cid );
                }
                else {
                    if (content_lengths_[ current_cid ] == 0) {
                        // if Content-Length header was longer than <ESC>Z length,
                        // we wait til next bulk transfer
                        request_state = GSREQUESTSTATE_RECEIVED;
                    }
                    // user callback should write(), writeEnd() and close()
                    dispatchRequestHandler(current_cid, routeid, request_state);
                }
                ring_clear(_buf_cmd);
            }
        }
        else {
            // is request from us
            static uint16_t status_code;

            switch (request_state) {
            case GSREQUESTSTATE_HEAD1:
                if (dat != '\n') {
                    if ( ! ring_isfull(_buf_cmd) ) {
                        // ignore if overflowed
                        ring_put( _buf_cmd, dat );
                    }
                }
                else {
                    uint8_t i=0;

                    // skip 9 characters "HTTP/1.1 "
                    while (i++ < 9) {
                        ring_get( _buf_cmd, &temp[0], 1 );
                    }

                    // copy 3 numbers representing status code into temp buffer
                    temp[ 3 ] = 0;
                    int8_t count = ring_get( _buf_cmd, temp, 3 );
                    if (count != 3) {
                        // protocol error
                        // we should receive something like: "200 OK", "401 Unauthorized"
                        status_code   = 999;
                        request_state = GSREQUESTSTATE_ERROR;
                        break;
                    }
                    status_code                     = atoi(temp);
                    request_state                   = GSREQUESTSTATE_HEAD2;
                    continuous_newlines_            = 0;
                    content_lengths_[ current_cid ] = 0;
                    ring_clear(_buf_cmd);
                }
                break;
            case GSREQUESTSTATE_HEAD2:
                if(0 == parseHead2(dat, current_cid)) {
                    request_state = GSREQUESTSTATE_BODY;
                    // dispatched once, at start of body
                    dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY_START);
                }
                break;
            case GSREQUESTSTATE_BODY:
                if (content_lengths_[ current_cid ] > 0) {
                    content_lengths_[ current_cid ] --;
                }
                if (ring_isfull(_buf_cmd)) {
                    dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY);
                }
                ring_put(_buf_cmd, dat);
                break;
            case GSREQUESTSTATE_ERROR:
            case GSREQUESTSTATE_RECEIVED:
            default:
                break;
            }

            if (len == 0) {
                gs_mode_ = GSMODE_COMMAND;

                if ( request_state == GSREQUESTSTATE_ERROR ) {
                    dispatchResponseHandler(current_cid, status_code, request_state);
                }
                else {
                    if (content_lengths_[ current_cid ] == 0) {
                        // if Content-Length header was longer than <ESC>Z length,
                        // we wait til all response body received.
                        // we need to close our clientRequest before handling it.
                        // GS often locks when closing 2 connections in a row
                        // ex: POST /keys from iPhone (cid:1) -> POST /keys to server (cid:2)
                        //     response from server arrives -> close(1) -> close(2) -> lock!!
                        // the other way around: close(2) -> close(1) doesn't lock :(
                        request_state = GSREQUESTSTATE_RECEIVED;
                    }
                    dispatchResponseHandler(current_cid, status_code, request_state);
                }
                ring_clear( _buf_cmd );
            }
        } // is response
    } // (next_token == NEXT_TOKEN_DATA)
}