//-------------------------------------------------------------- void ofApp::draw(){ ofBeginShape(); bool first = true; int currentDraw; for(float i=-M_PI;i<=M_PI;i+=step) { if(first) {currentDraw = 0; first = false;} else {currentDraw = 1;} setFold(i,pos,currentDraw); } pos += step; ofEndShape(); if(pos > M_PI) { ofSleepMillis(1000); ofSaveFrame(); ofExit(); } }
//--------------------------------------------------------------------------- void ofxKinect::threadedFunction() { freenect_set_led(kinectDevice, LED_GREEN); freenect_set_video_format(kinectDevice, bInfrared?FREENECT_VIDEO_IR_8BIT:FREENECT_VIDEO_RGB); freenect_set_depth_format(kinectDevice, FREENECT_DEPTH_11BIT); freenect_set_depth_callback(kinectDevice, &grabDepthFrame); freenect_set_video_callback(kinectDevice, &grabRgbFrame); ofLog(OF_LOG_VERBOSE, "ofxKinect: Connection opened"); freenect_start_depth(kinectDevice); freenect_start_video(kinectDevice); while (isThreadRunning()) { if( bTiltNeedsApplying ) { freenect_set_tilt_degs(kinectDevice, targetTiltAngleDeg); bTiltNeedsApplying = false; } freenect_update_tilt_state(kinectDevice); freenect_raw_tilt_state * tilt = freenect_get_tilt_state(kinectDevice); rawAccel.set(tilt->accelerometer_x, tilt->accelerometer_y, tilt->accelerometer_z); double dx,dy,dz; freenect_get_mks_accel(tilt, &dx, &dy, &dz); mksAccel.set(dx, dy, dz); ofSleepMillis(10); // printf("\r raw acceleration: %4d %4d %4d mks acceleration: %4f %4f %4f", ax, ay, az, dx, dy, dz); } //TODO: uncomment these when they are implemented in freenect freenect_set_tilt_degs(kinectDevice, 0); freenect_update_tilt_state(kinectDevice); freenect_stop_depth(kinectDevice); freenect_stop_video(kinectDevice); freenect_set_led(kinectDevice, LED_YELLOW); freenect_close_device(kinectDevice); freenect_shutdown(kinectContext); ofLog(OF_LOG_VERBOSE, "ofxKinect: Connection closed"); }
ofImage* PVGLImageLoader::getPanoramaSections() { if(imgLoaded) { //if(currTexture) // delete currTexture; //currTexture=nextTexture; //imgLoaded = false; ofSleepMillis(1000); return panoSections; } else { return NULL; } }
//-------------------------------------------------------------- void ofApp::update() { ofSetWindowTitle("fps: "+ ofToString(ofGetFrameRate())); cam.update(); display.update(cam.getNumFaces()); if(oscRecvr.hasWaitingMessages()){ //TODO: check how dangerous this blocking while is ofxOscMessage m; oscRecvr.getNextMessage(&m); cout<< "m.getAddress: "<<m.getAddress()<<endl; string incomingHostIp = m.getRemoteIp(); cout << "\n-----------------\n\nRECVD OSC MESSAGE FROM IP: "+m.getRemoteIp()<<endl; cout << " /address: "<< m.getAddress() << endl; //cout << "\t MSG: "+ getOscMsgAsString(m) << "\n\n------------"; if(std::find(knownClients.begin(), knownClients.end(), incomingHostIp) == knownClients.end()){ knownClients.push_back(incomingHostIp); //add new host to list } if(m.getAddress() == "/round"){ ofxJSONElement thisObj; thisObj = ofxJSONElement(m.getArgAsString(0)); //send callback ofxOscMessage n; n.setAddress("/callback"); n.addIntArg(1); oscSender.sendMessage(n); display.startRound(thisObj); } else if(m.getAddress() == "/callback"){ cout << "GOT CALLBACK, STARTING ROUND"; waitingCallback = false; display.startRound(thisPair[0]); dataConnect.sendShowing(thisPair[0]["objectId"].asString(), thisPair[1]["objectId"].asString(), ofToString(CURR_CAT_URL)); } } if(waitingCallback){ ofSleepMillis(100); sendRound(); } }
//-------------------------------------------------------------- void ofxTeensyOcto::serialConfigure(string portName, float _xoffset, float _yoffset, float _widthPct, float _heightPct, int _direction) { int baud = 115200; ledSerial[numPorts].setup(portName, baud); ledSerial[numPorts].writeByte('?'); // send an initial character ofSleepMillis(50); string configline; while (ledSerial[numPorts].available() != OF_SERIAL_ERROR ){ int val = ledSerial[numPorts].readByte(); if(val == 10) { break; } configline += val; } if (configline.length() <= 0) { ofLogError("serialConfigure") << "Serial port " + portName + " is not responding."; ofLogError("serialConfigure") << "Is it really a Teensy 3.0+ running VideoDisplay?"; simulate = true; } else { ofLogNotice() << "Read " << configline.length() << " bytes: " << configline << endl; } // Count the number of parameters received int numparam = 0; char *dup = strdup(configline.c_str()); char *token = strtok(dup, ","); while (token != NULL) { token = strtok(NULL, ","); numparam++; } free(dup); ofLogNotice("serialConfigure") << "Number of parameters: " << numparam; if (numparam != 12) { ofLogError("serialConfigure") << "Error: port " + portName + " did not respond to LED config query"; simulate = true; } // only store the info and increase numPorts if Teensy responds properly ledImage[numPorts].allocate(ledWidth, ledHeight * stripsPerPort, OF_IMAGE_COLOR); ledArea[numPorts].set(_xoffset, _yoffset, _widthPct, _heightPct); ledLayout[numPorts] = _direction == 0; // affects layout > pixel direction numPorts++; }
void CameraTheosVideoInput::grab() { lock(); fresh = false; unlock(); while(!fresh) ofSleepMillis(1); lock(); for (int iPixel=0; iPixel<getWidth()*getHeight(); iPixel++) { greyPixels[iPixel] = 0; for (int iColour=0; iColour<3; iColour++) greyPixels[iPixel] += rgbPixels[iPixel*3+iColour]/3; } unlock(); }
//-------------------------------------------------------------- void galaxieApp::setupI(){ gInitialized = true; if (WITH_ARDUINO){ arduino.enumerateDevices(); int i = 0; while (!arduino.setup(SERIAL_PORT, 9600)){ i++; if (i == 5){ printf("Are you sure you have an Arduino connected?"); break; } ofSleepMillis(400); } arduino.startContinuousRead(); ofAddListener(arduino.NEW_MESSAGE, this, &galaxieApp::onNewMessage); } }
//-------------------------------------------------------------- void mpeClientTCP::threadedFunction() { out("Running!"); // let the server know that this client is ready to start send("S" + ofToString(id)); while (isThreadRunning()) { if (lock()) { string msg = tcpClient.receiveRaw(); if (msg.length() > 0) { read(msg); } unlock(); ofSleepMillis(5); } } }
void BuscaCaras::threadedFunction() { // loop through this process whilst thread running while( isThreadRunning() == true ){ lock(); if (processing) { finder.findHaarObjects(grayscaleImage, 100, 100); // //cout << "threaded encontró " << finder.blobs.size() << std::endl; processing = false; } unlock(); ofSleepMillis(40); } }
void Libdc1394Grabber::cleanupCamera() { closeCamera = true; ofxThread::stopThread(); ofLog(OF_LOG_VERBOSE,"Stopped capture thread."); //this sleep seems necessary, at least on OSX, to avoid an occasional hang on exit ofSleepMillis(150); dc1394switch_t is_iso_on = DC1394_OFF; if(camera) { if (dc1394_video_get_transmission(camera, &is_iso_on)!=DC1394_SUCCESS) { is_iso_on = DC1394_ON; // try to shut ISO anyway } if (is_iso_on > DC1394_OFF) { if (dc1394_video_set_transmission(camera, DC1394_OFF)!=DC1394_SUCCESS) { ofLog(OF_LOG_ERROR, "Could not stop ISO transmission!"); } } } ofLog(OF_LOG_VERBOSE,"Stopped ISO transmission."); /* cleanup and exit */ if(cameraList) dc1394_camera_free_list (cameraList); if(camera) { dc1394_capture_stop(camera); dc1394_camera_free (camera); camera = NULL; } ofLog(OF_LOG_VERBOSE,"Stopped camera."); if(dc1394) { dc1394_free (dc1394); dc1394 = NULL; } if(pixels) { delete [] pixels; pixels = NULL; } printf("Closed!\n"); }
void DetachThreadQueue::threadedFunction(){ lock(); int nPending = pending.size(); int nProcessing = processing.size(); unlock(); if(verbose) printf("DetachThreadQueue::threadedFunction() start processing\n"); #ifdef TARGET_OSX pthread_setname_np("DetachThreadQueue Manager"); #endif while( ( nPending > 0 || nProcessing > 0 ) && !timeToStop ){ bool needToRest = false; lock(); nPending = pending.size(); nProcessing = processing.size(); if ( nPending > 0 && nProcessing < maxProcessing ){ GenericWorkUnit * w = pending[0]; pending.erase( pending.begin() ); w->processInThread(); processing.push_back(w); }else{ needToRest = true; } unlock(); updateQueues(); if (needToRest) ofSleepMillis(restTime); } if(verbose) printf("DetachThreadQueue::threadedFunction() end processing %f\n", ofGetElapsedTimef() ); if (!timeToStop){ if (verbose) printf("detaching DetachThreadQueue thread!\n"); pthread_detach(pthread_self()); //fixing that nasty zombie ofThread bug here } }
//------------------------------------------------------------ void ofOpenALSoundPlayer::threadedFunction(){ vector<vector<short> > multibuffer; multibuffer.resize(channels); while(isThreadRunning()){ for(int i=0; i<int(sources.size())/channels; i++){ int processed; alGetSourcei(sources[i*channels], AL_BUFFERS_PROCESSED, &processed); while(processed--) { stream("",buffer); int numFrames = buffer.size()/channels; if(channels>1){ for(int j=0;j<channels;j++){ multibuffer[j].resize(buffer.size()/channels); for(int k=0;k<numFrames;k++){ multibuffer[j][k] = buffer[k*channels+j]; } ALuint albuffer; alSourceUnqueueBuffers(sources[i*channels+j], 1, &albuffer); alBufferData(albuffer,AL_FORMAT_MONO16,&multibuffer[j][0],buffer.size()*2/channels,samplerate); alSourceQueueBuffers(sources[i*channels+j], 1, &albuffer); } }else{ ALuint albuffer; alSourceUnqueueBuffers(sources[i], 1, &albuffer); alBufferData(albuffer,AL_FORMAT_MONO16,&buffer[0],buffer.size()*2/channels,samplerate); alSourceQueueBuffers(sources[i], 1, &albuffer); } if(stream_end){ break; } } ALint state; alGetSourcei(sources[i*channels],AL_SOURCE_STATE,&state); if(state != AL_PLAYING && (streamf || mp3streamf) && !stream_end){ alSourcePlayv(channels,&sources[i*channels]); } stream_end = false; } ofSleepMillis(1); } }
void ofxNetworkSyncClientState::threadedFunction(){ while(isThreadRunning()){ if(step == CALIBRATING && calibrator.isFinishMeasuremant()){ stopCalibration(); } if(! isConnected()){ ofNotifyEvent(clientDisconnected, clientId, this); break; } string recv = tcpServer->receive(clientId); if(recv.length() > 0){ ofNotifyEvent(messageReceived, recv, this); server->onClientMessageReceived(clientId, recv); } ofSleepMillis(10); } }
void ofApp::exit(){ cout << "Start termination." << endl; cout << "EXIT: KILL ALL NODE(closing the process of git-hub)" << endl; exe("killall node"); int flg = 1; GismoManager& gismo = GismoManager::getInstance(); gismo.bang("/yaritori/save", &flg); cout << ": : :" << endl; cout << "Auto save finished." << endl; cout << "waiting the file writing..." << endl; ofSleepMillis(1000); cout << "yaritori all finished." << endl; }
void terminateApp(const std::string & module, const std::string & reason, float secondsOnScreen){ ofLogFatalError("ofxApp") << "terminateApp()!"; ofxSimpleHttp::destroySslContext(); ofLogFatalError("ofxApp") << ""; ofLogFatalError("ofxApp") << "-----------------------------------------------------------------------------------------------------------"; ofLogFatalError("ofxApp") << ""; ofLogFatalError("ofxApp") << "ofxApp is terminating because the module \"" << module << "\" found an unrecoverable error."; ofLogFatalError("ofxApp") << "\"" << reason << "\""; ofLogFatalError("ofxApp") << "This message will be on screen for " << (int)secondsOnScreen << " seconds, then the app will quit."; ofLogFatalError("ofxApp") << ""; ofLogFatalError("ofxApp") << "-----------------------------------------------------------------------------------------------------------"; ofLogFatalError("ofxApp") << ""; ofxThreadSafeLog::one()->close(); if(ofxApp::get().isWindowSetup()){ ofxSuperLog::getLogger()->setScreenLoggingEnabled(true); //show log if json error ofxSuperLog::getLogger()->getDisplayLogger().setPanelWidth(1.0); int numFrames = secondsOnScreen * 1000 / 16; //stay up a bit so that you can read logs on screen OFXAPP_REPORT("ofxAppTerminate_" + module, reason, 2); //hijack OF and refresh screen & events by hand at ~60fps if(ofGetWindowPtr()){ for(int i = 0; i < numFrames; i++ ){ ofSetupScreen(); ofClear(0,0,0,255); ofxSuperLog::getLogger()->getDisplayLogger().draw(ofGetWidth(), ofGetHeight()); ofGetMainLoop()->pollEvents(); if(ofGetWindowPtr()->getWindowShouldClose()){ ofLogFatalError("ofxApp") << "Quitting by user action"; std::exit(-1); } ofGetWindowPtr()->swapBuffers(); ofSleepMillis(16); } } }else{ ofLogFatalError("ofxApp") << "Terminating ofxApp before the app window is setup."; } std::exit(0); };
void ofxFadeAnimation::threadedFunction(){ while( isThreadRunning() != 0 ){ ofSleepMillis(1 * 60); if( lock() ){ if (!_bTimeOut){ count = count - 0.06; _alpha = (_fadeIn ? (_alpha + 0.06 * _alphaStride) : (_alpha - 0.06 * _alphaStride)); //cout << "threaded function alpha = " << _alpha <<endl; if (count <= 0){ _bTimeOut = true; } } unlock(); }else{ cout << "lock failed" <<endl; } } }
void threadedFunction() { while(isThreadRunning()) { for(int i = 0; i < backNotes.size(); i++) { MidiNote& cur = backNotes[i]; if(cur.finished()) { midi.sendNoteOff(cur.channel, cur.pitch, 0); } } ofRemove(backNotes, isFinished); lock(); swap(); unlock(); ofSleepMillis(1); } // silence remaining notes swap(); for(int i = 0; i < backNotes.size(); i++) { MidiNote& cur = backNotes[i]; midi.sendNoteOff(cur.channel, cur.pitch, 0); } }
string ofxPTZControl::sendCommand(string command){ string cmd = "http://" + ip + ":" + ofToString(port) + "/cgi-bin/aw_ptz?cmd=%23" + command + "&res=1"; float currentTime = ofGetElapsedTimeMillis(); if (currentTime - lastCMDTime > 120){ // dont spam the same command response = sendRawCommand(cmd); lastcmd = cmd; lastCMDTime = currentTime; } else if (lastcmd != cmd) { // if it is a new command wait untill 120 ms since the last command send, then send it ofSleepMillis(120 - (currentTime - lastCMDTime)); response = sendRawCommand(cmd); lastcmd = cmd; lastCMDTime = currentTime; } return response.data; }
// discover lasers on the network and give them timeslots void ForestSerialPort::discover() { rodInfos.clear(); int slotId = 1; progress = 0; float progressIncrement = 1.f/MAX_BOARDS_PER_NETWORK; for(int id = 1; id <= MAX_BOARDS_PER_NETWORK; id++) { if(foundDeviceIds.find(id)==foundDeviceIds.end()) { bool success = setTimeslot(id, slotId); if(success) { printf("DEVICE ID: %d - TIMESLOT: %d\n", id, slotId); foundDeviceIds.insert(id); slotId++; } progress += progressIncrement; ofSleepMillis(3); } } report = "=================================\n"; report += "Forest Serial Port " + serialNo + "\n"; report += "Scanned for " +ofToString(MAX_BOARDS_PER_NETWORK) + " boards, found: " + ofToString(rodInfos.size()) + "\n"; string top = "DEVICE ID: "; string bottom = "TIMESLOT: "; map<int,RodInfo>::iterator it = rodInfos.begin(); for( ; it != rodInfos.end(); it++) { top += padMe((*it).second.id, 5); bottom += padMe((*it).second.timeslot, 5); } report += top + "\n" + bottom + "\n"; report += "=================================\n"; printf("%s\n", report.c_str()); printf("There are %d rodInfos\n", rodInfos.size()); }
//-------------------------------------------------------------- void ofApp::draw(){ ofSleepMillis(10); cout << "Frame rate = " << std::fixed << std::setw( 5 ) << std::setprecision( 2 ) << std::setfill( '0' ) <<ofGetFrameRate() << " Hz, "; if (myLidarLite.isOutputNew()) { int distance = -1; int signalStrength = -1; // Read the distance and signalStrength myLidarLite.getOutput(distance, signalStrength); cout << "Distance = " << distance << " cm, "; // Read the status (useful for debug) //int status = myLidarLite.status(); //cout << myLidarLite.statusString(status); // Power user technique: // Weighting the new distance value by the measured signal strength // Helps eliminate noise created by the sun and by not detecting any objects int minSigStrength = 20; // signal strength minimum int fullSigStrength = 80; // signal strength that gets full weight float weight; if (signalStrength < minSigStrength) { // We're below the min signal strength // Set distance to -1 to indicate no object was found wDistance = -1; // Indicates no object was found } else { // Weight by the signal strength weight = ofMap(signalStrength, minSigStrength, fullSigStrength, 0.05f, 1.f, true); // Calculate the weighted distance wDistance = ((float) distance)*weight + ((float) wDistance)*(1-weight); } cout << "wDistance = " << wDistance << " cm, "; cout << "signalStrength = " << signalStrength << ", "; cout << endl; } }
void MyWorkUnit::process(){ //this will be exectued on a non-main thread, keep this in mind if using openGL (ofImage, OpenCV, etc...) //do your lengthy operations here, and update "processPercent" with your progress if you want to visualize it on the draw method //in this example, we'll be calculating the factorial of the input value result = 1; int iterations = input; for(int i = 0; i < iterations; i++){ //let's pretend this operation takes a looong time... #ifdef REAL_CPU_LOAD float c = 0; //by doing lots of useless calculations for(int j = 0; j < 50000; j++){ for(int k = 0; k < 5000; k++){ c += sqrtf(sinf( j * 0.1f)); } } #else ofSleepMillis(250); //or by sleeping for a while #endif result *= i; //iterative calculation of factorial setPercentDone( (float)i / (iterations - 1) ); //update this work unit progress in each loop if (isJobPendingCancelation()){ //check if we have been asked to stop this job, to stop if early if required return; } } //if required, you can mark a WorkUnit as failed. //in this example, a small number of units will randomly fail if ( ofRandom(1.0f) < 0.01 ){ setStatusFailed(); } //our processing is done and will be enqueued in the results queue //we should now gather the result from the main thread }
//-------------------------------------------------------------- void testApp::update() { if (m_run) { ++m_BallPos; //ofSleepMillis(40); ofxOscMessage m; //m.setAddress( "/mouse/position" ); m.setAddress( "/fx" ); m.addStringArg("positionx"); m.addIntArg( pts[m_BallPos].x ); m.addStringArg("positiony"); m.addIntArg( pts[m_BallPos].y ); sender.sendMessage( m ); if (showOscDebugPosition) { setOscDebugMessage(m); } if ( m_BallPos >= nPts) { m_BallPos = 0; } //if ( pts[m_BallPos].x == m_samplVec[m_BallPos] checkPlayPos(pts[m_BallPos].x, pts[m_BallPos].y); } else { m_BallPos = 0; } if (debugMode) { } ofSleepMillis(40); }
void imageGrid::loadStudentNames() { //-------read names from text file //http://forum.openframeworks.cc/t/accents-with-ofxftgl/5752/3?u=stephanschulz //save cpp as western iso latin to avoid complains about special chars ifstream nameFile; //declare a file stream nameFile.open( ofToDataPath("names.txt").c_str() ); //open your text file int lineCnt = 0; int name_cnt = 0; while(nameFile!=NULL) //as long as theres still text to be read { string line; //declare a string for storage getline(nameFile, line); //get a line from the file, put it in the string if(line.length() > 0) { //cout<<"line = "<<line<<endl; vector<string> lineParts; lineParts = ofSplitString(line, ":"); string firstName = lineParts[0]; string lastName = ""; if(lineParts.size() > 1) lastName = lineParts[1]; // int temp_node1 = ofToInt(lineParts[2]); // cout<<"name "<<name_cnt<<" "<<lineParts[0]<<endl; cout<<"name "<<name_cnt<<" "<<line<<":"<<endl; portrait_firstNames.push_back(firstName); portrait_lastNames.push_back(lastName); //line; //lineParts[0]; name_cnt++; ofSleepMillis(10); } //zonesNodes.push_back(str); //push the string onto a vector of strings } nameFile.close(); cout<<"done loadStudentNames"<<endl; }
//-------------------------------------------------------------- void SineChanger::threadedFunction() { cout << "threadedFunction" << endl; for (;;) { if( lock() ) { // hide old messages for ( int i=0; i<NUM_MSG_STRINGS; i++ ) { if ( timers[i] < ofGetElapsedTimef() ) msg_strings[i] = ""; } // check for waiting messages while( receiver.hasWaitingMessages() ) { // get the next message ofxOscMessage m; receiver.getNextMessage( &m ); // check for mouse moved message if ( m.getAddress() == "/counter" ) { // both the arguments are int32's counter = m.getArgAsInt32( 0 ); } } // count++; // if(count > 500) count = 200; unlock(); ofSleepMillis(20); } // cout << "in thread. count=" << count << endl; } }
//-------------------------- void pmThreadedOscReceiver::threadedFunction() { while( isThreadRunning() != 0 ) { // OSC // check for waiting messages while(ofxOscReceiver::hasWaitingMessages() ) //if(ofxOscReceiver::hasWaitingMessages() ) { // get the next message ofxOscMessage m; ofxOscReceiver::getNextMessage( &m ); // check for any OSC message containing /pm3 //if ( m.getAddress() == "/test" ) if(m.getAddress().find(filterAddress)!=-1) { pmOscMessage pmM; pmM.address = m.getAddress(); if(m.getArgType(0)==OFXOSC_TYPE_FLOAT) { pmM.value = m.getArgAsFloat(0); } else if (m.getArgType(0)==OFXOSC_TYPE_INT32) { pmM.value = float (m.getArgAsInt32(0)); } if(verbose) printf("pmThreadOsc :: new OscMessage In %s :: %f \n",pmM.address.c_str(),pmM.value); ofNotifyEvent(newOscMessage,pmM,this); } } ofSleepMillis(threadSleepMs); } }
void ofApp::connectionSearchCount(){ connections.clear(); for(int i =0; i <searchTerms.size(); i++){ for(int j = i+1; j < searchTerms.size(); j++){ string searchTerm = searchTerms[i]+"%20"+searchTerms[j]; //cout<< "connection string " << searchTerm << endl; int n = myAPI.numSearchResults(searchTerm); //cout << "number of connections are " << n << endl; ofSleepMillis(5000); connections.push_back(n); } } //this is for debugging -- limit server requests for (auto c : connections) { cout << "connections.push_back("<<c<<");"<<endl; } }
string mareklib::getHomeDirectory() { FILE *fp = popen("who am I", "r"); if(fp!=NULL) { printf("popen made it\n"); char name[512]; string username; ofSleepMillis(100); if(fgets(name, 512, fp)) { printf("fgets\n"); username = name; if(username.find(' ')!=-1) { username = username.substr(0, username.find(' ')); string home = "/Users/"+username; return home; } } pclose(fp); } else { printf("Couldn't find user's name, going with default\n"); } return ""; }
void Player::updateHeading(){ /* Request current heading of human player. */ if(!FAKING){ string newAngle; int newHeading; unsigned char newByte = 0; port->writeByte('e'); ofSleepMillis(100); while(newByte != '\n'){ newByte = port->readByte(); if(newByte != 0xff){ newAngle.append((char *)&newByte,1); } } printf("New heading = %s\n",newAngle.c_str()); istringstream stream(newAngle); stream >> newHeading; if(newHeading != 0) heading = newHeading; newAngle.clear(); }
bool Plotter::checkSendMore() { serial.flush(true, true); const char *getAvailable = "\x1b.B"; serial.writeBytes((unsigned char *) getAvailable, 3); int counter = 0; while (counter < 100) { if (serial.available() == 5) { unsigned char readBytes[5]; serial.readBytes(readBytes, 5); int space = atoi((char*) readBytes); return space > 1300; } ofSleepMillis(100); counter++; } cout << "serial timeout" << endl; return false; }
void mpeServerTCP::threadedFunction() { while(isThreadRunning()){ if(shouldTriggerFrame){ float now = ofGetElapsedTimef(); float elapsed = (now - lastFrameTriggeredTime); //cout << "should trigger frame!" << endl; if(elapsed >= 1.0/framerate){ //cout << "triggered frame with framerate error of " << fabs( elapsed - 1.0/framerate) << endl; string message = "G,"+ofToString(currentFrame); if (newMessage){ message += currentMessage; newMessage = false; currentMessage = ""; } server.sendToAll(message); for(int i = 0; i < connections.size(); i++){ connections[i].ready = false; } shouldTriggerFrame = false; lastFrameTriggeredTime = now; currentFrame++; } } else { //check for dead clients bool lostConnection = false; for(int c = 0; c < numExpectedClients; c++){ if(connections[c].started && !server.isClientConnected(connections[c].tcpServerIndex)){ connections[c].started = false; lostConnection = true; } } if(allconnected && lostConnection){ ofLog(OF_LOG_NOTICE, "MPE :: Client Disconnected -- RESET"); //oops someone left printClientStatus(); currentFrame = 0; shouldTriggerFrame = false; allconnected = false; server.sendToAll("R"); } //cout << "All clients are connected! " << endl; for(int i = 0; i < server.getLastID(); i++){ if(!server.isClientConnected(i)){ continue; } string response = server.receive(i); if(response == ""){ continue; } // cout << "received a response " << response << endl; char first = response.at(0); if(first == 'L'){ //Listener connected listeners.push_back(i); } else if(first == 'S'){ //that's the start! int clientID = ofToInt(response.substr(1,1)); if(clientID < numExpectedClients){ vector<string> info = ofSplitString(response, ",", true, true); if(connections[clientID].started && currentFrame != 0){ //client already started, must have reset... allconnected = false; currentFrame = 0; shouldTriggerFrame = false; server.sendToAll("R"); } connections[clientID].tcpServerIndex = i; connections[clientID].started = true; connections[clientID].name = info[1]; cout << "Client ID " << clientID << " with response " << response << endl; //TODO: parse name printClientStatus(); } else{ ofLog(OF_LOG_ERROR, "Received Client ID " + ofToString(clientID) + " out of range"); } } else if(first == 'D'){ if(!allconnected){ continue; } vector<string> info = ofSplitString(response, ",", true, true); if(info.size() >= 3){ int clientID = ofToInt(info[1]); int fc = ofToInt(info[2]); if(fc == currentFrame){ //todo validate client id connections[clientID].ready = true; //cout << " client " << clientID << " is ready " << endl; } if(info.size() > 3){ newMessage = true; for(int i = 3; i < info.size(); i++){ currentMessage += ":" + info[i]; } //cout << "NEW FORMAT :: MESSSAGE IS " << currentMessage << endl; } } else { ofLog(OF_LOG_ERROR, "MPE Server :: Response String " + response + " Invalid size"); } } } if(!allconnected){ allconnected = true; for(int c = 0; c < connections.size(); c++){ if(!connections[c].started){ allconnected = false; break; } } if(allconnected){ shouldTriggerFrame = true; cout << "All clients connected!" << endl; } } //All connected and going else { bool allready = true; for(int c = 0; c < connections.size(); c++){ if(!connections[c].ready){ allready = false; break; } } if(allready){ shouldTriggerFrame = true; } } } ofSleepMillis(5); }//end while }