void ofxOscReceiver::setup( int listen_port ) { if(listen_socket) delete listen_socket; listen_socket = new UdpListeningReceiveSocket( IpEndpointName( IpEndpointName::ANY_ADDRESS, listen_port ), this ); #ifdef TARGET_WIN32 thread = CreateThread( NULL, // default security attributes 0, // use default stack size &ofxOscReceiver::startThread, // thread function (void*)(listen_socket), // argument to thread function 0, // use default creation flags NULL); // we don't the the thread id #else pthread_create( &thread, NULL, &ofxOscReceiver::startThread, (void*)(listen_socket) ); #endif }
IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const { assert( isBound_ ); // first connect the socket to the remote server struct sockaddr_in connectSockAddr; SockaddrFromIpEndpointName( connectSockAddr, remoteEndpoint ); if (connect(socket_, (struct sockaddr *)&connectSockAddr, sizeof(connectSockAddr)) < 0) { throw std::runtime_error("unable to connect udp socket\n"); } // get the address struct sockaddr_in sockAddr; memset( (char *)&sockAddr, 0, sizeof(sockAddr ) ); socklen_t length = sizeof(sockAddr); if (getsockname(socket_, (struct sockaddr *)&sockAddr, &length) < 0) { throw std::runtime_error("unable to getsockname\n"); } if( isConnected_ ){ // reconnect to the connected address if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) { throw std::runtime_error("unable to connect udp socket\n"); } }else{ // unconnect from the remote address struct sockaddr_in unconnectSockAddr; SockaddrFromIpEndpointName( unconnectSockAddr, IpEndpointName() ); if( connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr)) < 0 && WSAGetLastError() != WSAEADDRNOTAVAIL ){ throw std::runtime_error("unable to un-connect udp socket\n"); } } return IpEndpointNameFromSockaddr( sockAddr ); }
OscSendingDevice::OscSendingDevice(const std::string& address, int port, unsigned int num_messages_per_event, unsigned int delay_between_sends_in_millisecs) : osgGA::Device() , _transmitSocket(IpEndpointName(address.c_str(), port)) , _buffer(new char[BUFFER_SIZE]) , _oscStream(_buffer, BUFFER_SIZE) , _numMessagesPerEvent(osg::maximum(1u,num_messages_per_event)) , _delayBetweenSendsInMilliSecs( (_numMessagesPerEvent > 1) ? delay_between_sends_in_millisecs : 0) { setCapabilities(SEND_EVENTS); OSG_NOTICE << "OscDevice :: sending events to " << address << ":" << port << " "; #ifdef OSC_HOST_LITTLE_ENDIAN OSG_NOTICE << "(little endian)"; #elif OSC_HOST_BIG_ENDIAN OSG_NOTICE << "(big endian)"; #endif OSG_NOTICE << " (" << _numMessagesPerEvent << "msgs/event, " << _delayBetweenSendsInMilliSecs << "ms delay between msgs)"; OSG_NOTICE << std::endl; }
void SerialOscController::sendDevicePrefixMessage(int port) { String prefix = devicePrefix; if (prefix.startsWith("/")) { prefix = prefix.substring(1); } UdpTransmitSocket transmitSocket( IpEndpointName( SERIALOSC_ADDRESS, port ) ); char buffer[OSC_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OSC_BUFFER_SIZE ); p << osc::BeginBundleImmediate << osc::BeginMessage( "/sys/prefix" ) << prefix.toUTF8() << osc::EndMessage << osc::EndBundle; transmitSocket.Send( p.Data(), p.Size() ); }
static void server( void *args ) { RemoteApplication *_this = (RemoteApplication *)args; _this->m_server.Bind( IpEndpointName(12345) ); _this->m_server.Listen(); while( true ) { std::cout << "listening for client..." << std::endl; _this->m_server.Accept( _this->m_client ); if(_this->m_client.isValid()) { std::cout << "connected to client..." << std::endl; _this->m_isConnected = true; _this->loadOperatorGraph(_this->m_operatorGraph); } else _this->m_isConnected = false; } }
int main(int argc, char* argv[]){ hid_device *handle; unsigned char resbuf[8]; if(argc < 3){ usage(); return 1; } host = argv[1]; port = atoi(argv[2]); printf("Opening ONTRAK device...\n"); handle = hid_open(VENDOR_ID, DEVICE_ID, NULL); hid_set_nonblocking(handle, 0); //blocking mode ftw printf("Device opened and set to blocking mode."); UdpTransmitSocket transmitSocket( IpEndpointName( host, port ) ); while(true){ send_ontrak_command(handle); int res = hid_read(handle, resbuf, 8); if(res <= 0){ printf("ERROR reading\n"); } else{ fprintf(stdout, "."); fflush(stdout); if(++dots > 80){ printf("\n"); dots = 0; } int state = atoi((const char*)resbuf+1); // printf("%d\n", state); if(state != last_state){ last_state = state; send_osc(transmitSocket, state); } } usleep(POLL_SLEEP_MS * 1000); } }
static IpEndpointName IpEndpointNameFromSockaddr( const struct sockaddr_in& sockAddr ) { return IpEndpointName( (sockAddr.sin_addr.s_addr == INADDR_ANY) ? IpEndpointName::ANY_ADDRESS : ntohl( sockAddr.sin_addr.s_addr ), (sockAddr.sin_port == 0) ? IpEndpointName::ANY_PORT : ntohs( sockAddr.sin_port ) ); }
void SerialOscController::sendDeviceLedCommand(int x, int y, bool state) { HashMap<String, MonomeDevice*>::Iterator iter(devices); while (iter.next()) { auto device = iter.getValue(); UdpTransmitSocket transmitSocket( IpEndpointName( SERIALOSC_ADDRESS, device->port ) ); char buffer[OSC_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OSC_BUFFER_SIZE ); String address = (device->prefix + "/grid/led/set"); p << osc::BeginBundleImmediate << osc::BeginMessage( address.toUTF8() ) << x << y << (state ? 1 : 0) << osc::EndMessage << osc::EndBundle; transmitSocket.Send( p.Data(), p.Size() ); } }
void * io_thread (void *arg) { jack_thread_info_t *info = (jack_thread_info_t *) arg; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); pthread_mutex_lock(&io_thread_lock); while (run) { const int pkhld = ceilf(2.0 / ( (info->delay/1000000.0) + ((float)info->buffersize / (float)info->samplerate))); if (info->can_capture) { int chn; memcpy(info->peak, info->pcur, sizeof(float)*info->channels); for (chn = 0; chn < info->channels; ++chn) { info->pcur[chn]=0.0; } if ((info->format&1)==0) { if (flock(fileno(info->outfd), LOCK_EX)) continue; // pthread_cond_wait ? fseek(info->outfd, 0L, SEEK_SET); } switch (info->format&6) { case 6: case 4: fprintf(info->outfd,"{\"cnt\":%d,\"peak\":[", info->channels); break; default: break; } for (chn = 0; chn < info->channels; ++chn) { switch (info->format&6) { case 0: printf("%3.3f ", info->peak[chn]); break; //printf("%s ", info->address); break; case 2: fprintf(info->outfd,"%3d ", peak_db(info->peak[chn], 1.0, info->iecmult)); break; case 4: printf("%.3f,", info->peak[chn]); break; case 6: fprintf(info->outfd,"%d,", peak_db(info->peak[chn], 1.0, info->iecmult)); break; } /* Insert OSC stuff here */ UdpTransmitSocket transmitSocket( IpEndpointName( info->address, info->port ) ); char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream stream( buffer, OUTPUT_BUFFER_SIZE ); stream //<< osc::BeginBundleImmediate << osc::BeginMessage( info->message ) << (float)info->peak[chn] << osc::EndMessage ;//<< osc::EndBundle; transmitSocket.Send( stream.Data(), stream.Size() ); if (info->peak[chn] > info->pmax[chn]) { info->pmax[chn] = info->peak[chn]; info->ptme[chn] = 0; } else if (info->ptme[chn] <= pkhld) { (info->ptme[chn])++; } else { info->pmax[chn] = info->peak[chn]; } } if (info->format&8) { // add peak-hold if (info->format&4) { fprintf(info->outfd,"],\"max\":["); } else { fprintf(info->outfd," | "); } for (chn = 0; chn < info->channels; ++chn) { switch (info->format&6) { case 0: printf("%3.3f ", info->pmax[chn]); break; case 2: fprintf(info->outfd,"%3d ", peak_db(info->pmax[chn], 1.0, info->iecmult)); break; case 4: printf("%.3f,", info->pmax[chn]); break; case 6: fprintf(info->outfd,"%d,", peak_db(info->pmax[chn], 1.0, info->iecmult)); break; } } } switch (info->format&6) { case 6: case 4: fprintf(info->outfd,"]}"); break; default: break; } if (info->format&1) fprintf(info->outfd, "\r"); else { ftruncate(fileno(info->outfd), ftell(info->outfd)); fprintf(info->outfd, "\n"); flock(fileno(info->outfd), LOCK_UN); } fflush(info->outfd); if (info->delay>0) usleep(info->delay); } pthread_cond_wait(&data_ready, &io_thread_lock); } pthread_mutex_unlock(&io_thread_lock); return 0; }
void OscSender::setup(std::string hostname, int port){ if (socket) shutdown(); socket = new UdpTransmitSocket( IpEndpointName(hostname.c_str(), port)); }
oscReceiver::oscReceiver(int port, MessageRetrievalMode retrievalMode_) : socket(IpEndpointName( IpEndpointName::ANY_ADDRESS, port ), this ), isListening(false) , currentMessage(0) , retrievalMode(retrievalMode_) {}
int main(int argc, char * const argv[]) { char *host = (char*)"127.0.0.1"; int port = 3001; int device = -1; // for default device int c; opterr = 0; /* options descriptor */ static struct option longopts[] = { { "help", no_argument , NULL, '?' }, { "list", no_argument , NULL, 'l' }, { "host", required_argument, NULL, 'h' }, { "port", required_argument, &port, 'p' }, { "device", required_argument, &device, 'd' }, { "time-out", required_argument, NULL, 't' }, { "osc-path", required_argument, NULL, 'o' }, { NULL, 0, NULL, 0 } }; while ((c = getopt_long (argc, argv, ":h:p:t:d:l",longopts,NULL)) != -1) switch (c) { case 'h': host = optarg; break; case 'p': port = atoi(optarg); break; case 'd': device = atoi(optarg); break; case 't': timeOut = atoi(optarg)/1000.f; break; case 'o': osc_path = optarg; break; case 'l': listDevices(); return 0; case '?': usage(); return 0; case ':': switch (optopt) { case 'h': case 'p': fprintf (stderr, "Please specify an ip and port to send to.\n"); break; case 't': fprintf (stderr, "Please specify a time out value in milliseconds.\n"); break; case 'd': fprintf (stderr, "-d takes a device index. Use -l to list all available devices.\n"); break; default: if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); break; } return 1; default: usage(); return 1; } // attach signal handlers signal(SIGINT, catch_int); // Set up OSC const int osc_buffer_size = 512; char buffer[osc_buffer_size]; UdpTransmitSocket _sock(IpEndpointName(host,port)); osc::OutboundPacketStream _stream(buffer,osc_buffer_size); OSCSender osc_sender(&_sock,_stream); _sock.SetEnableBroadcast(true); std::clog << "Sending OSC to " << host << " on port " << port << " with path '" << osc_path << "'" << std::endl; std::clog << "Time for repeated detection is set to " << ((int)(timeOut*1000)) << " milliseconds." << std::endl; std::clog << "Samplerate is set to " << SAMPLING_RATE << "Hz" << std::endl; // try to open audio: PaError err; err = Pa_Initialize(); if( err != paNoError ) goto error; DTMFSetup(SAMPLING_RATE, BUFFER_SIZE); deviceInfo = Pa_GetDeviceInfo((device == -1) ? Pa_GetDefaultInputDevice() : device); /* Open an audio I/O stream. */ PaStream *stream; err = Pa_OpenDefaultStream( &stream, 1, 0, paInt16, SAMPLING_RATE, BUFFER_SIZE, audioCallback, &osc_sender ); // send a pointer to the OSCSender with it if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; info = Pa_GetStreamInfo(stream); std::clog << "Audio initialized with:" << std::endl << " Device " << deviceInfo->name << std::endl << " Latency " << info->inputLatency << "ms" << std::endl << " Samplerate " << info->sampleRate << "kHz" << std::endl << " Buffer Size " << BUFFER_SIZE << "samples" << std::endl; std::clog << "Read for detection!" << std::endl; // pause and let the audio thread to the work while(running) pause(); // end program err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; // Close Audio: err = Pa_Terminate(); if( err != paNoError ) { error: std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl; return -1; } return 0; }
void TUIOSender::connectSocket(std::string ip_address, int port) { transmitSocket = new UdpTransmitSocket( IpEndpointName( ip_address.c_str(), port ) ); //printf("Socket Initialized : %s Port : %i\n\n", ip_address.c_str(), port); fseq = 0; }
MyPacketListenerWorker::MyPacketListenerWorker(int port) : QObject(NULL), listener_(this), socket_(IpEndpointName(port), &listener_) { }
void main() { // communication UdpTransmitSocket transmitSocket(IpEndpointName( ADDRESS, PORT )); char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream PacketSender(buffer, OUTPUT_BUFFER_SIZE); // tracking windage::Logger logger(&std::cout); IplImage* inputImage; IplImage* resizeImage = cvCreateImage(cvSize(WIDTH, HEIGHT), IPL_DEPTH_8U, 3); IplImage* grayImage = cvCreateImage(cvSize(WIDTH, HEIGHT), IPL_DEPTH_8U, 1); IplImage* resultImage = cvCreateImage(cvSize(WIDTH, HEIGHT), IPL_DEPTH_8U, 3); CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY); cvNamedWindow("result"); // create and initialize tracker double threshold = 50.0; windage::Frameworks::MultiplePlanarObjectTracking tracking; windage::Calibration* calibration; windage::Algorithms::FeatureDetector* detector; windage::Algorithms::OpticalFlow* opticalflow; windage::Algorithms::HomographyEstimator* estimator; windage::Algorithms::OutlierChecker* checker; windage::Algorithms::HomographyRefiner* refiner; calibration = new windage::Calibration(); detector = new windage::Algorithms::SIFTGPUdetector(); opticalflow = new windage::Algorithms::OpticalFlow(); estimator = new windage::Algorithms::ProSACestimator(); checker = new windage::Algorithms::OutlierChecker(); refiner = new windage::Algorithms::LMmethod(); calibration->Initialize(INTRINSIC[0], INTRINSIC[1], INTRINSIC[2], INTRINSIC[3], INTRINSIC[4], INTRINSIC[5], INTRINSIC[6], INTRINSIC[7]); detector->SetThreshold(50.0); opticalflow->Initialize(WIDTH, HEIGHT, cvSize(15, 15), 3); estimator->SetReprojectionError(REPROJECTION_ERROR); checker->SetReprojectionError(REPROJECTION_ERROR * 3); refiner->SetMaxIteration(10); tracking.AttatchCalibration(calibration); tracking.AttatchDetetor(detector); tracking.AttatchTracker(opticalflow); tracking.AttatchEstimator(estimator); tracking.AttatchChecker(checker); tracking.AttatchRefiner(refiner); tracking.Initialize(WIDTH, HEIGHT, (double)WIDTH, (double)HEIGHT); tracking.SetFilter(false); tracking.SetDitectionRatio(5); bool trained = false; #if USE_TEMPLATE_IMAEG for(int i=0; i<TEMPLATE_IMAGE_COUNT; i++) { char message[100]; sprintf_s(message, TEMPLATE_IMAGE, i+1); IplImage* sampleImage = cvLoadImage(message, 0); detector->SetThreshold(30.0); tracking.AttatchReferenceImage(sampleImage); cvReleaseImage(&sampleImage); } tracking.TrainingReference(SCALE_FACTOR, SCALE_STEP); trained = true; detector->SetThreshold(threshold); #endif int keypointCount = 0; int matchingCount = 0; double processingTime = 0.0; char message[100]; bool fliping = true; bool processing = true; while(processing) { // capture image inputImage = cvRetrieveFrame(capture); cvResize(inputImage, resizeImage); if(fliping) cvFlip(resizeImage, resizeImage); cvCvtColor(resizeImage, grayImage, CV_BGR2GRAY); cvCopyImage(resizeImage, resultImage); logger.updateTickCount(); // track object if(trained) { tracking.UpdateCamerapose(grayImage); // tracking.GetDetector()->DrawKeypoints(resultImage); // adaptive threshold #if ADAPTIVE_THRESHOLD int localcount = detector->GetKeypointsCount(); if(keypointCount != localcount) { if(localcount > FEATURE_COUNT) threshold += 1; if(localcount < FEATURE_COUNT) threshold -= 1; detector->SetThreshold(threshold); keypointCount = localcount; } #endif // draw result std::vector<int> matchingCount; matchingCount.resize(tracking.GetObjectCount()); for(int i=0; i<tracking.GetObjectCount(); i++) { matchingCount[i] = tracking.GetMatchingCount(i); if(tracking.GetMatchingCount(i) > 10) { // tracking.DrawDebugInfo(resultImage, i); tracking.DrawOutLine(resultImage, i, true); windage::Calibration* calibrationTemp = tracking.GetCameraParameter(i); calibrationTemp->DrawInfomation(resultImage, 100); CvPoint centerPoint = calibrationTemp->ConvertWorld2Image(0.0, 0.0, 0.0); centerPoint.x += 5; centerPoint.y += 10; sprintf_s(message, "object #%d (%03d)", i+1, matchingCount[i]); windage::Utils::DrawTextToImage(resultImage, centerPoint, 0.6, message); } } // calcuate relation if(tracking.GetMatchingCount(0) > 10 && tracking.GetMatchingCount(1) > 10) { windage::Matrix3 rotation = windage::Coordinator::MultiMarkerCoordinator::GetRotation(tracking.GetCameraParameter(0), tracking.GetCameraParameter(1)); windage::Vector3 translation = windage::Coordinator::MultiMarkerCoordinator::GetTranslation(tracking.GetCameraParameter(0), tracking.GetCameraParameter(1)); PacketSender << osc::BeginBundleImmediate << osc::BeginMessage("MultimarkerRelation") << rotation.m[0][0] << rotation.m[0][1] << rotation.m[0][2] << rotation.m[1][0] << rotation.m[1][1] << rotation.m[1][2] << rotation.m[2][0] << rotation.m[2][1] << rotation.m[2][2] << translation.x << translation.y << translation.z << osc::EndMessage << osc::EndBundle; transmitSocket.Send( PacketSender.Data(), PacketSender.Size() ); PacketSender.Clear(); } } processingTime = logger.calculateProcessTime(); logger.log("processingTime", processingTime); logger.logNewLine(); sprintf_s(message, "Processing Time : %.2lf ms", processingTime); windage::Utils::DrawTextToImage(resultImage, cvPoint(10, 20), 0.6, message); sprintf_s(message, "Feature Count : %d, Threshold : %.0lf", keypointCount, threshold); windage::Utils::DrawTextToImage(resultImage, cvPoint(10, 40), 0.6, message); sprintf_s(message, "Matching Count : %d", matchingCount); windage::Utils::DrawTextToImage(resultImage, cvPoint(10, 60), 0.6, message); sprintf_s(message, "Press 'Space' to add tracking the current image", keypointCount, threshold); windage::Utils::DrawTextToImage(resultImage, cvPoint(WIDTH-315, HEIGHT-10), 0.5, message); cvShowImage("result", resultImage); char ch = cvWaitKey(1); switch(ch) { case 'q': case 'Q': processing = false; break; case 'f': case 'F': fliping = !fliping; break; case ' ': case 's': case 'S': detector->SetThreshold(30.0); tracking.AttatchReferenceImage(grayImage); tracking.TrainingReference(SCALE_FACTOR, SCALE_STEP); detector->SetThreshold(threshold); trained = true; break; } } cvReleaseCapture(&capture); cvDestroyAllWindows(); }
oscReceiver::oscReceiver(int port, std::string multicast_IP, MessageRetrievalMode retrievalMode_) : socket(IpEndpointName(multicast_IP.c_str(), port), this), isListening(false) , currentMessage(0) , retrievalMode(retrievalMode_) {}
QOSCReceiver::QOSCReceiver(unsigned int localPortUI, QObject *parent): QThread(parent), _localPortUI(localPortUI), _socket( new UdpListeningReceiveSocket(IpEndpointName( IpEndpointName::ANY_ADDRESS, localPortUI ), this)) { }
int MLOSCListener::listenToOSC(int port) { int ret = false; if(port) { if(mpSocket) { listenToOSC(0); } try { std::cout << "MLOSCListener: trying listen on port " << port << "...\n"; mpSocket = new UdpListeningReceiveSocket( IpEndpointName( IpEndpointName::ANY_ADDRESS, port), this); } catch( osc::Exception& e ) { mpSocket = 0; std::cout << "MLOSCListener::listenToOSC: couldn't bind to port " << port << ".\n"; std::cout << "error: " << e.what() << "\n"; } catch(...) { mpSocket = 0; std::cout << "MLOSCListener::listenToOSC: couldn't bind to port " << port << ".\n"; std::cout << "Unknown error.\n"; } if(mpSocket) { std::cout << "MLOSCListener::listenToOSC: created receive socket on port " << port << ".\n"; mPort = port; int err; pthread_attr_t attr; // std::cout << "initializing pthread attributes...\n"; err = pthread_attr_init(&attr); if(!err) { // std::cout << "creating listener thread...\n"; err = pthread_create(&mListenerThread, &attr, &MLOSCListenerStartThread, (void*)this); if(!err) { ret = true; mListening = true; } } } } else { if(mpSocket) { std::cout << "MLOSCListener: disconnecting.\n"; mpSocket->Break(); delete mpSocket; mpSocket = 0; } mListening = false; ret = true; } return ret; }
Compositor::Compositor(std::string synthesisIP,int portnum,bool dbg): debug(dbg){ synthServSocket=new UdpTransmitSocket( IpEndpointName(synthesisIP.c_str(), portnum) ); OUTPUT_BUFFER_SIZE=1024; }
MOboolean moNetOSCIn::Init() { int dev; MOuint i, n, n_dev, n_hosts; moText conf, dev_name; //========================== // CORRESPONDE A UN PREINIT //========================== // Loading config file. conf = m_pResourceManager->GetDataMan()->GetDataPath() + moSlash; conf += GetConfigName(); conf += moText(".cfg"); if (m_Config.LoadConfig(conf) != MO_CONFIG_OK ) { moText text = "Couldn't load netoscin config"; MODebug->Push(text); return false; } //========================== // INIT //========================== moDefineParamIndex( NETOSCIN_INLET, moText("inlet") ); moDefineParamIndex( NETOSCIN_OUTLET, moText("outlet") ); moDefineParamIndex( NETOSCIN_HOSTS , moText("hosts") ); moDefineParamIndex( NETOSCIN_PORT , moText("port") ); moDefineParamIndex( NETOSCIN_RECEIVEEVENTS, moText("receive_events") ); bool events_present; bool trackersystem_present; events_present = false; trackersystem_present = false; for( int i=0; i<m_Config.GetParam( moR(NETOSCIN_OUTLET) ).GetValuesCount(); i++) { moValue val( m_Config.GetParam( moR(NETOSCIN_OUTLET) ).GetValue(i)); if ( val.GetSubValue().Text()==moText("EVENTS")) { events_present = true; } if ( val.GetSubValue().Text()==moText("TRACKERSYSTEM")) { trackersystem_present = true; } } if (!events_present) { m_Config.GetParam( moR(NETOSCIN_OUTLET) ).AddValue( moValue( "EVENTS", "TXT", "DATA", "TXT" ).Ref() ); } if (!trackersystem_present) { m_Config.GetParam( moR(NETOSCIN_OUTLET) ).AddValue( moValue( "EVENTS", "TXT", "DATA", "TXT" ).Ref() ); } moMoldeoObject::Init(); for(int a=0; a <GetOutlets()->Count(); a++) { if ( m_Outlets[a]->GetConnectorLabelName() == moText("EVENTS") ) { m_pEvents = m_Outlets[a]; } } // Reading hosts names and ports. n = m_Config.GetParamIndex("hosts"); n_hosts = m_Config.GetValuesCount(n); host_name.Init(n_hosts, moText("")); host_port.Init(n_hosts, 0); for(i = 0; i < n_hosts; i++) { host_name.Set(i, m_Config.GetParam(n).GetValue(i).GetSubValue(0).Text()); host_port.Set(i, m_Config.GetParam(n).GetValue(i).GetSubValue(1).Int()); } for(i = 0; i < n_hosts; i++) { moOscPacketListener* pListener = NULL; pListener = new moOscPacketListener(); if (pListener) { /* if ( host_name[i] == moText("all") ) { if (host_port[i]>0) pListener->Set( new UdpListeningReceiveSocket( IpEndpointName( IpEndpointName::ANY_ADDRESS, host_port[i] ), pListener ) ); else pListener->Set( new UdpListeningReceiveSocket( IpEndpointName( IpEndpointName::ANY_ADDRESS, IpEndpointName::ANY_PORT ), pListener ) ); } else if ( host_name[i] != moText("") ) { moTextArray ipNumbers; unsigned long ipaddress = 0; unsigned long i1=0, i2=0, i3=0, i4=0; ipNumbers = host_name[i].Explode("."); if (ipNumbers.Count()==4) { i1 = atoi(ipNumbers[0]); i2 = atoi(ipNumbers[1]); i3 = atoi(ipNumbers[2]); i4 = atoi(ipNumbers[3]); ipaddress = (i1 << 24) & (i2<<16) & (i3<<8) & i4; } else { ipaddress = IpEndpointName::ANY_ADDRESS; } if (host_port[i]>0) pListener->Set( new UdpListeningReceiveSocket( IpEndpointName( ipaddress, host_port[i] ), pListener ) ); else pListener->Set( new UdpListeningReceiveSocket( IpEndpointName( ipaddress, IpEndpointName::ANY_PORT ), pListener ) ); } else { pListener->Set( new UdpListeningReceiveSocket( IpEndpointName( IpEndpointName::ANY_ADDRESS, IpEndpointName::ANY_PORT ), pListener ) ); } */ UdpListeningReceiveSocket *socket = NULL; try { socket = new UdpListeningReceiveSocket( IpEndpointName( IpEndpointName::ANY_ADDRESS, host_port[i] ), pListener ); } catch (std::exception &e) { MODebug2->Error(moText("could not bind to UDP port ")); socket = NULL; } if (socket!=NULL) { if (!socket->IsBound()) { delete socket; socket = NULL; MODebug2->Error( moText("NETOSCIN UDP socket not connected:") + + (moText)host_name[i] + moText(" PORT:") + IntToStr(host_port[i]) ); } else { MODebug2->Message( moText("NetOSCIn listening to OSC messages on UDP port ")); pListener->Set(socket); } } if (socket) { m_OscPacketListeners.Add( pListener ); if (pListener->CreateThread()) { MODebug2->Message( moText(" NETOSCIN OK: HOST NAME:") + (moText)host_name[i] + moText(" PORT:") + IntToStr(host_port[i]) ); } else { MODebug2->Error( moText("NETOSCIN:") + + (moText)host_name[i] + moText(" PORT:") + IntToStr(host_port[i]) ); } } } } return true; }
int main(int argc, char* argv[]) { if(argc < 2){ ADDRESS = "localhost"; }else{ std::string line = argv[1]; int colon_pos = line.find(":"); if(colon_pos != std::string::npos){ ADDRESS = line.substr(0, colon_pos); PORT = std::stoi(line.substr(colon_pos + 1, std::string::npos)); }else{ ADDRESS = line; } } std::cout << ADDRESS << std::endl; std::cout << PORT << std::endl; //start ros thread XInitThreads(); std::thread ros_thread(ros_stuff); //Initialize OSC stuff UdpTransmitSocket transmit_socket( IpEndpointName( ADDRESS.c_str(), PORT ) ); listener = new LRPacketListener(); //listener->registerStringCallback(nothing); listener->registerTransportCallback(sync); listener->registerPlaybackCallback(playbackChanged); listener->registerClipUpdateCallback(loadClip); receive_socket = new UdpListeningReceiveSocket(IpEndpointName( IpEndpointName::ANY_ADDRESS, PORT ), listener); //Set up threads std::thread listen_thread(listen); //interupt quits signal(SIGINT, [](int signum){std::cout << "okay" << std::endl; quit = true; receive_socket->Break(); receive_socket->AsynchronousBreak();}); //conductor listener->registerTransportCallback(update_baton); //SFML sf::Font font; if (!font.loadFromFile("Ubuntu-R.ttf")) { std::cout << "where's the font?" << std::endl; } play_shape.rotate(90); play_shape.setPosition(700, 10); play_shape.setFillColor(sf::Color::Green); stop_shape.setPosition(700, 10); stop_shape.setFillColor(sf::Color::Red); for(int i = 0; i < 50; i++){ sf::CircleShape baton(8, 20); sf::Color color(255, i*255/50, 0, 51*(i-50)*(i-50)/500); baton.setFillColor(color); baton.setPosition(400, 300); baton_trail.push_back(baton); } // select the font transport_text.setFont(font); // font is a sf::Font time_text.setFont(font); offset_text.setFont(font); debug_text.setFont(font); transport_text.setCharacterSize(24); // in pixels, not points! time_text.setCharacterSize(24); offset_text.setCharacterSize(24); debug_text.setCharacterSize(24); transport_text.setColor(sf::Color::White); time_text.setColor(sf::Color::White); offset_text.setColor(sf::Color::White); debug_text.setColor(sf::Color::White); transport_text.setPosition(10, 10); time_text.setPosition(10, 40); offset_text.setPosition(10, 70); debug_text.setPosition(400, 70); // set the string to display transport_text.setString("Hello world"); time_text.setString("waiting..."); offset_text.setString("no offset"); //sfml window sf::ContextSettings settings; settings.antialiasingLevel = 8; sf::RenderWindow window(sf::VideoMode(800, 600), "Terpsichore", sf::Style::Default, settings); window.setVerticalSyncEnabled(true); //request initial information send("/terpsichore", (int)1, transmit_socket); // run the program as long as the window is open while (window.isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { // "close requested" event: we close the window if (event.type == sf::Event::Closed){ window.close(); quit = true; receive_socket->Break(); receive_socket->AsynchronousBreak(); } } // clear the window with black color window.clear(sf::Color::Black); // draw everything here... // draw the notes of the currently playing clips double y = 100.0; double scale = 50.0; for(std::map<int, Clip*>::iterator clip_it = listener->clips.begin(); clip_it != listener->clips.end(); clip_it++){ Clip* c = clip_it->second; for(std::multimap<Position, Note>::iterator note_it = c->notes.begin(); note_it != c->notes.end(); note_it++){ Position p = note_it->first; Note n = note_it->second; double x = p.toFloat(listener->transport.timeSignature) * scale + 10; double w = n.duration * scale; double h = n.pitch; sf::RectangleShape noteRect(sf::Vector2f(w, h)); noteRect.setFillColor(sf::Color::Blue); noteRect.setOutlineThickness(2); noteRect.setOutlineColor(sf::Color::Cyan); noteRect.setPosition(x, y); window.draw(noteRect); } y += 80; debug_text.setString(std::to_string(y)); } // window.draw(...); transport_text.setString(transport_string); time_text.setString(time_string); window.draw(time_text); offset_text.setString(offset_string); window.draw(offset_text); window.draw(debug_text); if(playing){ window.draw(play_shape); }else{ window.draw(stop_shape); } //draw the baton point; for(int i = baton_trail.size() - 1; i >= 0; i--){ window.draw(baton_trail.at(i)); } window.draw(transport_text); // end the current frame window.display(); } //stopping threads std::cout << "attempting to join\n"; listen_thread.join(); ros_thread.join(); delete receive_socket; delete listener; return 0; }
// Set IP and Port with commandline parameters void OSCApp::connectSocket(std::string ip_address, int port) { transmitSocket = new UdpTransmitSocket(IpEndpointName(ip_address.c_str(), port)); printf("Socket Initialized : %s Port : %i\n\n", ip_address.c_str(), port); frameSeq = 0; }
int main(int argc, char* argv[]) { signal(SIGINT, sigproc); #ifndef WIN32 signal(SIGQUIT, sigproc); #endif UdpTransmitSocket transmitSocket( IpEndpointName( ADDRESS, PORT ) ); char buffer[OUTPUT_BUFFER_SIZE]; FILE *input; FILE *output; enum headset_type type; char raw_frame[32]; struct epoc_frame frame; epoc_device* d; uint8_t data[32]; if (argc < 2) { fputs("Missing argument\nExpected: epocd [consumer|research|special]\n", stderr); return 1; } if(strcmp(argv[1], "research") == 0) type = RESEARCH_HEADSET; else if(strcmp(argv[1], "consumer") == 0) type = CONSUMER_HEADSET; else if(strcmp(argv[1], "special") == 0) type = SPECIAL_HEADSET; else { fputs("Bad headset type argument\nExpected: epocd [consumer|research|special] source [dest]\n", stderr); return 1; } epoc_init(type); d = epoc_create(); printf("Current epoc devices connected: %d\n", epoc_get_count(d, EPOC_VID, EPOC_PID)); if(epoc_open(d, EPOC_VID, EPOC_PID, 0) != 0) { printf("CANNOT CONNECT\n"); return 1; } while(1) { if(epoc_read_data(d, data) > 0) { epoc_get_next_frame(&frame, data); osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); p << osc::BeginBundleImmediate << osc::BeginMessage( "/epoc/channels" ) << frame.F3 << frame.FC6 << frame.P7 << frame.T8 << frame.F7 << frame.F8 << frame.T7 << frame.P8 << frame.AF4 << frame.F4 << frame.AF3 << frame.O2 << frame.O1 << frame.FC5 << osc::EndMessage << osc::BeginMessage( "/epoc/gyro" ) << frame.gyroX << frame.gyroY << osc::EndMessage << osc::EndBundle; transmitSocket.Send( p.Data(), p.Size() ); } } epoc_close(d); epoc_delete(d); return 0; }
int main(int argc, char* argv[]) { signal(SIGINT, sigproc); #ifndef WIN32 signal(SIGQUIT, sigproc); #endif bool noHelmet = false; if((argc > 1) && (argv[1] == std::string("-n"))) noHelmet = true; UdpTransmitSocket transmitSocket( IpEndpointName( ADDRESS, PORT ) ); char buffer[OUTPUT_BUFFER_SIZE]; emokit_device* d; d = emokit_create(); printf("Current epoc devices connected: %d\n", emokit_get_count(d, EMOKIT_VID, EMOKIT_PID)); if(emokit_open(d, EMOKIT_VID, EMOKIT_PID, 0) != 0 && !noHelmet) { printf("CANNOT CONNECT\n"); return 1; } else if(noHelmet) { std::cout << "Sending random data" << std::endl; } if (!noHelmet) { while(true) { if(emokit_read_data(d) > 0) { emokit_get_next_frame(d); struct emokit_frame frame = d->current_frame; std::cout << "\r\33[2K" << "gyroX: " << (int)frame.gyroX << "; gyroY: " << (int)frame.gyroY << "; F3: " << frame.F3 << "; FC6: " << frame.FC6 << "; battery: " << (int)d->battery << "%"; flush(std::cout); osc::OutboundPacketStream channels( buffer, OUTPUT_BUFFER_SIZE ); osc::OutboundPacketStream gyro( buffer, OUTPUT_BUFFER_SIZE ); osc::OutboundPacketStream info( buffer, OUTPUT_BUFFER_SIZE ); channels << osc::BeginMessage( "/emokit/channels" ) << frame.F3 << frame.FC6 << frame.P7 << frame.T8 << frame.F7 << frame.F8 << frame.T7 << frame.P8 << frame.AF4 << frame.F4 << frame.AF3 << frame.O2 << frame.O1 << frame.FC5 << osc::EndMessage; transmitSocket.Send( channels.Data(), channels.Size() ); gyro << osc::BeginMessage( "/emokit/gyro" ) << (int)frame.gyroX << (int)frame.gyroY << osc::EndMessage; transmitSocket.Send( gyro.Data(), gyro.Size() ); info << osc::BeginMessage( "/emokit/info" ) << (int)d->battery; for (int i = 0; i<14 ; i++) info << (int)d->contact_quality[i]; info << osc::EndMessage; transmitSocket.Send( info.Data(), info.Size() ); } } } else { while (true) { usleep(FREQ); osc::OutboundPacketStream channels( buffer, OUTPUT_BUFFER_SIZE ); osc::OutboundPacketStream gyro( buffer, OUTPUT_BUFFER_SIZE ); osc::OutboundPacketStream info( buffer, OUTPUT_BUFFER_SIZE ); channels << osc::BeginMessage( "/emokit/channels" ); for (int i=0 ; i < 14 ; i++) channels << rand() % 10000; channels << osc::EndMessage; transmitSocket.Send( channels.Data(), channels.Size() ); gyro << osc::BeginMessage( "/emokit/gyro" ) << rand() % 100 << rand() % 100 << osc::EndMessage; transmitSocket.Send( gyro.Data(), gyro.Size() ); info << osc::BeginMessage( "/emokit/info" ) << rand() % 100; for (int i = 0; i<14 ; i++) info << rand() % 50; info << osc::EndMessage; transmitSocket.Send( info.Data(), info.Size() ); } } emokit_close(d); emokit_delete(d); return 0; }
void ofxOscSender::setup( std::string hostname, int port ) { socket = new UdpTransmitSocket( IpEndpointName( hostname.c_str(), port ) ); }
#include <iostream> #include <cstring> #define OSC_OUTPUT_ENABLED 0 #if OSC_OUTPUT_ENABLED #include "ip/IpEndpointName.h" #include "ip/IpEndpointName.cpp" #include "ip/UdpSocket.h" #include "ip/posix/UdpSocket.cpp" #include "ip/posix/NetworkingUtils.cpp" #include "osc/OscOutboundPacketStream.h" #include "osc/OscOutboundPacketStream.cpp" #include "osc/OscTypes.cpp" UdpTransmitSocket oscSocket(IpEndpointName("127.0.0.1", 7000)); char oscBuffer[1024]; osc::OutboundPacketStream oscStream(oscBuffer, 1024); #endif std::vector<FixtureTile*> strips; std::vector<PowerSupply*> supplies; #define BEGIN_POWER_NODE(ip, stripLength, startAddress, direction) { \ PowerSupply* pSupply = new PowerSupply(ip); \ supplies.push_back(pSupply); \ int start = startAddress; \ bool dir = direction; \ int length = stripLength; \ std::cout << "Created power supply " << ip << "\n";
OSCSender::OSCSender(QObject *parent) : QObject(parent), ip_("127.0.0.1"), port_(3333), socket_(IpEndpointName(ip_.c_str(), port_)) { }
int main(int argc, char* argv[]) { (void) argc; // suppress unused parameter warnings (void) argv; // suppress unused parameter warnings struct sockaddr_in myaddr; /* our address */ struct sockaddr_in remaddr; /* remote address */ socklen_t addrlen = sizeof(remaddr); /* length of addresses */ int recvlen; /* # bytes received */ int fd; /* our socket */ unsigned char buf[BUFFER_SIZE]; /* receive buffer */ /* create a UDP socket */ if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("cannot create socket\n"); return 0; } UdpTransmitSocket transmitSocket( IpEndpointName( SEND_ADDRESS, SEND_PORT ) ); // The buffer out char buffer[BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, BUFFER_SIZE ); /* bind the socket to any valid IP address and a specific port */ memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(RECEIVE_PORT); if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); return 0; } else{ printf("Listening to port %d\n", RECEIVE_PORT); } /* now loop, receiving data and printing what we received */ for (;;) { recvlen = recvfrom(fd, buf, BUFFER_SIZE, 0, (struct sockaddr *)&remaddr, &addrlen); if (recvlen > 0) { buf[recvlen] = 0; // retrieving the data from the udp message std::string inMessage( buf, buf + sizeof buf / sizeof buf[0] ); // converting the input buffer to a string // counting the number of semicolons to detect the number of messages in the packet int nParams = std::count(inMessage.begin(), inMessage.end(), ';')-2; for(int i=0; i<nParams; i++){ std::string oscAddress = OSC_BASE_ADDRESS; oscAddress.append(inMessage.substr(0,inMessage.find(":"))); std::string oscValueString = inMessage.substr(inMessage.find(":")+1,inMessage.find(";")-inMessage.find(":")-1); // making sure that the received message is valid if(!std::all_of(oscValueString.begin(), oscValueString.end(), ::isdigit)){ float oscValue = stof(oscValueString); //printf("Rec: %s: ",oscAddress.c_str()); //printf("%f\n", oscValue); inMessage = inMessage.substr(inMessage.find("\n")+1,inMessage.find(";;")-inMessage.find("\n")); // formating and sending the OSC message p.Clear(); p << osc::BeginMessage(oscAddress.c_str()) << oscValue << osc::EndMessage; transmitSocket.Send( p.Data(), p.Size() ); } else printf("Dropped message\n"); } } } /* never exits */ }
int _tmain(int argc, _TCHAR* argv[]) { splash(argv[0]); if((argc < 4) || ((argc > 5) && (strcmp("log", argv[5])))){ printf("Usage: %s <ServerIP> <ClientIP> <OSCIP> <OSCPort> [\"log\"]", argv[0]); }else{ int retCode; char* OSCIP = argv[3]; int OSCPort = atoi(argv[4]); //EU printf("\n\nBanana hammock!!\n\n"); // Set callback handlers theClient.SetMessageCallback(MessageHandler); theClient.SetVerbosityLevel(Verbosity_Debug); theClient.SetDataCallback( DataHandler, &theClient ); // this function will receive data from the server // Connect to NatNet server strcpy(szServerIPAddress, argv[1]); // specified on command line strcpy(szMyIPAddress, argv[2]); // specified on command line printf("Connecting to server at %s from %s...\n", szServerIPAddress, szMyIPAddress); // Connect to NatNet server retCode = theClient.Initialize(szMyIPAddress, szServerIPAddress); if (retCode != ErrorCode_OK) { printf("Unable to connect to server. Error code: %d. Exiting", retCode); return 1; } else { // print server info sServerDescription ServerDescription; memset(&ServerDescription, 0, sizeof(ServerDescription)); theClient.GetServerDescription(&ServerDescription); if(!ServerDescription.HostPresent) { printf("Unable to connect to server. Host not present. Exiting."); return 1; } printf("[OSCNatNetClient] Server application info:\n"); printf("Application: %s (ver. %d.%d.%d.%d)\n", ServerDescription.szHostApp, ServerDescription.HostAppVersion[0], ServerDescription.HostAppVersion[1], ServerDescription.HostAppVersion[2], ServerDescription.HostAppVersion[3]); printf("NatNet Version: %d.%d.%d.%d\n", ServerDescription.NatNetVersion[0], ServerDescription.NatNetVersion[1], ServerDescription.NatNetVersion[2], ServerDescription.NatNetVersion[3]); printf("Server IP:%s\n", szServerIPAddress); printf("Server Name:%s\n\n", ServerDescription.szHostComputerName); //EU - init UDP socket transmitSocket = new UdpTransmitSocket(IpEndpointName(OSCIP, OSCPort)); printf("OSC IP:%s\n", OSCIP); printf("OSC Port:%d\n", OSCPort); } // send/receive test request printf("[OSCNatNetClient] Sending Test Request\n"); void* response; int nBytes; retCode = theClient.SendMessageAndWait("TestRequest", &response, &nBytes); if (retCode == ErrorCode_OK) { printf("[OSCNatNetClient] Received: %s", (char*)response); } //Writing Session data to file char szFile[MAX_PATH]; char szFolder[MAX_PATH]; #ifdef __linux__ sprintf(szFolder, "./"); #else GetCurrentDirectory(MAX_PATH, szFolder); #endif char timeLabel[50]; time_t rawtime; struct tm* timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); //create time label for files strftime (timeLabel,80,"%d.%m.%y %H.%M.%S",timeinfo); // Retrieve MarkerSets from server printf("\n\n[OSCNatNetClient] Requesting all data definitions for current session..."); sDataDescriptions* pDataDefs = NULL; theClient.GetDataDescriptions(&pDataDefs); if(!pDataDefs){ printf("[OSCNatNetClient] Unable to retrieve current session."); //return 1; }else{ sprintf(szFile, "%s\\SessionData %s.txt", szFolder, timeLabel); fps = fopen(szFile, "w"); if(!fps) { printf("error opening output file %s. Exiting.", szFile); exit(1); } _WriteHeader(fps, pDataDefs); fclose(fps); } // Prepare data file for frame info if(argc > 5){ sprintf(szFile, "%s\\FrameData %s.txt", szFolder, timeLabel); fpf = fopen(szFile, "w"); if(!fpf){ printf("error opening output file %s. Exiting.", szFile); exit(1); } } // Ready to receive marker stream! printf("\nOSCNatNetClient is connected to server and listening for data... press 'q' for quitting\n"); int c; bool bExit = false; while(c =_getch()){ switch(c){ case 'q': bExit = true; printf("\nQuitting...\n\n"); break; case 'r': printf("\nReseting Client...\n\n"); resetClient(); break; default: printf("not an option\n\n"); break; } if(bExit) break; } printf("clean up\n\n"); // Done - clean up. theClient.Uninitialize(); if(fpf != NULL) fclose(fpf); return ErrorCode_OK; } }
//============================================================================== void MiditoOscAudioProcessor::setOSCConnection (const juce::String address, const uint16_t port) { transmitSocket.Connect( IpEndpointName(address.getCharPointer(), port) ); }