//--------------------------------------------------------------
void testApp::setup() {

    // this load font loads the non-full character set
    // (ie ASCII 33-128), at size "32"
    franklinBook.loadFont("frabk.ttf", 32);
    franklinBook.setLineHeight(36);


    // the page http://search.yahoo.com/search?p=GOOG contains the current stock price for Google
    string url = "http://search.yahoo.com/search?p=GOOG";
    string result = ofLoadURL(url).data.getText();


    // Use a regular expression to get the bit of text that we want.
    RegularExpression re("<li class=\"price\">([0-9\\.]+)</li>");
    RegularExpression::MatchVec matches;
    re.match(result, 0, matches);


    // result.substr(matches[0].offset, matches[0].length)  -- contains the entire matched <li>
    // result.substr(matches[1].offset, matches[1].length) -- contains the subpattern inside the ()
    int stock_price_start_position = matches[1].offset;
    int stock_price_length = matches[1].length;
    message = result.substr(stock_price_start_position, stock_price_length);
}
Poco::Net::IPAddress NetworkUtils::getPublicIPAddress(const std::string& url)
{
    try
    {
        ofHttpResponse response = ofLoadURL(url);

        if (response.status == 200)
        {
            return Poco::Net::IPAddress(response.data.getText());
        }
        else
        {
            ofLogError("NetworkUtils::getPublicIPAddress") << response.error;
            return Poco::Net::IPAddress();
        }
    }
    catch (const Poco::Net::InvalidAddressException& exc)
    {
        ofLogError("NetworkUtils::getPublicIPAddress") << exc.displayText();
        return Poco::Net::IPAddress();
    }
    catch (const Poco::Exception& exc)
    {
        ofLogError("NetworkUtils::getPublicIPAddress") << exc.displayText();
        return Poco::Net::IPAddress();
    }
}
//--------------------------------------------------------------
bool ofxJSONElement::openRemote(string filename, bool secure)
{
	string result = ofLoadURL(filename).data.getText();
	//std::cout<<"this is the resulttttt"<<" "<<result<<std::endl;
	Reader reader;
	if(!reader.parse( result, *this )) {
		ofLog(OF_LOG_WARNING, "Unable to parse "+filename);
		return false;
	}
	return true;
}
//--------------------------------------------------------------
bool ofxJSONElement::openRemote(string filename, bool secure)
{
	string result = ofLoadURL(filename).data.getText();
	
	Json::Reader reader;
	if(!reader.parse( result, *this )) {
		ofLog(OF_LOG_WARNING, "Unable to parse "+filename);
		return false;
	}
	return true;
}
void ofPackageManager::doctor()
{
	printVersion();

	// check version of ofPackageManager
	ofHttpResponse request = ofLoadURL("https://raw.githubusercontent.com/thomasgeissl/ofPackageManager/master/defines.h");
	auto defines = request.data.getText();
	int majorVersion = 0;
	int minorVersion = 0;
	int patchVersion = 0;
	auto lines = ofSplitString(defines, "\n");
	for (auto line : lines)
	{
		auto parts = ofSplitString(line, " ");
		if (parts.size() == 3)
		{
			if (parts[1] == "major")
			{
				majorVersion = ofToInt(parts[2]);
			}
			else if (parts[1] == "minor")
			{
				minorVersion = ofToInt(parts[2]);
			}
			else if (parts[1] == "patch")
			{
				patchVersion = ofToInt(parts[2]);
			}
		}
	}
	ofJson mostRecentVersionJson;
	// mostRecentVersionJson = ofJson::parse(request.data.getText());
	mostRecentVersionJson["major"] = majorVersion;
	mostRecentVersionJson["minor"] = minorVersion;
	mostRecentVersionJson["patch"] = patchVersion;
	ofJson currentVersion = getVersionJson();
	if (
		mostRecentVersionJson["major"].get<int>() > currentVersion["major"].get<int>() ||
		mostRecentVersionJson["minor"].get<int>() > currentVersion["minor"].get<int>() ||
		mostRecentVersionJson["patch"].get<int>() > currentVersion["patch"].get<int>())
	{
		ofLogNotice("doctor") << "There is a new version of ofPackageManager available";
		ofLog::setAutoSpace(false);
		ofLogNotice("doctor") << "The most recent version is " << mostRecentVersionJson["major"] << "." << mostRecentVersionJson["minor"] << "." << mostRecentVersionJson["patch"];
		ofLog::setAutoSpace(true);
	}
	else
	{
		ofLogNotice("doctor") << "You are up to date. Currently there is no newer version of ofPackageManager available";
	}

	// check version of ofPackages
}
static bool loadImage(ofPixels_<PixelType> & pix, const std::string& _fileName, const ofImageLoadSettings& settings){
	ofInitFreeImage();

#ifndef TARGET_EMSCRIPTEN
	Poco::URI uri;
	try {
		uri = Poco::URI(_fileName);
	} catch(const std::exception & exc){
		ofLogError("ofImage") << "loadImage(): malformed uri when loading image from uri \"" << _fileName << "\": " << exc.what();
		return false;
	}
	if(uri.getScheme() == "http" || uri.getScheme() == "https"){
		return ofLoadImage(pix, ofLoadURL(_fileName).data);
	}
#endif
	
	std::string fileName = ofToDataPath(_fileName);
	bool bLoaded = false;
	FIBITMAP * bmp = nullptr;

	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		if(fif == FIF_JPEG) {
			int option = getJpegOptionFromImageLoadSetting(settings);
			bmp = FreeImage_Load(fif, fileName.c_str(), option);
		} else {
			bmp = FreeImage_Load(fif, fileName.c_str(), 0);
		}

		if (bmp != nullptr){
			bLoaded = true;
		}
	}
	
	//-----------------------------

	if ( bLoaded ){
		putBmpIntoPixels(bmp,pix);
	}

	if (bmp != nullptr){
		FreeImage_Unload(bmp);
	}

	return bLoaded;
}
Exemple #7
0
static bool loadImage(ofPixels_<PixelType> & pix, string fileName){
	ofInitFreeImage();

#ifndef TARGET_EMSCRIPTEN
	// Attempt to parse the fileName as a url - specifically it must be a full address starting with http/https
	// Poco::URI normalizes to lowercase
	Poco::URI uri;
    try {
        uri = Poco::URI(fileName);
    } catch(const Poco::SyntaxException& exc){
        ofLogError("ofImage") << "loadImage(): malformed url when loading image from url \"" << fileName << "\": " << exc.displayText();
		return false;
    }
	if(uri.getScheme() == "http" || uri.getScheme() == "https"){
		return ofLoadImage(pix, ofLoadURL(fileName).data);
	}
#endif
	
	fileName = ofToDataPath(fileName);
	bool bLoaded = false;
	FIBITMAP * bmp = NULL;

	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		bmp = FreeImage_Load(fif, fileName.c_str(), 0);

		if (bmp != NULL){
			bLoaded = true;
		}
	}
	
	//-----------------------------

	if ( bLoaded ){
		putBmpIntoPixels(bmp,pix);
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}

	return bLoaded;
}
Exemple #8
0
static bool loadImage(ofPixels_<PixelType> & pix, string fileName){
	ofInitFreeImage();

#ifndef TARGET_EMSCRIPTEN
	// Attempt to parse the fileName as a url - specifically it must be a full address starting with http/https
	network::uri uri;
    try {
        uri = network::uri(fileName);
    } catch(const std::exception &){
    }
	if(uri.scheme() != boost::none && (uri.scheme().get() == "http" || uri.scheme().get() == "https")){
		return ofLoadImage(pix, ofLoadURL(fileName).data);
	}else if(uri.scheme()!=boost::none){
		ofLogError() << "protocol " << uri.scheme().get() << " not supported";
	}
#endif
	
	fileName = ofToDataPath(fileName);
	bool bLoaded = false;
	FIBITMAP * bmp = NULL;

	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		bmp = FreeImage_Load(fif, fileName.c_str(), 0);

		if (bmp != NULL){
			bLoaded = true;
		}
	}
	
	//-----------------------------

	if ( bLoaded ){
		putBmpIntoPixels(bmp,pix);
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}

	return bLoaded;
}
void DownloaderTask::triggerDownload(){
    ofLog(OF_LOG_NOTICE)<<"Download Triggered"<<endl;
    ofNotifyEvent(downloadStarted, downloadFiles.front(), this); //alert UI that download started...
    ofHttpResponse response = ofLoadURL("http://10.11.12.13/get_last_saved_filename");
    ofLog(OF_LOG_NOTICE)<<response.data<<endl;
    
    string newFile = ofToString(response.data);
    if(ofIsStringInString(newFile, "\"")){
        ofStringReplace(newFile, "\"", "");
    }
    if(newFile != lastFileName){
        lastFileName = newFile;
        
        ofLog(OF_LOG_NOTICE)<<"Download url "<<downloadURL+"/static/asattachment"+lastFileName<<endl;
        ofLoadURLAsync(downloadURL+"/static/asattachment"+lastFileName);
    }
    
    
}
Exemple #10
0
static bool loadImage(ofPixels_<PixelType> & pix, string fileName){
	ofInitFreeImage();
	if(fileName.substr(0, 7) == "http://") {
		return ofLoadImage(pix, ofLoadURL(fileName).data);
	}
	
	int width, height, bpp;
	fileName = ofToDataPath(fileName);
	bool bLoaded = false;
	FIBITMAP * bmp = NULL;

	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		bmp = FreeImage_Load(fif, fileName.c_str(), 0);

		if (bmp != NULL){
			bLoaded = true;
		}
	}
	
	//-----------------------------

	if ( bLoaded ){
		putBmpIntoPixels(bmp,pix);
	} else {
		width = height = bpp = 0;
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}

	return bLoaded;
}
void ofApp::setup()
{
    ofEnableDepthTest();
	ofEnableAlphaBlending();

    rot = 0;

    scaler = 300 / ofx::Geo::GeoUtils::EARTH_RADIUS_KM;

    colorMap.loadImage("color_map_1024.jpg");

    earthSphere.set(ofx::Geo::GeoUtils::EARTH_RADIUS_KM, 24);
    ofQuaternion quat;
    quat.makeRotate(180, 0, 1, 0);
    earthSphere.rotate(quat);
    earthSphere.mapTexCoords(0,
                             colorMap.getTextureReference().getTextureData().tex_u,
                             colorMap.getTextureReference().getTextureData().tex_t,
                             0);

    myLocation = ofx::Geo::ElevatedCoordinate(51.507406923983446,
                                              -0.12773752212524414,
                                              0.05);

    ofHttpResponse response = ofLoadURL("http://www.celestrak.com/NORAD/elements/resource.txt");

    if (200 == response.status)
    {
        satellites = ofx::Satellite::Utils::loadTLEFromBuffer(response.data);
    }
    else
    {
        ofLogError("ofApp::setup()") << "Unable to load : " << response.error;
    }


    cam.setPosition(0, 0, 0);

}
Exemple #12
0
//--------------------------------------------------------------
void ofApp::setup(){

    
    
    
    string baseUrl = "http://api.nytimes.com/svc/search/v1/article?format=json";
    string apiKey = "&api-key=################################:#:########";         /// YOUR API KEY GOES HERE 
    string query = "&query=publication_year:[2011]";
    string facets = "&facets=per_facet,org_facet";
    
    string url = baseUrl + query + facets + apiKey;
    string data = ofLoadURL(url).data.getText();
   
    json.parse(data);
    
    
    for (int i = 0; i < json["facets"]["org_facet"].size(); i++){
        string name = json["facets"]["org_facet"][i]["term"].asString();
        int count = json["facets"]["org_facet"][i]["count"].asInt();
        facet tempFacet;
        tempFacet.name = name;
        tempFacet.count = count;
        yearFacets.push_back(tempFacet);
    }
    
    for (int i = 0; i < json["facets"]["per_facet"].size(); i++){
        string name = json["facets"]["per_facet"][i]["term"].asString();
        int count = json["facets"]["per_facet"][i]["count"].asInt();
        facet tempFacet;
        tempFacet.name = name;
        tempFacet.count = count;
        yearFacets.push_back(tempFacet);
    }
    
    ofSleepMillis(100); 

    
    for (int i = 0; i < yearFacets.size(); i++){
        
        string queryName = yearFacets[i].name;
        query = "&query='" + yearFacets[i].name + "' publication_year:[2011]";
        string facets = "&facets=per_facet,org_facet";
        
        string url = baseUrl + query + facets + apiKey;
        
        cout << url << endl;
        string data = ofLoadURL(url).data.getText();
        
        json.parse(data);
        
        for (int i = 0; i < json["facets"]["per_facet"].size(); i++){
            string name = json["facets"]["per_facet"][i]["term"].asString();
            int count = json["facets"]["per_facet"][i]["count"].asInt();
            facet tempFacet;
            tempFacet.name = name;
            tempFacet.count = count;
            subFacets[queryName].push_back(tempFacet);
        }
        
        for (int i = 0; i < json["facets"]["org_facet"].size(); i++){
            string name = json["facets"]["org_facet"][i]["term"].asString();
            int count = json["facets"]["org_facet"][i]["count"].asInt();
            facet tempFacet;
            tempFacet.name = name;
            tempFacet.count = count;
            subFacets[queryName].push_back(tempFacet);
        }
        
        
        ofSleepMillis(100);
    }
    

    which = 0;
    
    
}
Exemple #13
0
static bool loadImage(ofPixels_<PixelType> & pix, const std::filesystem::path& _fileName, const ofImageLoadSettings& settings){
	ofInitFreeImage();

	auto uriStr = _fileName.string();
	UriUriA uri;
	UriParserStateA state;
	state.uri = &uri;

	if(uriParseUriA(&state, uriStr.c_str())!=URI_SUCCESS){
		const int bytesNeeded = 8 + 3 * strlen(uriStr.c_str()) + 1;
		std::vector<char> absUri(bytesNeeded);
	#ifdef TARGET_WIN32
		uriWindowsFilenameToUriStringA(uriStr.c_str(), absUri.data());
	#else
		uriUnixFilenameToUriStringA(uriStr.c_str(), absUri.data());
	#endif
		if(uriParseUriA(&state, absUri.data())!=URI_SUCCESS){
			ofLogError("ofImage") << "loadImage(): malformed uri when loading image from uri " << _fileName;
			uriFreeUriMembersA(&uri);
			return false;
		}
	}
	std::string scheme(uri.scheme.first, uri.scheme.afterLast);
	uriFreeUriMembersA(&uri);

	if(scheme == "http" || scheme == "https"){
		return ofLoadImage(pix, ofLoadURL(_fileName.string()).data);
	}

	std::string fileName = ofToDataPath(_fileName, true);
	bool bLoaded = false;
	FIBITMAP * bmp = nullptr;

	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		if(fif == FIF_JPEG) {
			int option = getJpegOptionFromImageLoadSetting(settings);
			bmp = FreeImage_Load(fif, fileName.c_str(), option);
		} else {
			bmp = FreeImage_Load(fif, fileName.c_str(), 0);
		}

		if (bmp != nullptr){
			bLoaded = true;
		}
	}

	//-----------------------------

	if ( bLoaded ){
		putBmpIntoPixels(bmp,pix);
	}

	if (bmp != nullptr){
		FreeImage_Unload(bmp);
	}

	return bLoaded;
}
void ofApp::updateSensors(){
    const unsigned int frequency = 100;
    int sensor = (int)ofRandom(100)%3;
    
    // send data
    if ((int)ofGetFrameNum()%frequency==0) {
        
        float data;
    
#if ARDUINO
#else
        simulate = true;
#endif
        
        if (simulate) {
            arduinoText->setTextString("simulate arduino connection");
            data = getSimulatedData();
        } else {
            arduinoText->setTextString("arduino connected");
            data = arduino.getAnalog(sensor);
            if (data==FALSE_DATA) {
                data = getSimulatedData();
            }
        }
        
        ofxJSONElement result;
        bool parsing = result.open(getPostUrl(sensor, data));
        
        if (parsing) {
            generalText->setTextString("succesfully sended data");
        } else {
            cout << "not parsed: error" << endl;
        }
    }
    
    //receive data
    if ((int)ofGetFrameNum()%frequency==floor(frequency/2)) {
        const string url = SERVER+"/sensor/getSensors";
        
        ofHttpResponse resp = ofLoadURL(url);
        generalText->setTextString("data received");
        
        ofxJSONElement json;
        bool parsingSuccessful = json.parse(resp.data);
        
        if (parsingSuccessful){
            for (int i(0); i < 3; i++) {
                sensors[i].rawData.clear();
                sensors[i].averageData.clear();
                
                for (Json::ArrayIndex rd = 0; rd < json[i]["raw"].size(); rd++) {
                    sensors[i].rawData.push_back(ofToFloat(json[i]["raw"][rd].asString()));
                    sensors[i].averageData.push_back(ofToFloat(json[i]["averageData"][rd].asString()));
                }
            }
            sensor1->setBuffer(sensors[0].averageData);
            sensor2->setBuffer(sensors[1].averageData);
            sensor3->setBuffer(sensors[2].averageData);
        } else {
            ofLogNotice("ofApp::setup")  << "Failed to parse JSON" << endl;
        }
    }
    
    //update actuators
    // actuator 1
    //can be improved by erasing duplication
    if (actuator1time > 0) {
        int remainingTime = actuator1time-ofGetElapsedTimef();
        if (remainingTime <= 0) {
            actuator1time = 0;
            arduino.sendDigital(3, ARD_LOW);
            actuator1text->setTextString("actuator 1 disabled");
        } else {
            actuator1text->setTextString("actuator 1: "+ofToString(remainingTime)+" seconds remaining");
        }
    }
    
    if (actuator2time > 0) {
        int remainingTime = actuator2time-ofGetElapsedTimef();
        if (remainingTime <= 0) {
            actuator2time = 0;
            arduino.sendDigital(4, ARD_LOW);
            actuator1text->setTextString("actuator 2 disabled");
        } else {
            actuator1text->setTextString("actuator 2: "+ofToString(remainingTime)+" seconds remaining");
        }
    }
}
ofHttpResponse ofxPTZControl::sendRawCommand(string command) {
    cout<<"Sending command: " + command<<endl;
    response = ofLoadURL(command);
    cout<<"Response: "<<response.data<<endl;
    return response;
}