int detectFileMPISize(Options& options, Dimensions &fileMPISizeDim) { int result = RESULT_OK; DataCollector *dc = NULL; #if (SPLASH_SUPPORTED_PARALLEL==1) if (options.parallelFile) dc = new ParallelDataCollector(MPI_COMM_WORLD, MPI_INFO_NULL, Dimensions(options.mpiSize, 1, 1), 1); else #endif dc = new SerialDataCollector(1); DataCollector::FileCreationAttr fileCAttr; DataCollector::initFileCreationAttr(fileCAttr); fileCAttr.fileAccType = DataCollector::FAT_READ; try { dc->open(options.filename.c_str(), fileCAttr); dc->getMPISize(fileMPISizeDim); dc->close(); } catch (DCException e) { std::cerr << "[0] Detecting file MPI size failed!" << std::endl << e.what() << std::endl; fileMPISizeDim.set(0, 0, 0); result = RESULT_ERROR; } delete dc; dc = NULL; return result; }
int main(int argc, char** argv) { // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("com.example.hello-myo"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; arduino = fopen("/dev/cu.usbmodem1411","w"); test = fopen("test.txt", "w"); if (arduino == NULL) { printf("not open\n"); return -1 ; } else { printf("arduino opened\n"); sleep(1); std::string command = "t30i0m0r0p0"; fprintf(test,"%s", command.c_str()); fflush(test); } // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); // Finally we enter our main loop. while (1) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000/20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. collector.print(); } // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } }
int main(int nargs, char *args[]) { const char *filename; filename = (nargs > 1) ? args[1] : LOG_FILE; DataCollector *d = new DataCollector(filename); d->startCollectingData(); d->joinCollectingThread(); return 0; }
int main(int argc, char** argv) { sf::RenderWindow window(sf::VideoMode(400, 400), "Myo color picker"); shape.setPosition(sf::Vector2f(50, 50)); shape.setFillColor(sf::Color::Green); color_input = true; // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("com.example.hello-myo"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForAnyMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForAnyMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); // Finally we enter our main loop. while (1) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000/20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. collector.print(); } // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } }
int main(void) { char logFileName[300] = "/home/danconde/coleta/europa.log"; ResourceData parameters(0.5f, 100000); bool answer; DataCollector *dtCollector = new DataCollector(logFileName); unsigned int i, count; UsageData *testUsageData; setValidResourceDataThreshold(0.9f); setPredictionHours(6); cout << "timestamp\tp_cpu\tp_mem\tanswer\tpcs\tvcs\tcoff" << endl; // pcs = predicted cpu satisfability // vcs = verified cpu satisfability UsagePredictor *up = new UsagePredictor(new KMeansClusteringAlgorithm(), dtCollector); vector<UsageData*> *usageDatas = dtCollector->getUnclassifiedData(); for (unsigned int k = 0; k < usageDatas->size(); k += 3) { testUsageData = usageDatas->at(k); if (testUsageData->isValid()) { for (unsigned int j = 6; j < 18; j++) { Timestamp timestamp = Timestamp(testUsageData->getDate().beginningOfSameDay().getRawTime() + j*3600); answer = up->canRunGridApplication(timestamp, parameters, testUsageData); cout << timestamp.formattedPrint() << "\t" << parameters << "\t" << answer << "\t"; vector<double> prediction = up->getPrediction(timestamp, CPU_USAGE, getPredictionHours(), testUsageData); count = 0; for (i = 0; i < prediction.size(); i++) if (prediction[i] + parameters.getCpuUsage() <= 1.0f) count++; cout << (static_cast<double>(count) / prediction.size()) * 100 << "%\t"; count = 0; for (i = 0; i < prediction.size(); i++) { ResourceData rd = testUsageData->getData()[(timestamp.getSecondInDay()/COLLECT_INTERVAL) + SAMPLES_PER_DAY + i]; if (rd.isValid() && (rd.getCpuUsage() + parameters.getCpuUsage() <= 1.0f)) count++; } cout << (static_cast<double>(count) / prediction.size()) * 100 << "%\t"; cout << testUsageData->resourceAverage(CPU_USAGE, timestamp.getSecondInDay()/COLLECT_INTERVAL, timestamp.getSecondInDay()/COLLECT_INTERVAL + SAMPLES_PER_DAY) << endl; } } } /* informar qual cluster foi encontrado */ /* comparar resultado da predicao com o realizado */ /* pegar o resultado do getPrediction e ver a porcentagem de elementos do vetor de previsao condisseram com o realizado */ return 0; }
int main() { DataCollector myDataCollector; myDataCollector.startCollect(); int seconds = 5; for(int i = 0; i < seconds; i++) { std::this_thread::sleep_for(std::chrono::seconds(2)); } return 0; }
/* updateMethod - called every 16 milliseconds, meant to update the animation and add more particles to the list of particles */ void updateMethod(int value) { //iterate through list of particles and call the move function of the particle has no expired else remove it from the list for(list<particle>::iterator i = listOfParticles.begin(); i != listOfParticles.end(); ++i) { i->move(gravity, flatQuadSize, friction); } glutTimerFunc(16, updateMethod, 0); //call updateMethod after 16 seconds glutPostRedisplay(); //call display function hub.run(1000/20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. collector.print(); }
bool Parallel_SimpleDataTest::subtestFill(int32_t iteration, int currentMpiRank, const Dimensions mpiSize, const Dimensions mpiPos, uint32_t elements, MPI_Comm mpiComm) { bool results_correct = true; DataCollector::FileCreationAttr fileCAttr; #if defined TESTS_DEBUG if (currentMpiRank == 0) std::cout << "iteration: " << iteration << std::endl; #endif // write data to file DataCollector::initFileCreationAttr(fileCAttr); fileCAttr.fileAccType = DataCollector::FAT_CREATE; fileCAttr.enableCompression = false; parallelDataCollector->open(HDF5_FILE, fileCAttr); int dataWrite = currentMpiRank + 1; uint32_t num_elements = (currentMpiRank + 1) * elements; Dimensions grid_size(num_elements, 1, 1); #if defined TESTS_DEBUG std::cout << "[" << currentMpiRank << "] " << num_elements << " elements" << std::endl; #endif Dimensions globalOffset, globalSize; parallelDataCollector->reserve(iteration, grid_size, &globalSize, &globalOffset, 1, ctInt, "reserved/reserved_data"); int attrVal = currentMpiRank; parallelDataCollector->writeAttribute(iteration, ctInt, "reserved/reserved_data", "reserved_attr", &attrVal); uint32_t elements_written = 0; uint32_t global_max_elements = mpiSize.getScalarSize() * elements; for (size_t i = 0; i < global_max_elements; ++i) { Dimensions write_size(1, 1, 1); if (i >= num_elements) write_size.set(0, 0, 0); Dimensions write_offset(globalOffset + Dimensions(elements_written, 0, 0)); parallelDataCollector->append(iteration, write_size, 1, write_offset, "reserved/reserved_data", &dataWrite); if (i < num_elements) elements_written++; } MPI_CHECK(MPI_Barrier(mpiComm)); attrVal = -1; parallelDataCollector->readAttribute(iteration, "reserved/reserved_data", "reserved_attr", &attrVal, NULL); CPPUNIT_ASSERT(attrVal == currentMpiRank); parallelDataCollector->close(); MPI_CHECK(MPI_Barrier(mpiComm)); // test written data using various mechanisms fileCAttr.fileAccType = DataCollector::FAT_READ; // need a complete filename here std::stringstream filename_stream; filename_stream << HDF5_FILE << "_" << iteration << ".h5"; Dimensions size_read; Dimensions full_grid_size = globalSize; // test using SerialDataCollector if (currentMpiRank == 0) { int *data_read = new int[full_grid_size.getScalarSize()]; memset(data_read, 0, sizeof (int) * full_grid_size.getScalarSize()); DataCollector *dataCollector = new SerialDataCollector(1); dataCollector->open(filename_stream.str().c_str(), fileCAttr); dataCollector->read(iteration, "reserved/reserved_data", size_read, data_read); dataCollector->close(); delete dataCollector; CPPUNIT_ASSERT(size_read == full_grid_size); CPPUNIT_ASSERT(size_read[1] == size_read[2] == 1); int this_rank = 0; uint32_t elements_this_rank = num_elements; for (uint32_t i = 0; i < size_read.getScalarSize(); ++i) { if (i == elements_this_rank) { this_rank++; elements_this_rank += num_elements * (this_rank + 1); } CPPUNIT_ASSERT(data_read[i] == this_rank + 1); } delete[] data_read; } MPI_CHECK(MPI_Barrier(mpiComm)); return results_correct; }
bool Parallel_SimpleDataTest::subtestWriteRead(int32_t iteration, int currentMpiRank, const Dimensions mpiSize, const Dimensions mpiPos, const Dimensions gridSize, uint32_t dimensions, MPI_Comm mpiComm) { bool results_correct = true; DataCollector::FileCreationAttr fileCAttr; std::set<std::string> datasetNames; #if defined TESTS_DEBUG if (currentMpiRank == 0) std::cout << "iteration: " << iteration << std::endl; #endif size_t bufferSize = gridSize[0] * gridSize[1] * gridSize[2]; // write data to file DataCollector::initFileCreationAttr(fileCAttr); fileCAttr.fileAccType = DataCollector::FAT_CREATE; fileCAttr.enableCompression = false; parallelDataCollector->open(HDF5_FILE, fileCAttr); int *dataWrite = new int[bufferSize]; for (uint32_t i = 0; i < bufferSize; i++) dataWrite[i] = currentMpiRank + 1; parallelDataCollector->write(iteration, ctInt, dimensions, gridSize, "deep/folder/data", dataWrite); datasetNames.insert("deep/folder/data"); parallelDataCollector->write(iteration, ctInt, dimensions, gridSize, "deep/folder/data2", dataWrite); datasetNames.insert("deep/folder/data2"); parallelDataCollector->write(iteration, ctInt, dimensions, gridSize, "another_dataset", dataWrite); datasetNames.insert("another_dataset"); parallelDataCollector->close(); delete[] dataWrite; dataWrite = NULL; MPI_CHECK(MPI_Barrier(mpiComm)); // test written data using various mechanisms fileCAttr.fileAccType = DataCollector::FAT_READ; // need a complete filename here std::stringstream filename_stream; filename_stream << HDF5_FILE << "_" << iteration << ".h5"; Dimensions size_read; Dimensions full_grid_size = gridSize * mpiSize; int *data_read = new int[full_grid_size.getScalarSize()]; memset(data_read, 0, sizeof (int) * full_grid_size.getScalarSize()); // test using SerialDataCollector if (currentMpiRank == 0) { DataCollector *dataCollector = new SerialDataCollector(1); dataCollector->open(filename_stream.str().c_str(), fileCAttr); dataCollector->read(iteration, "deep/folder/data", size_read, data_read); dataCollector->close(); delete dataCollector; CPPUNIT_ASSERT(size_read == full_grid_size); CPPUNIT_ASSERT(testData(mpiSize, gridSize, data_read)); } MPI_CHECK(MPI_Barrier(mpiComm)); // test using full read per process memset(data_read, 0, sizeof (int) * full_grid_size.getScalarSize()); ParallelDataCollector *readCollector = new ParallelDataCollector(mpiComm, MPI_INFO_NULL, mpiSize, 1); readCollector->open(HDF5_FILE, fileCAttr); /* test entries listing */ { DataCollector::DCEntry *entries = NULL; size_t numEntries = 0; int32_t *ids = NULL; size_t numIDs = 0; readCollector->getEntryIDs(NULL, &numIDs); /* there might be old files, but we are at least at the current iteration */ CPPUNIT_ASSERT(numIDs >= iteration + 1); ids = new int32_t[numIDs]; readCollector->getEntryIDs(ids, NULL); readCollector->getEntriesForID(iteration, NULL, &numEntries); CPPUNIT_ASSERT(numEntries == 3); entries = new DataCollector::DCEntry[numEntries]; readCollector->getEntriesForID(iteration, entries, NULL); CPPUNIT_ASSERT(numEntries == datasetNames.size()); for (uint32_t i = 0; i < numEntries; ++i) { /* test that listed datasets match expected dataset names*/ CPPUNIT_ASSERT(datasetNames.find(entries[i].name) != datasetNames.end()); } delete[] entries; delete[] ids; } readCollector->read(iteration, "deep/folder/data", size_read, data_read); readCollector->close(); CPPUNIT_ASSERT(size_read == full_grid_size); CPPUNIT_ASSERT(testData(mpiSize, gridSize, data_read)); delete[] data_read; MPI_CHECK(MPI_Barrier(mpiComm)); // test using parallel read data_read = new int[gridSize.getScalarSize()]; memset(data_read, 0, sizeof (int) * gridSize.getScalarSize()); const Dimensions globalOffset = gridSize * mpiPos; readCollector->open(HDF5_FILE, fileCAttr); readCollector->read(iteration, gridSize, globalOffset, "deep/folder/data", size_read, data_read); readCollector->close(); delete readCollector; CPPUNIT_ASSERT(size_read == gridSize); for (size_t k = 0; k < gridSize[2]; ++k) { for (size_t j = 0; j < gridSize[1]; ++j) { for (size_t i = 0; i < gridSize[0]; ++i) { size_t index = k * gridSize[1] * gridSize[0] + j * gridSize[0] + i; if (data_read[index] != currentMpiRank + 1) { #if defined TESTS_DEBUG std::cout << index << ": " << data_read[index] << " != expected " << currentMpiRank + 1 << std::endl; #endif results_correct = false; break; } } if (!results_correct) break; } if (!results_correct) break; } delete[] data_read; MPI_CHECK(MPI_Barrier(mpiComm)); return results_correct; }
int main(int argc, char *argv[]) { // Initalizing these to NULL prevents segfaults! AVFormatContext *pFormatCtx = NULL; int i, videoStream; AVCodecContext *pCodecCtxOrig = NULL; AVCodecContext *pCodecCtx = NULL; // 코덱 컨트롤러(?) 이걸 자주 쓴다. AVCodec *pCodec = NULL; // 영상을 디코딩할 코덱 AVFrame *pFrame = NULL; // 영상데이터 라고 보면됨. AVPacket packet; int frameFinished; struct SwsContext *sws_ctx = NULL; // Convert the image into YUV format that SDL uses //SDL 관련 변수 SDL_Overlay *bmp; SDL_Surface *screen; SDL_Rect rect; SDL_Event event; CVideoSocket videoSocket; //줌인 줌 아웃을 위한 변수 int rect_w = 0; int rect_h = 0; // We catch any exceptions that might occur below -- see the catch statement for more details. try { // 여기부터 마이오 초기화 // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. // 마이오에서 제공하는 어플리케이션과 연결하는 허브 생성 myo::Hub hub("com.example.hello-myo"); // 마이오 찾는중 ... std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. // 마이오를 찾는 동안 대기하는 소스코드 myo::Myo* myo = hub.waitForMyo(10000); // If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. // 마이오가 존재하지 않을경우 예외처리 if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. // 마이오에서 얻은 데이터를 가공해주는 클래스 DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. // 데이터를 지속적으로 받아온다. hub.addListener(&collector); //---여기까지 마이오 초기화 // SDL 초기화 InitSDL(); // Open video file // 파일 또는 데이터 스트림을 연다. if (avformat_open_input(&pFormatCtx, videoSocket.videoStreamUrl, NULL, NULL) != 0) { return -1; // Couldn't open file } // Retrieve stream information // 데이터 스트림의 정보를 얻어온다. if (avformat_find_stream_info(pFormatCtx, NULL) < 0) { return -1; // Couldn't find stream information } // Dump information about file onto standard error av_dump_format(pFormatCtx, 0, videoSocket.videoStreamUrl, 0); // Find the first video stream // 비디로 스트림을 찾는과정 - 어떤 형식의 데이터 스트림인지 판별 ( 우리는 h.264로 고정되어있지만...) videoStream = -1; for (i = 0; (unsigned)i < pFormatCtx->nb_streams; i++) { if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { videoStream = i; break; } } if (videoStream == -1) { return -1; // Didn't find a video stream } // Get a pointer to the codec context for the video stream pCodecCtxOrig = pFormatCtx->streams[videoStream]->codec; // Find the decoder for the video stream pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id); if (pCodec == NULL) { fprintf(stderr, "Unsupported codec!\n"); return -1; // Codec not found } // Copy context // 왜 인지 모르겠지만 그냥 쓰지 않고 복사해서 사용한다. pCodecCtx = avcodec_alloc_context3(pCodec); if (avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) { fprintf(stderr, "Couldn't copy codec context"); return -1; // Error copying codec context } // Open codec if (avcodec_open2(pCodecCtx, pCodec, NULL)<0) { return -1; // Could not open codec } // Allocate video frame pFrame = av_frame_alloc(); // Make a screen to put our video // 스크린을 생성 #ifndef __DARWIN__ screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0); #else screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 24, 0); #endif if (!screen) { fprintf(stderr, "SDL: could not set video mode - exiting\n"); exit(1); } // Allocate a place to put our YUV image on that screen // 이미지를 스크린에 그림 bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height, SDL_YV12_OVERLAY, screen); // initialize SWS context for software scaling sws_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL ); while (av_read_frame(pFormatCtx, &packet) >= 0) { // 메인 루프 // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // 데이터를 어느정도 주기로 받아올지 정하는 소스 // 이 값이 낮아지면 영상을 받아오는데도 딜레이가 걸리기때문에 원하는 fps를 고려해야한다. hub.run(1000 / 500); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. // 마이오 상태 모니터링 코드 collector.print(); // 마이오 루프 여기까지 // Is this a packet from the video stream? if (packet.stream_index == videoStream) { // Decode video frame avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet); // Did we get a video frame? // 비디오 프레임을 비트맵 이미지로 변환 if (frameFinished) { SDL_LockYUVOverlay(bmp); AVPicture pict; pict.data[0] = bmp->pixels[0]; pict.data[1] = bmp->pixels[2]; pict.data[2] = bmp->pixels[1]; pict.linesize[0] = bmp->pitches[0]; pict.linesize[1] = bmp->pitches[2]; pict.linesize[2] = bmp->pitches[1]; // Convert the image into YUV format that SDL uses sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pict.data, pict.linesize); SDL_UnlockYUVOverlay(bmp); // 소프트웨어상으로 줌인 줌아웃을 하기위해 영상프레임의 사이즈를 조절 rect.x = -rect_w/2; rect.y = -rect_h/2; rect.w = pCodecCtx->width + rect_w; rect.h = pCodecCtx->height + rect_h; SDL_DisplayYUVOverlay(bmp, &rect); } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); SDL_PollEvent(&event); //// 마이오의 동작을 체크해서 메시지 송신 //// 좌우 카메라 컨트롤 if (collector.currentPose == myo::Pose::waveOut) { SendData(videoSocket.ClientSocket, "right", videoSocket.ToServer); rest = true; } if (collector.currentPose == myo::Pose::waveIn) { SendData(videoSocket.ClientSocket, "left", videoSocket.ToServer); rest = true; } // 상하 카메라 컨트롤 if (collector.currentPose == myo::Pose::fingersSpread && collector.pitch_w > 10) { SendData(videoSocket.ClientSocket, "up", videoSocket.ToServer); rest = true; } if (collector.currentPose == myo::Pose::fingersSpread && collector.pitch_w < 6) { SendData(videoSocket.ClientSocket, "down", videoSocket.ToServer); rest = true; } if (collector.currentPose == myo::Pose::rest &&rest == true) { SendData(videoSocket.ClientSocket, "stop", videoSocket.ToServer); rest = false; } if (collector.currentPose == myo::Pose::doubleTap && collector.roll_w <= 5) { collector.currentPose = myo::Pose::rest; rest = true; myo->lock(); } if (collector.currentPose == myo::Pose::doubleTap && collector.roll_w > 5) { rest = true; myo->unlock(myo::Myo::unlockHold); } // 마이오의 동작을 체크해서 줌인 줌 아웃 if (collector.currentPose == myo::Pose::fist && collector.roll_w < 6) { ZoomOut(rect_w, rect_h, 0); } if (collector.currentPose == myo::Pose::fist && collector.roll_w > 8) { ZoomIn(rect_w, rect_h, 300); } // 키 이벤트를 받는 함수 switch (event.type) { case SDL_QUIT: SDL_Quit(); exit(0); break; case SDL_KEYDOWN: /* Check the SDLKey values and move change the coords */ switch (event.key.keysym.sym){ case SDLK_LEFT: // 문자열 송신 SendData(videoSocket.ClientSocket, "left", videoSocket.ToServer); break; case SDLK_RIGHT: // 문자열 송신 SendData(videoSocket.ClientSocket, "right", videoSocket.ToServer); break; case SDLK_UP: SendData(videoSocket.ClientSocket, "up", videoSocket.ToServer); break; case SDLK_DOWN: SendData(videoSocket.ClientSocket, "down", videoSocket.ToServer); break; case SDLK_q: // 줌 인 ZoomIn(rect_w,rect_h,300); break; case SDLK_w: // 줌 아웃 ZoomOut(rect_w, rect_h, 0); break; case SDLK_s: // 모터 stop SendData(videoSocket.ClientSocket, "stop", videoSocket.ToServer); break; case SDLK_x: // 플그램 종료 SDL_Quit(); exit(0); break; default: break; } default: break; } } // Free the YUV frame av_frame_free(&pFrame); // Close the codecs avcodec_close(pCodecCtx); avcodec_close(pCodecCtxOrig); // Close the video file avformat_close_input(&pFormatCtx); // 소켓 닫기 closesocket(videoSocket.ClientSocket); WSACleanup(); return 0; } // 개인적으로 exception handling을 이렇게하는걸 좋아하지 않지만... // 예제에서 이렇게 사용하였기에 일단 이렇게 두었다. catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } }
int main() { //MyForm frm1; MyForm^ frm1 = gcnew MyForm; frm1->ShowDialog(); // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("com.jakechapeskie.SerialCommunication"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForAnyMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForAnyMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); // Finally we enter our main loop. if (frm1->LockingEnalbed) { hub.setLockingPolicy(myo::Hub::LockingPolicy::lockingPolicyStandard); } else { hub.setLockingPolicy(myo::Hub::LockingPolicy::lockingPolicyNone); } while (1) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000 / 20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. collector.print(); std::string poseString = (collector.currentPose.toString()); String^ poseStrorageString = gcnew String(poseString.c_str()); frm1->sendDataOverComm(poseStrorageString); } // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } }
void Experiment::run( DataCollector& dc, RandomNumberGenerator& rng ) { // INITIALIZE double prob_learning_type; // ELITE or BEST OF GENERATION int i; for( int run = 0; run < config->number_of_runs; run++ ) { std::cout << "" << (run+1) << ","; std::cout.flush(); dc.start_new_run( run ); prob_learning_type = 1.; dc.run << "Run seed = " << rng.getCurrentSeed() << endline; //INITIALIZE THE MODEL Model model; model.set_data_collector( dc ); // RUN FOR N GENERATIONS for( i = 0; i < config->number_of_generations; i++ ) { //std::cout << (run+1) << "." << i << "," << std::flush; // ELITIST LEARNING if( config->structural_learning == PIPE && prob_learning_type < config->pipe_prob_elitist_learn ) { model.is_elitist_learning = true; model.adapt( model.get_elite() ); } else { // BEST OF LEARNING // GENERATION BASED LEARNING model.sample( rng ); if( config->fitness_test == RETINA_SWITCHING && ( i % config->retina_switch_after ) == 0 && i != 0 ) retina_test_switch(); // MEASURE FITNESS + INDEX BEST and ELITE model.measure_fitness( dc.run ); // ADAPT PPC TOWARD BEST model.adapt( model.get_best() ); } // MUTATE model.mutate( rng ); prob_learning_type = rng.getRandom(); dc.log_generation( run, i, model ); dc.flush_debug(); if( ( model.stop_condition_met() && config->stop_on_target_reached ) || ( i + 1 ) == config->number_of_generations ) { dc.log_run( run, i, model ); break; } } // RANDOM FITNESS TEST (to confirm findings) dc.log_random_fitness( model ); } dc.log_experiment(); }
int main() { try { // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("com.khalory.puppy"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); collector.connectPipe(); myo::Vector3<float> oldAccel; myo::Vector3<double> curSpeed = myo::Vector3<double>(0, 0, 0); myo::Vector3<double> oldSpeed; myo::Vector3<double> avgSpeed; myo::Vector3<double> curPos = myo::Vector3<double>(0, 0, 0); auto start = std::chrono::high_resolution_clock::now(); auto curTime = std::chrono::high_resolution_clock::now(); long numSteps = 1; // Finally we enter our main loop. while (1) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000 / 20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. //collector.print(); auto finish = std::chrono::high_resolution_clock::now(); long nanos = std::chrono::duration_cast<std::chrono::microseconds>(finish - curTime).count(); long nanosTotal = std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count(); double dt = ((double)nanos) / 1000000.0; double timeTotal = ((double)nanosTotal) / 1000000.0; /*std::cout << "-----" << endl; std::cout << nanos << endl; std::cout << nanosTotal << endl; std::cout << dt << endl; std::cout << timeTotal << endl;*/ curSpeed = myo::Vector3<double>(oldSpeed.x() + (collector.accel.x()*dt), oldSpeed.y() + (collector.accel.y()*dt), oldSpeed.z() + (collector.accel.z()*dt)); avgSpeed = myo::Vector3<double>((numSteps - 1)*avgSpeed.x() + (collector.accel.x()*dt) / numSteps, (numSteps - 1)*avgSpeed.y() + (collector.accel.y()*dt) / numSteps, (numSteps - 1)*avgSpeed.z() + (collector.accel.z()*dt) / numSteps); /*curPos = myo::Vector3<double>(curPos.x() + (.5*(curSpeed.x() + oldSpeed.x())*dt), curPos.y() + (.5*(curSpeed.y() + oldSpeed.y())*dt), curPos.z() + (.5*(curSpeed.z() + oldSpeed.z())*dt));*/ curPos = myo::Vector3<double>(avgSpeed.x() * timeTotal, avgSpeed.y() * timeTotal, avgSpeed.z() * timeTotal); collector.sendData(curPos); oldAccel = collector.accel; oldSpeed = curSpeed; curTime = std::chrono::high_resolution_clock::now(); } // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } return 0; }
///@brief Execute a device. int MyoDevice::run() { try { // Read the initialize file. this->readIniFile(); // Prepare to use SIGService. this->sigService.setName(this->serviceName); this->initializeSigService(sigService); // check receive SIGService data by another thread CheckRecvSIGServiceData checkRecvSIGServiceData; boost::thread thCheckRecvData(&CheckRecvSIGServiceData::run, &checkRecvSIGServiceData, &this->sigService); // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("org.sigverse.myoplugin"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we enable EMG streaming on the found Myo. myo->setStreamEmg(myo::Myo::streamEmgEnabled); // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); // Finally we enter our main loop. while (true) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000/20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. MyoSensorData sensorData = collector.getSensorData(); // Send message to SigServer. std::string messageHeader = this->generateMessageHeader(); std::string sensorDataMessage = sensorData.encodeSensorData(); std::string message = messageHeader + sensorDataMessage; this->sendMessage(this->sigService, message); // std::cout << message << std::endl; } sigService.disconnect(); } catch (std::exception &ex) { std::cout << "run ERR :" << ex.what() << std::endl; throw ex; } return 0; }
int main(int argc, char** argv) { // We catch any exceptions that might occur below -- see the catch statement for more details. try { if (argc != 3 && argc != 2 && argc != 1) { std::cout << "\nusage: " << argv[0] << " [IP address] <port>\n\n" << "Myo-OSC sends OSC output over UDP from the input of a Thalmic Myo armband.\n" << "IP address defaults to 127.0.0.1/localhost\n\n" << "by Samy Kamkar -- http://samy.pl -- [email protected]\n"; exit(0); } if (argc == 1) { int port = 7777; std::cout << "Sending Myo OSC to 127.0.0.1:7777\n"; transmitSocket = new UdpTransmitSocket(IpEndpointName("127.0.0.1", port)); } else if (argc == 2) { std::cout << "Sending Myo OSC to 127.0.0.1:" << argv[1] << "\n"; transmitSocket = new UdpTransmitSocket(IpEndpointName("127.0.0.1", atoi(argv[1]))); } else if (argc == 3) { std::cout << "Sending Myo OSC to " << argv[1] << ":" << argv[2] << "\n"; transmitSocket = new UdpTransmitSocket(IpEndpointName(argv[1], atoi(argv[2]))); } else { std::cout << "well this awkward -- weird argc: " << argc << "\n"; exit(0); } // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("com.samy.myo-osc"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForAnyMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForAnyMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; myo->setStreamEmg(myo::Myo::streamEmgEnabled); // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); // Finally we enter our main loop. while (1) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000/20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. collector.print(); } // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } }
int main(int argc, char** argv) { // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("com.example.hello-myo"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForAnyMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForAnyMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } const int wind_width = 640; const int wind_height = 480; SDL_Window* wind = SDL_CreateWindow("Fuzzy", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, wind_width, wind_height, SDL_WINDOW_SHOWN); if (wind == nullptr) { std::cout << "SDL_CreateWindow Failure, errorcode: " << SDL_GetError() << std::endl; return 1; } SDL_Renderer* rend = SDL_CreateRenderer(wind, -1, SDL_RENDERER_ACCELERATED); if (rend == nullptr) { std::cout << "SDL_CreateRederer Failure, errorcode: " << SDL_GetError() << std::endl; return 1; } SDL_Surface* surf = SDL_GetWindowSurface(wind); if (surf == nullptr) { std::cout << "SDL_GetWindowSurface Failur, errorcode: " << SDL_GetError() << std::endl; return 1; } // Finally we enter our main loop. while (1) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000 / 20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. collector.print(); SDL_UnlockSurface(surf); Uint32* pix; put_pixel(surf, wind_width, wind_height, wind_width*(collector.m_yaw/(18.0)), wind_height*(collector.m_pitch/18.0), 0x00ffffff); SDL_LockSurface(surf); SDL_UpdateWindowSurface(wind); } SDL_Quit(); // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } }
int main() { //create factory PerformerFactory *pf = getPerfFactory(); //config objects ConfigFile *vecConf = pf->createConfigObject("results/vecResult.xml"); ConfigFile *listConf = pf->createConfigObject("results/listResult.xml"); ConfigFile *setConf = pf->createConfigObject("results/setResult.xml"); //create data collectors DataCollector *vecDc = pf->createDataCollector(vecConf); DataCollector *listDc = pf->createDataCollector(listConf); DataCollector *setDc = pf->createDataCollector(setConf); //create a vector, list and set of ints vector<int> intVec; list<int> intList; set<int> intSet; //add operations to fill all three containers vecDc->startSection("push_back"); //measure from here for(int i=0; i<10; i++){ intVec.push_back(i); } vecDc->stopSection(); //stop measuring here listDc->startSection("insert"); //measure list push_back for(int i=0; i<10; i++){ intList.push_back(i); } listDc->stopSection(); setDc->startSection("insert"); //measure set insert for(int i=0; i<10; i++){ intSet.insert(i); } setDc->stopSection(); //search a value in the container vecDc->startSection("find"); //measure find algorithm for vector find(intVec.begin(), intVec.end(), 5); vecDc->stopSection(); listDc->startSection("find"); //measure find algorithm for list find(intList.begin(), intList.end(), 5); listDc->stopSection(); setDc->startSection("find"); //measure find find algorithm for set find(intSet.begin(), intSet.end(), 5); setDc->stopSection(); //erase vecDc->startSection("erase"); //measure erase algorithm for vector intVec.erase(intVec.begin(), intVec.end()); vecDc->stopSection(); listDc->startSection("erase"); //measure erase algorithm for list intList.erase(intList.begin(), intList.end()); listDc->stopSection(); setDc->startSection("erase"); //measure erase algorithm for set intSet.erase(intSet.begin(), intSet.end()); setDc->stopSection(); //insert operatins to refill containers vecDc->startSection("insert"); for(int i=0; i<=100; i++){ intVec.push_back(i); } vecDc->stopSection(); listDc->startSection("insert"); for(int i=0; i<100; i++){ intList.push_back(i); } listDc->stopSection(); setDc->startSection("insert"); for(int i=0; i<100; i++){ intSet.insert(i); } setDc->stopSection(); //modify values via fill algorithm in container int y = 1; vecDc->startSection("fill"); //measure fill algorithm with vector fill(intVec.begin(), intVec.end(), (++y)*2); vecDc->stopSection(); y = 1; listDc->startSection("fill"); //measure fill algorithm with list fill(intVec.begin(), intVec.end(), (++y)*2); listDc->stopSection(); y = 1; setDc->startSection("fill"); //measure fill algorithm with set fill(intVec.begin(), intVec.end(), (++y)*2); setDc->stopSection(); //clear all containers vecDc->startSection("clear"); //measure clear operation with vector intVec.clear(); vecDc->stopSection(); listDc->startSection("clear"); //measure clear operation with list intList.clear(); listDc->stopSection(); setDc->startSection("clear"); //measure clear operation with set intSet.clear(); setDc->stopSection(); return 0; }
void FilenameTest::runTest(const char* filename, const char* fullFilename) { CPPUNIT_ASSERT(!fileExists(fullFilename)); DataCollector::FileCreationAttr attr; DataCollector::initFileCreationAttr(attr); attr.fileAccType = DataCollector::FAT_WRITE; // write first dataset to file (create file) dataCollector->open(filename, attr); int data1 = rand(); dataCollector->write(1, ctInt, 1, Selection(Dimensions(1, 1, 1)), "data", &data1); dataCollector->close(); // Now file must exist CPPUNIT_ASSERT(fileExists(fullFilename)); // write second dataset to file (write to existing file of same name dataCollector->open(filename, attr); int data2 = rand(); dataCollector->write(2, ctInt, 1, Selection(Dimensions(1, 1, 1)), "data", &data2); dataCollector->close(); // read data from file attr.fileAccType = DataCollector::FAT_READ; Dimensions data_size; int data = -1; dataCollector->open(filename, attr); CPPUNIT_ASSERT(dataCollector->getMaxID() == 2); dataCollector->read(1, "data", data_size, &data); CPPUNIT_ASSERT(data_size.getScalarSize() == 1); CPPUNIT_ASSERT(data == data1); dataCollector->read(2, "data", data_size, &data); CPPUNIT_ASSERT(data_size.getScalarSize() == 1); CPPUNIT_ASSERT(data == data2); dataCollector->close(); // erase file attr.fileAccType = DataCollector::FAT_CREATE; dataCollector->open(filename, attr); CPPUNIT_ASSERT_THROW(dataCollector->read(1, "data", data_size, &data), DCException); int data3 = rand(); dataCollector->write(2, ctInt, 1, Selection(Dimensions(1, 1, 1)), "data", &data3); dataCollector->close(); // Read from created file attr.fileAccType = DataCollector::FAT_READ; data = -1; dataCollector->open(filename, attr); CPPUNIT_ASSERT(dataCollector->getMaxID() == 2); dataCollector->read(2, "data", data_size, &data); CPPUNIT_ASSERT(data_size.getScalarSize() == 1); CPPUNIT_ASSERT(data == data3); dataCollector->close(); }
int main(int argc, char** argv) { struct sockaddr_in si_other; int s, slen = sizeof(si_other); char buf[BUFLEN]; char message[BUFLEN]; WSADATA wsa; //Initialise winsock printf("\nInitialising Winsock..."); if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { printf("Failed. Error Code : %d", WSAGetLastError()); exit(EXIT_FAILURE); } printf("Initialised.\n"); //create socket //if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { printf("socket() failed with error code : %d", WSAGetLastError()); exit(EXIT_FAILURE); } char str[INET_ADDRSTRLEN]; //setup address structure memset((char *)&si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); //si_other.sin_addr.S_un.S_addr = inet_pton(AF_INET, SERVER, &(si_other.sin_addr)); inet_pton(AF_INET, SERVER, &(si_other.sin_addr.S_un.S_addr)); /*if (inet_pton(AF_INET, SERVER, &(si_other.sin_addr.S_un.S_addr))) { inet_ntop(AF_INET, &(si_other.sin_addr.S_un.S_addr), str, INET_ADDRSTRLEN); std::cout << ("%s\n", str); }*/ // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("om.example.emg-data-sample"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we enable EMG streaming on the found Myo. myo->setStreamEmg(myo::Myo::streamEmgEnabled); // Create a sample listener and controller for Leap Motion SampleListener listener; Controller controller; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; double timeElasped = 0.000; const double minMax[10] = { 32, 85, 36, 100, 37, 107, 36, 100, 36, 90 }; //T.I.M.R.P // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); //controller.addListener(listener); if (argc > 1 && strcmp(argv[1], "--bg") == 0) controller.setPolicy(Leap::Controller::POLICY_BACKGROUND_FRAMES); myfile << std::fixed; myfile << std::setprecision(2); // Finally we enter our main loop. while (1) { //collector.tic(); // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 50 times a second, so we run for 1000/20 milliseconds. hub.run(1000 / 100); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. collector.print(); int i = 0; int j = 1; int h = 0; double fingDis[5]; const Frame frame = controller.frame(); HandList hands = frame.hands(); for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) { // Get the first hand const Hand hand = *hl; // Get fingers const FingerList fingers = hand.fingers(); for (FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) { const Finger finger = *fl; //myfile << " " << hand.palmPosition().distanceTo(finger.tipPosition()); /*myfile << std::string(4, ' ') << fingerNames[finger.type()] << ": " << listener.mapping(hand.palmPosition().distanceTo(finger.tipPosition()), minMax[i + i], minMax[i + j]);*/ fingDis[h] = listener.mapping(hand.palmPosition().distanceTo(finger.tipPosition()), minMax[i + i], minMax[i + j]); //fingDis[h] = hand.palmPosition().distanceTo(finger.tipPosition()); i++; j++; h++; if (i == 5 && j == 6 && h == 5) { string tmp = to_string(fingDis[0]) + " " + to_string(fingDis[1]) + " " + to_string(fingDis[2]) + " " + to_string(fingDis[3]) + " " + to_string(fingDis[4]); //string tmp = to_string('0'); strcpy_s(message, tmp.c_str()); //send message if (sendto(s, message, strlen(message), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR) { printf("sendto() failed with error code : %d", WSAGetLastError()); //exit(EXIT_FAILURE); } std::cout << "Data Sent"; i = 0; j = 1; h = 0; } } } //timeElasped = timeElasped + ((double)(clock() - tictoc_stack.top())) / CLOCKS_PER_SEC; /*myfile << " Time elapsed: " << ((double)(clock() - tictoc_stack.top())) / CLOCKS_PER_SEC;*/ //tictoc_stack.pop(); //myfile << " " << timeElasped << endl; } // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } closesocket(s); WSACleanup(); }
int main(int argc, char** argv) { // We catch any exceptions that might occur below -- see the catch statement for more details. try { // First, we create a Hub with our application identifier. Be sure not to use the com.example namespace when // publishing your application. The Hub provides access to one or more Myos. myo::Hub hub("com.example.hello-myo"); std::cout << "Attempting to find a Myo..." << std::endl; // Next, we attempt to find a Myo to use. If a Myo is already paired in Myo Connect, this will return that Myo // immediately. // waitForAnyMyo() takes a timeout value in milliseconds. In this case we will try to find a Myo for 10 seconds, and // if that fails, the function will return a null pointer. myo::Myo* myo = hub.waitForMyo(10000); // If waitForAnyMyo() returned a null pointer, we failed to find a Myo, so exit with an error message. if (!myo) { throw std::runtime_error("Unable to find a Myo!"); } // We've found a Myo. std::cout << "Connected to a Myo armband!" << std::endl << std::endl; // Next we construct an instance of our DeviceListener, so that we can register it with the Hub. DataCollector collector; // Hub::addListener() takes the address of any object whose class inherits from DeviceListener, and will cause // Hub::run() to send events to all registered device listeners. hub.addListener(&collector); //CALIBRATE FOR SIMULATED SPATIAL LOCATION //Copy the start position of the calibration gesture during this time. double roll_orient = 0; double yaw_orient = 0; for(int i=0; i<50; i++) { //about 1 second of sampling - keep still! hub.run(1000/20); roll_orient += ROLL; yaw_orient += YAW; } roll_orient /= 50; yaw_orient /= 50; int hand; // start the sound engine with default parameters ISoundEngine* engine = createIrrKlangDevice(); if (!engine) { printf("Could not startup engine\n"); return 0; // error starting up the engine } // play some sound stream, looped ISound *samples[3]; samples[0] = engine->play3D("BeatK03B 70-01.wav", vec3df(0,0,0), true, false, true); samples[1] = engine->play3D("GrulerK03 70B-01.wav", vec3df(0,0,0), true, false, true); samples[2] = engine->play3D("Wind-Mark_DiAngelo-1940285615.wav", vec3df(0,0,0), true, false, true); for(int i = 0; i < 3; i++) { samples[i]->setPosition(vec3df(0,0,1)); } engine->setListenerPosition(vec3df(0,0,0), vec3df(0,0,1)); const float radius = 1; int currentSample = 0; float vol = .5; while(1) { // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds. // In this case, we wish to update our display 20 times a second, so we run for 1000/20 milliseconds. hub.run(1000/20); // After processing events, we call the print() member function we defined above to print out the values we've // obtained from any events that have occurred. // // printf("Press any key to play some sound, press 'q' to quit.\n"); // play a single sound collector.print(); vec3df pos3d(radius * 2*cosf(YAW + yaw_orient - M_PI/2), 0, radius * 2*x`sinf(YAW + yaw_orient - M_PI/2)); (WHICHARM == myo::armLeft ? hand=1 : hand=-1); vol = hand*(-ROLL) + roll_orient + 1; if (vol > 1) vol = 1; if (vol < 0) vol = 0; if (CURRENTPOSE == myo::Pose::fist) { if (samples[currentSample]) { samples[currentSample]->setPosition(pos3d); } } if (CURRENTPOSE == myo::Pose::fingersSpread) { if (samples[currentSample]) { samples[currentSample]->setVolume(vol); } } if (CURRENTPOSE == myo::Pose::waveIn && WAVEINCOUNTER > THRESHOLD) { currentSample += 1; currentSample %= 3; WAVEINCOUNTER = 1; } std::cout << '[' << "Sample: " << currentSample << " Thresh: " << WAVEINCOUNTER << " Vol: " << vol << " roll/yaw orient: " << roll_orient << " " << yaw_orient << "]"; } // If a standard exception occurred, we print out its message and exit. } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Press enter to continue."; std::cin.ignore(); return 1; } }