本文整理汇总了C++中DataCollector类的典型用法代码示例。如果您正苦于以下问题:C++ DataCollector类的具体用法?C++ DataCollector怎么用?C++ DataCollector使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DataCollector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: detectFileMPISize
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;
}
示例2: main
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;
}
}
示例3: main
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;
}
示例4: main
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;
}
}
示例5: main
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;
}
示例6: main
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;
}
示例7: grid_size
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);
}
//.........这里部分代码省略.........
示例8: MPI_CHECK
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());
//.........这里部分代码省略.........
示例9: main
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
//.........这里部分代码省略.........
示例10: main
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;
}
}
示例11: run
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();
}
示例12: main
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;
}
示例13: thCheckRecvData
///@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;
}
示例14: main
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;
}
}
示例15: main
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;
}
}