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 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;
    }
}
示例#3
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();
}
示例#4
0
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;
	}
	
}
示例#5
0
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;
	}
}
示例#6
0
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;
	}
}
示例#7
0
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();
}
示例#8
0
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;
    }
}
示例#9
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;
    }
}