int main(int argc, const char *argv[]) { if(argc < 2) { return -1; } unsigned int ports = midi.getPortCount(); if(ports < 1) { return -1; } // I'm not sure what port 0 is, but ports 1 and 2 seem to work midi.openPort(1); lua_State* L = luaL_newstate(); luaL_openlibs(L); lua_pushcfunction(L, midi_send); lua_setglobal(L, "midi_send"); luaL_dofile(L, argv[1]); lua_close(L); return 0; }
FREObject openOutputDevice(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) { int index = 0; FREGetObjectAsInt32(argv[0],&index); //printf("Native MIDI :: open output device %i\n",index); int pointer = -1; try { RtMidiOut* out = new RtMidiOut(); out->openPort(index); openMidiOut.push_back(out); pointer = (int)out; //printf("Open midi pointer : %i\n",pointer); // Don't ignore sysex, timing, or active sensing messages. } catch ( RtMidiError &error ) { error.printMessage(); } FREObject result; FRENewObjectFromInt32(pointer,&result); return result; }
int main() { // Create an api map. std::map<int, std::string> apiMap; apiMap[RtMidi::MACOSX_CORE] = "OS-X CoreMidi"; apiMap[RtMidi::WINDOWS_MM] = "Windows MultiMedia"; apiMap[RtMidi::UNIX_JACK] = "Jack Client"; apiMap[RtMidi::LINUX_ALSA] = "Linux ALSA"; apiMap[RtMidi::RTMIDI_DUMMY] = "RtMidi Dummy"; std::vector< RtMidi::Api > apis; RtMidi :: getCompiledApi( apis ); std::cout << "\nCompiled APIs:\n"; for ( unsigned int i=0; i<apis.size(); i++ ) std::cout << " " << apiMap[ apis[i] ] << std::endl; RtMidiIn *midiin = 0; RtMidiOut *midiout = 0; try { // RtMidiIn constructor ... exception possible midiin = new RtMidiIn(); std::cout << "\nCurrent input API: " << apiMap[ midiin->getCurrentApi() ] << std::endl; // Check inputs. unsigned int nPorts = midiin->getPortCount(); std::cout << "\nThere are " << nPorts << " MIDI input sources available.\n"; for ( unsigned i=0; i<nPorts; i++ ) { std::string portName = midiin->getPortName(i); std::cout << " Input Port #" << i+1 << ": " << portName << '\n'; } // RtMidiOut constructor ... exception possible midiout = new RtMidiOut(); std::cout << "\nCurrent output API: " << apiMap[ midiout->getCurrentApi() ] << std::endl; // Check outputs. nPorts = midiout->getPortCount(); std::cout << "\nThere are " << nPorts << " MIDI output ports available.\n"; for ( unsigned i=0; i<nPorts; i++ ) { std::string portName = midiout->getPortName(i); std::cout << " Output Port #" << i+1 << ": " << portName << std::endl; } std::cout << std::endl; } catch ( RtMidiError &error ) { error.printMessage(); } delete midiin; delete midiout; return 0; }
int rtmidi_out_send_message (RtMidiOutPtr device, const unsigned char *message, int length) { #if defined(__NO_EXCEPTIONS__) RtMidiOut* rtm = (RtMidiOut*) device->ptr; rtm->resetError(); rtm->sendMessage (message, length); if (rtm->isError()) { device->ok = false; device->msg = rtm->getError().what (); return -1; } return 0; #else try { ((RtMidiOut*) device->ptr)->sendMessage (message, length); return 0; } catch (const RtMidiError & err) { device->ok = false; device->msg = err.what (); return -1; } catch (...) { device->ok = false; device->msg = "Unknown error"; return -1; } #endif }
FREObject sendMIDIMessage(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) { int pointer = 0; int status = 0; int data1 = 0; int data2 = 0; FREGetObjectAsInt32(argv[0],&pointer); FREGetObjectAsInt32(argv[1],&status); FREGetObjectAsInt32(argv[2],&data1); FREGetObjectAsInt32(argv[3],&data2); RtMidiOut* out = (RtMidiOut *)pointer; //printf("Send Message : %i %i %i %i\n",out,status,data1,data2); outMessage[0] = (unsigned char)status; outMessage[1] = (unsigned char)data1; outMessage[2] = (unsigned char)data2; bool sendResult = false; try { if(out->isPortOpen()) out->sendMessage(&outMessage); }catch(std::exception e) { printf("Error sending message : %s\n",e.what()); } FREObject result; FRENewObjectFromBool(sendResult,&result); return result; }
int main(int argc, const char* argv[]) { if (argc < 1) { return -1; } unsigned int ports = midi.getPortCount(); if (ports < 1) { return -1; } midi.openPort(0); lua_State* L = luaL_newstate(); luaL_openlibs(L); lua_pushcfunction(L, midi_send); lua_setglobal(L, "midi_send"); luaL_dostring(L, "song = require 'notation'"); int result = luaL_dofile(L, argv[1]); if (result != 0) { std::cerr << lua_tostring(L, -1) << std::endl; } else { luaL_dostring(L, "song.go()"); } lua_close(L); return 0; }
//////////////////////////////////////////////////////////////////////////////// // SetupDialog::showEvent() //////////////////////////////////////////////////////////////////////////////// ///\brief Message handler for the window show event. ///\param [in] e: Description of the event. //////////////////////////////////////////////////////////////////////////////// void SetupDialog::showEvent(QShowEvent* /*e*/) { // Lock UI: blocked = true; // Get MIDI in properties: RtMidiIn midiIn; unsigned int portCnt = midiIn.getPortCount(); if (portCnt > 0) { int selItem = -1; // Loop through MIDI ports: for (unsigned int i = 0; i < portCnt; i++) { // Get name of the port: QString name(midiIn.getPortName(i).c_str()); // Does this match the currently selected option? if (name == inputName) selItem = i; // Add item to the combo box: ui->inputComboBox->addItem(name); } // Select current item, if any: ui->inputComboBox->setCurrentIndex(selItem); } // Get MIDI out properties: RtMidiOut midiOut; portCnt = midiOut.getPortCount(); if (portCnt > 0) { int selItem = -1; // Loop through MIDI ports: for (unsigned int i = 0; i < portCnt; i++) { // Get name of the port: QString name(midiOut.getPortName(i).c_str()); // Does this match the currently selected option? if (name == outputName) selItem = i; // Add item to the combo box: ui->outputComboBox->addItem(name); } // Select current item, if any: ui->outputComboBox->setCurrentIndex(selItem); } // Unlock UI: blocked = false; }
t_CKBOOL MidiOutManager::open( MidiOut * mout, const std::string & name ) { t_CKINT device_num = -1; try { RtMidiOut * rtmout = new RtMidiOut; t_CKINT count = rtmout->getPortCount(); for(t_CKINT i = 0; i < count; i++) { std::string port_name = rtmout->getPortName( i ); if( port_name == name ) { device_num = i; break; } } if( device_num == -1 ) { // search by substring for(t_CKINT i = 0; i < count; i++) { std::string port_name = rtmout->getPortName( i ); if( port_name.find( name ) != std::string::npos ) { device_num = i; break; } } } } catch( RtMidiError & err ) { if( !mout->m_suppress_output ) { // print it EM_error2( 0, "MidiOut: error locating MIDI port named %s", name.c_str() ); err.getMessage(); // const char * e = err.getMessage().c_str(); // EM_error2( 0, "...(%s)", err.getMessage().c_str() ); } return FALSE; } if(device_num == -1) { EM_error2( 0, "MidiOut: error locating MIDI port named %s", name.c_str() ); return FALSE; } t_CKBOOL result = open( mout, device_num ); return result; }
// ****************************************** void shruthiEditorSettings::getDeviceInfo() { // ****************************************** RtMidiIn *midiin = 0; RtMidiOut *midiout = 0; QString name; // Input ports: try { midiin = new RtMidiIn(); } catch ( RtError &error ) { error.printMessage(); exit( EXIT_FAILURE ); } unsigned int numdev = midiin->getPortCount(); std::cout << numdev << " midi input devices found.\n"; for (unsigned int i=0; i < numdev; i++) { try { name = QString::fromStdString(midiin->getPortName(i)); } catch ( RtError &error ) { error.printMessage(); goto cleanup; } midi_input_device->addItem(name,i); } // Output ports: try { midiout = new RtMidiOut(); } catch ( RtError &error ) { error.printMessage(); exit( EXIT_FAILURE ); } numdev = midiout->getPortCount(); std::cout << numdev << " midi output devices found.\n"; for (unsigned int i=0; i < numdev; i++) { try { name = QString::fromStdString(midiout->getPortName(i)); } catch ( RtError &error ) { error.printMessage(); goto cleanup; } midi_output_device->addItem(name,i); } cleanup: delete midiin; delete midiout; }
int main(int argc, char* argv[]) { char filename[] = "doom-e1m1.mid"; RtMidiOut *midiout = new RtMidiOut(); string portName; nPorts = midiout->getPortCount(); if(argc < 2) { if ( nPorts == 0 ) cout << "No ports available!\n"; for ( unsigned int i=0; i<nPorts; i++ ) { try { portName = midiout->getPortName(i); } catch (RtError &error) {error.printMessage(); } cout << " Output Port #" << i+1 << ": " << portName << '\n'; } }else{ int port = atoi(argv[1]); //midiout->openPort( port ); cout << "Opening midi" << endl; char *filef = argv[2]; if(argc == 3) parser.Open(filef); else parser.Open(filename); tickspersecond = ( (parser.bpm / 30.0) * ( parser.tpb)); cout << " Ticks per second: " << tickspersecond << endl; (void) signal(SIGINT, finish); tickcount = 0; Sequencer sequencers[parser.numtracks]; SequencerRunning = true; for(int i=0;i<parser.numtracks;i++) { sequencers[i].StartSequencer(i, &parser.mididata.tracks[i], port); sf::Sleep(0.01f); } sf::Sleep(1); timer.Reset(); while(run) { timecount = timer.GetElapsedTime(); tickcount += timecount * tickspersecond; timer.Reset(); //sf::Sleep(0.0001f); } } delete midiout; finish(0); return 0; }
value rtmidi_out_sendmessage(value obj, value msg) { RtMidiOut *midiout = (RtMidiOut *)(intptr_t)val_float(obj); std::vector<unsigned char> message; int size = val_array_size(msg); for (int i = 0; i < size; ++i) { message.push_back(val_int(val_array_i(msg, i))); } midiout->sendMessage(&message); return alloc_null(); }
int main() { std::vector<unsigned char> message; RtMidiOut *midiout = new RtMidiOut(); // Check available ports. unsigned int nPorts = midiout->getPortCount(); if ( nPorts == 0 ) { std::cout << "No ports available!\n"; goto cleanup; } cout<<"sending messages"<<endl; // Open first available port. midiout->openPort( 0 ); // Send out a series of MIDI messages. // Program change: 192, 5 message.push_back( 192 ); message.push_back( 5 ); midiout->sendMessage( &message ); // Control Change: 176, 7, 100 (volume) message[0] = 176; message[1] = 7; message.push_back( 100 ); midiout->sendMessage( &message ); // Note On: 144, 64, 90 message[0] = 144; message[1] = 64; message[2] = 90; midiout->sendMessage( &message ); sleep(1); message[0] = 144; message[1] = 64; message[2] = 90; midiout->sendMessage( &message ); sleep(3); cout<<"inside"<<endl; int bend; while(1){ cin>>bend; if (!bend) break; message[0] = 224; message[1] = 0; message[2] = bend; midiout->sendMessage( &message ); } // Note Off: 128, 64, 40 message[0] = 128; message[1] = 64; message[2] = 40; midiout->sendMessage( &message ); // Clean up cleanup: delete midiout; }
/** * Get the list of available ports. * Can be called repeatedly to regenerate the list if a MIDI device is plugged in or unplugged. */ void refreshPorts() { char cPortName[MAX_STR_SIZE]; inPortMap.clear(); outPortMap.clear(); if(midiin) { numInPorts = midiin->getPortCount(); for ( int i=0; i<numInPorts; i++ ) { try { std::string portName = midiin->getPortName(i); // CME Xkey reports its name as "Xkey ", which was a hassle to deal with in a Max patch, so auto-trim the names. portName = trim(portName); strncpy(cPortName, portName.c_str(), MAX_STR_SIZE); cPortName[MAX_STR_SIZE - 1] = NULL; inPortMap[gensym(cPortName)] = i; } catch ( RtMidiError &error ) { printError("Error getting MIDI input port name", error); } } } if(midiout) { numOutPorts = midiout->getPortCount(); for ( int i=0; i<numOutPorts; i++ ) { try { std::string portName = midiout->getPortName(i); // CME Xkey reports its name as "Xkey ", which was a hassle to deal with in a Max patch, so auto-trim the names. portName = trim(portName); strncpy(cPortName, portName.c_str(), MAX_STR_SIZE); cPortName[MAX_STR_SIZE - 1] = NULL; outPortMap[gensym(cPortName)] = i; } catch (RtMidiError &error) { printError("Error getting MIDI output port name", error); } } } }
int main(int argc, const char* argv[]) { if (argc < 1) { return -1; } unsigned int ports = midi.getPortCount(); if (ports < 1) { return -1; } midi.openPort(0); lua_State* L = luaL_newstate(); luaL_openlibs(L); lua_pushcfunction(L, midi_send); lua_setglobal(L, "midi_send"); luaL_dofile(L, argv[1]); lua_close(L); return 0; }
FREObject closeOutputDevice(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) { int pointer = 0; FREGetObjectAsInt32(argv[0],&pointer); try { RtMidiOut *out = (RtMidiOut *)pointer; if(out->isPortOpen()) out->closePort(); removeDeviceOut(out); delete out; }catch(std::exception e) { printf("Error closing output device.\n"); } FREObject result; FRENewObjectFromBool(true,&result); return result; }
QList<MidiDevice::Description> MidiDevice::enumerateOutputDevices() { RtMidiOut midiOut; QList<MidiDevice::Description> devs; int n = midiOut.getPortCount(); for (int i = 0; i < n; i++) { Description desc; desc.number = i; desc.type = Type_Output; try { desc.name = QString::fromStdString(midiOut.getPortName(i)); devs.append(desc); } catch (RtMidiError &err) { Q_UNUSED(err); } } return devs; return devs; }
int midi_send(lua_State* L) { double status = lua_tonumber(L, -3); double data1 = lua_tonumber(L, -2); double data2 = lua_tonumber(L, -1); std::vector<unsigned char> message(3); message[0] = static_cast<unsigned char>(status); message[1] = static_cast<unsigned char>(data1); message[2] = static_cast<unsigned char>(data2); midi.sendMessage(&message); return 0; }
t_CKBOOL MidiOutManager::open( MidiOut * mout, t_CKINT device_num ) { // see if port not already open if( device_num >= (t_CKINT)the_mouts.capacity() || !the_mouts[device_num] ) { // allocate RtMidiOut * rtmout = new RtMidiOut; try { rtmout->openPort( device_num ); } catch( RtError & err ) { if( !mout->m_suppress_output ) { // print it EM_error2( 0, "MidiOut: couldn't open MIDI port %i...", device_num ); err.getMessage(); // const char * e = err.getMessage().c_str(); // EM_error2( 0, "...(%s)", err.getMessage().c_str() ); } return FALSE; } // resize? if( device_num >= (t_CKINT)the_mouts.capacity() ) { t_CKINT size = the_mouts.capacity() * 2; if( device_num >= size ) size = device_num + 1; the_mouts.resize( size ); } // put rtmout in vector for future generations the_mouts[device_num] = rtmout; } // found (always) (except when it doesn't get here) mout->mout = the_mouts[device_num]; mout->m_device_num = (t_CKUINT)device_num; // done return TRUE; }
void ofApp::midiSetup(){ /////////////// MIDI SETUP //////////////////////////////////////////////////////////////////////////////// // Alterar ofxRtMidiOut.cpp ?? //midiOut.listPorts(); // via instance int portaEscolhida = 0; static RtMidiOut s_midiOut; ofLogVerbose("MIDI") << "ofxMidiOut: " << s_midiOut.getPortCount() << " ports available"; for(unsigned int i = 0; i < s_midiOut.getPortCount(); ++i){ string PortName = s_midiOut.getPortName(i); PortName.pop_back(); if (PortName.compare(0,3,"MMC")==0){ofLogVerbose("MIDI") << "PORTA MMC: " << i;portaEscolhida = i;}; ofLogVerbose("MIDI") << "ofxMidiOut: " << i << ": " << PortName; } // connect if (midiOut.openPort(portaEscolhida)) // by number // Gera LOG { ofLogVerbose("MIDI") << "MIDI open: true"; } else { ofLogVerbose("MIDI") << "MIDI open: false"; ofApp::exit(); } //midiOut.openPort("1"); // by name //midiOut.openVirtualPort("ofxMidiOut"); // open a virtual port for (int ii=0; ii<8; ii++){ vol[ii].enable=1; vol[ii].test=0; vol[ii].volume=0; } vol2_inverse = 0; ofLogVerbose("SETUP") << "MIDI inicializado"; /////////////// MIDI SETUP //////////////////////////////////////////////////////////////////////////////// }
RtMidiOutPtr rtmidi_out_create (enum RtMidiApi api, const char *clientName) { RtMidiWrapper* wrp = new RtMidiWrapper; std::string name = clientName; #if defined(__NO_EXCEPTIONS__) RtMidiOut* rOut = new RtMidiOut ((RtMidi::Api) api, name); if (rOut->isError()) { wrp->ptr = 0; wrp->data = 0; wrp->ok = false; wrp->msg = rOut->getError().what (); } else { wrp->ptr = (void*) rOut; wrp->data = 0; wrp->ok = true; wrp->msg = ""; } #else try { RtMidiOut* rOut = new RtMidiOut ((RtMidi::Api) api, name); wrp->ptr = (void*) rOut; wrp->data = 0; wrp->ok = true; wrp->msg = ""; } catch (const RtMidiError & err) { wrp->ptr = 0; wrp->data = 0; wrp->ok = false; wrp->msg = err.what (); } #endif return wrp; }
int main(int argc, const char*argv[]) { if (argc < 1) { return -1; } unsigned int ports = midi.getPortCount(); if (ports < 1) { return -1; } midi.openPort(0); lua_State* L = luaL_newstate(); luaL_openlibs(L); lua_pushcfunction(L, midi_send); lua_setglobal(L, "midi_send"); int ret = luaL_dofile(L, argv[1]); if(ret != 0){ printf("Error occurs when calling luaL_dofile() Hint Machine 0x%x\n",ret); printf("Error: %s", lua_tostring(L,-1)); } lua_close(L); return 0; }
//----------------------------------------------------------------------------- // name: probeMidiOut() // desc: ... //----------------------------------------------------------------------------- void probeMidiOut() { RtMidiOut * mout = NULL; try { mout = new RtMidiOut; } catch( RtError & err ) { EM_error2b( 0, "%s", err.getMessageString() ); return; } // get num t_CKUINT num = mout->getPortCount(); EM_error2b( 0, "------( chuck -- %i MIDI outputs )-----", num ); std::string s; for( t_CKUINT i = 0; i < num; i++ ) { try { s = mout->getPortName( i ); } catch( RtError & err ) { err.printMessage(); return; } EM_error2b( 0, " [%i] : \"%s\"", i, s.c_str() ); } }
int main() { RtMidiOut *midiout = new RtMidiOut(); std::vector<unsigned char> message; // Check available ports. unsigned int nPorts = midiout->getPortCount(); if ( nPorts == 0 ) { std::cout << "No ports available!\n"; delete midiout; return -1; } // Open first available port. midiout->openPort( 0 ); // Send out a series of MIDI messages. // Program change: 192, 5 message.push_back( 192 ); message.push_back( 5 ); midiout->sendMessage( &message ); usleep( 500000 ); // Control Change: 176, 7, 100 (volume) message[0] = 176; message[1] = 7; message.push_back( 100 ); midiout->sendMessage( &message ); usleep( 500000 ); // Note On: 144, 64, 90 message[0] = 144; message[1] = 64; message[2] = 90; midiout->sendMessage( &message ); usleep( 500000 ); // Platform-dependent ... see example in tests directory. // Note Off: 128, 64, 40 message[0] = 128; message[1] = 64; message[2] = 40; midiout->sendMessage( &message ); usleep( 500000 ); return 0; }
/* RtMidiOut API */ RtMidiOutPtr rtmidi_out_create_default () { RtMidiWrapper* wrp = new RtMidiWrapper; #if defined(__NO_EXCEPTIONS__) RtMidiOut* rOut = new RtMidiOut (); if (rOut->isError()) { wrp->ptr = 0; wrp->data = 0; wrp->ok = false; wrp->msg = rOut->getError().what (); } else { wrp->ptr = (void*) rOut; wrp->data = 0; wrp->ok = true; wrp->msg = ""; } #else try { RtMidiOut* rOut = new RtMidiOut (); wrp->ptr = (void*) rOut; wrp->data = 0; wrp->ok = true; wrp->msg = ""; } catch (const RtMidiError & err) { wrp->ptr = 0; wrp->data = 0; wrp->ok = false; wrp->msg = err.what (); } #endif return wrp; }
enum RtMidiApi rtmidi_out_get_current_api (RtMidiPtr device) { #if defined(__NO_EXCEPTIONS__) RtMidiOut* rtm = (RtMidiOut*) device->ptr; rtm->resetError(); RtMidiApi curApi = (RtMidiApi) rtm->getCurrentApi (); if (rtm->isError()) { device->ok = false; device->msg = rtm->getError().what (); return RT_MIDI_API_UNSPECIFIED; } return curApi; #else try { return (RtMidiApi) ((RtMidiOut*) device->ptr)->getCurrentApi (); } catch (const RtMidiError & err) { device->ok = false; device->msg = err.what (); return RT_MIDI_API_UNSPECIFIED; } #endif }
virtual void Run() { cout << "Thread " << threadnum << " running." << endl; while(SequencerRunning) { for(unsigned int eventnum=lastevent;eventnum<track->events.size();eventnum++) { Event *tmp = &track->events[eventnum]; if(tmp->tick > tickcount) break; if(!tmp->played) { if(tmp->statusmsg != 0xFF ) { if(tmp->statusmsg >= 0x80) { message.push_back(tmp->statusmsg); if(tmp->data.size() >= 1) message.push_back(tmp->data[0]); if(tmp->data.size() == 2) message.push_back(tmp->data[1]); midiout->sendMessage( &message ); message.erase(message.begin(),message.end()); message.resize(0); message.clear(); cout << "Tick: " << tickcount << " - Out (0x" << hex << static_cast<int>(tmp->statusmsg) << ")" << endl; } }else{ switch(tmp->data[0]) { case 0x51: parser.bpm = tmp->data[1]; tickspersecond = ( (parser.bpm / 30.0) * ( parser.tpb)); cout << "BPM Changed to " << parser.bpm << " - Ticks per second: " << tickspersecond << endl; break; case 0x58: int numerador, denominador, clocks, notated; numerador = tmp->data[1]; denominador = tmp->data[2]; clocks = tmp->data[3]; notated = tmp->data[4]; cout << "Metronome: " << numerador << "/" << denominador << " - Clocks: " << clocks << " Notated: " << notated << endl; break; default: cout << "Sem handler" << endl; } } tmp->played = true; lastevent = eventnum; } } } delete midiout; cout << "Thread " << threadnum << " closed." << endl; }
int main() { RtMidiIn *midiin = 0; RtMidiOut *midiout = 0; // RtMidiIn constructor try { midiin = new RtMidiIn(); } catch ( RtError &error ) { error.printMessage(); exit( EXIT_FAILURE ); } // Check inputs. unsigned int nPorts = midiin->getPortCount(); std::cout << "\nThere are " << nPorts << " MIDI input sources available.\n"; std::string portName; unsigned int i; for ( i=0; i<nPorts; i++ ) { try { portName = midiin->getPortName(i); } catch ( RtError &error ) { error.printMessage(); goto cleanup; } std::cout << " Input Port #" << i+1 << ": " << portName << '\n'; } // RtMidiOut constructor try { midiout = new RtMidiOut(); } catch ( RtError &error ) { error.printMessage(); exit( EXIT_FAILURE ); } // Check outputs. nPorts = midiout->getPortCount(); std::cout << "\nThere are " << nPorts << " MIDI output ports available.\n"; for ( i=0; i<nPorts; i++ ) { try { portName = midiout->getPortName(i); } catch ( RtError &error ) { error.printMessage(); goto cleanup; } std::cout << " Output Port #" << i+1 << ": " << portName << '\n'; } std::cout << '\n'; // Clean up cleanup: delete midiin; delete midiout; return 0; }
Driver::tCollDeviceDescriptor DriverMIDI::enumerate() { M_LOG("[DriverMIDI] enumerate"); Driver::tCollDeviceDescriptor collDevices; std::string portNameIn, portNameOut; RtMidiIn midiIn; RtMidiOut midiOut; std::mutex mtxDevices; std::vector<std::future<void>> pendingFutures; unsigned nPortsOut = midiOut.getPortCount(); unsigned nPortsIn = midiIn.getPortCount(); for (unsigned int iOut = 0; iOut < nPortsOut; iOut++) { try { portNameOut = midiOut.getPortName(iOut); if (portNameOut != "") { for (unsigned int iIn = 0; iIn < nPortsIn; iIn++) { try { portNameIn = midiIn.getPortName(iIn); if (portNameIn == portNameOut) { M_LOG("[DriverMIDI] out: " << portNameOut << " ->" << iOut); M_LOG("[DriverMIDI] in: " << portNameIn << " ->" << iIn); auto f = std::async( std::launch::async, [this, &mtxDevices, &collDevices, iIn, iOut]() { bool received = false; bool timeout = false; RtMidiIn _midiIn; RtMidiOut _midiOut; std::vector<unsigned char> recv; std::vector<unsigned char> sysExIdentity = {0xF0, 0x7E, 0x00, 0x06, 0x01, 0xF7}; _midiIn.openPort(iIn); _midiIn.ignoreTypes(false); _midiOut.openPort(iOut); _midiOut.sendMessage(&sysExIdentity); auto start = std::chrono::system_clock::now(); while (!received && !timeout) { _midiIn.getMessage(&recv); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now() - start); if (recv.size() > 0) { if (recv[0] == 0xF0 && recv[1] == 0x7E && recv[3] == 0x06 && recv[4] == 0x02) { received = true; unsigned vendorId = recv[5]; unsigned productId = (recv[6] << 8) | recv[7]; std::lock_guard<std::mutex> lock(mtxDevices); collDevices.emplace_back(_midiIn.getPortName(iIn), DeviceDescriptor::Type::MIDI, vendorId, productId, "", iIn, iOut); M_LOG("[DriverMIDI] found device: " << vendorId << ":" << productId); } } else if (duration > std::chrono::milliseconds(500)) { timeout = true; M_LOG("[DriverMIDI] identity reply timeout on port #" << iOut); } } _midiIn.closePort(); _midiOut.closePort(); }); pendingFutures.push_back(std::move(f)); } } catch (RtMidiError& error) { std::string strError(error.getMessage()); M_LOG("[DriverMIDI] RtMidiError: " << strError); } } } } catch (RtMidiError& error) { std::string strError(error.getMessage()); M_LOG("[DriverMIDI] RtMidiError: " << strError); } } return collDevices; }
int _tmain (int argc, char** argv) { //FreeConsole(); //AllocConsole(); //freopen( "CONOUT$", "wb", stdout); ///// SETUP FILE WRITE const char* datafile = "data.txt"; ofstream outfile; outfile.open (datafile);//, std::ofstream::out | std::ofstream::trunc); //// Setup bluetooth const char* portLeft = "COM9"; const char* portRight = "COM6"; HANDLE* hSerialLeft = setupBluetooth(portLeft); HANDLE* hSerialRight = setupBluetooth(portRight); char szBuff[2 + 1] = {0}; // Not sure about the second 1 ////////////////////////////////////////// /////////////// SETUP MIDI //////////////// RtMidiOut *midiout = new RtMidiOut(); // Check available ports. unsigned int nPorts = midiout->getPortCount(); if ( nPorts == 0 ) { std::cout << "No ports available!\n"; //goto cleanup; } // Open first available port. midiout->openPort( PORT ); ///////////////////////////////////// SetConsoleTitle(_T("IR LEDs to GUI Integration Test - Demo")); HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // write the title PrintTitle(console); // create a wiimote object wiimote remote; // in this demo we use a state-change callback to get notified of // extension-related events, and polling for everything else // (note you don't have to use both, use whatever suits your app): remote.ChangedCallback = on_state_change; // notify us only when the wiimote connected sucessfully, or something // related to extensions changes remote.CallbackTriggerFlags = (state_change_flags)(CONNECTED | EXTENSION_CHANGED | MOTIONPLUS_CHANGED); reconnect: COORD pos = { 0, 6 }; SetConsoleCursorPosition(console, pos); // try to connect the first available wiimote in the system // (available means 'installed, and currently Bluetooth-connected'): WHITE; _tprintf(_T(" Looking for a Wiimote ")); static const TCHAR* wait_str[] = { _T(". "), _T(".. "), _T("...") }; unsigned count = 0; while(!remote.Connect(wiimote::FIRST_AVAILABLE)) { _tprintf(_T("\b\b\b\b%s "), wait_str[count%3]); count++; } // connected - light all LEDs remote.SetLEDs(0x0f); BRIGHT_CYAN; _tprintf(_T("\b\b\b\b... connected!")); COORD cursor_pos = { 0, 6 }; /////////////// Wiimote Variables /////////////// float positions [2][2]; // First array is left hand, second array is right. First element of array is x, second is y int quads[2]; // First element is left hand, second element is right PositionHistory* posHistoryL = setupPosHistory(1000, 30); // Left hand PositionHistory* posHistoryR = setupPosHistory(1000, 30); // Left hand positions[0][0] = 0.67; // These give our starting points!!!! positions[0][1] = 0.5; // Very important positions[1][0] = 0.33; // Must calibrate these positions[1][1] = 0.5; // Don't forget!! int writeTimerCount = 0; ////////////////////////////////////////////////// // display the wiimote state data until 'Home' is pressed: while(!remote.Button.Home()){ // && !GetAsyncKeyState(VK_ESCAPE)) // IMPORTANT: the wiimote state needs to be refreshed each pass while(remote.RefreshState() == NO_CHANGE) Sleep(1); // // don't hog the CPU if nothing changed cursor_pos.Y = 8; SetConsoleCursorPosition(console, cursor_pos); // did we loose the connection? if(remote.ConnectionLost()){ BRIGHT_RED; _tprintf( _T(" *** connection lost! *** \n") BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE BLANK_LINE); Beep(100, 1000); Sleep(2000); COORD pos = { 0, 6 }; SetConsoleCursorPosition(console, pos); _tprintf(BLANK_LINE BLANK_LINE BLANK_LINE); goto reconnect; } // Battery level: CYAN; _tprintf(_T(" Battery: ")); // (the green/yellow colour ranges are rough guesses - my wiimote // with rechargeable battery pack fails at around 15%) (remote.bBatteryDrained )? BRIGHT_RED : (remote.BatteryPercent >= 30)? BRIGHT_GREEN : BRIGHT_YELLOW; _tprintf(_T("%3u%% "), remote.BatteryPercent); // IR: CYAN ; _tprintf(_T("\n IR:")); _tprintf(_T(" Mode %s "), ((remote.IR.Mode == wiimote_state::ir::OFF )? _T("OFF ") : (remote.IR.Mode == wiimote_state::ir::BASIC )? _T("BASIC") : (remote.IR.Mode == wiimote_state::ir::EXTENDED)? _T("EXT. ") : _T("FULL "))); // IR dot sizes are only reported in EXTENDED IR mode (FULL isn't supported yet) bool dot_sizes = (remote.IR.Mode == wiimote_state::ir::EXTENDED); for(unsigned index=0; index<4; index++){ wiimote_state::ir::dot &dot = remote.IR.Dot[index]; if(!remote.IsBalanceBoard()) WHITE; _tprintf(_T("%u: "), index); if(dot.bVisible) { WHITE; _tprintf(_T("Seen ")); } else{ RED; _tprintf(_T("Not seen ")); } _tprintf(_T("Size")); if(dot_sizes) _tprintf(_T("%3d "), dot.Size); else{ RED; _tprintf(_T(" n/a")); if(dot.bVisible) WHITE; } //_tprintf(_T(" X %.3f Y %.3f\n"), 133.9*(dot.X-0.470), 88.7*(dot.Y-0.575)); // Changed stuff here! _tprintf(_T(" X %.3f Y %.3f\n"), dot.X, dot.Y); if(index < 3) _tprintf(_T(" ")); } BRIGHT_WHITE; determineQuadrant(remote.IR.Dot, quads, positions); cout << quads[0] << endl; cout << quads[1] << endl; cout << "Left Hand - X = " << positions[0][0] << " Y = " << positions[0][1] << endl; cout << "Right Hand - X = " << positions[1][0] << " Y = " << positions[1][1] << endl; if (writeTimerCount == 3){ outfile << positions[0][0] << " " << positions[0][1] << " " << "1" << endl; // write to file outfile << positions[1][0] << " " << positions[1][1] << " " << "0" << endl; writeTimerCount = 0; } else { writeTimerCount++; } posHistoryL->oldest_point = (posHistoryL->oldest_point + 1) % posHistoryL->size; // Move circular buffer forward posHistoryL->velo_point = (posHistoryL->velo_point + 1) % posHistoryL->size; // Move circular buffer forward posHistoryL->positionsX[posHistoryL->oldest_point] = positions[0][0]; // Update left hand X position posHistoryL->positionsY[posHistoryL->oldest_point] = positions[0][1]; // Update left hand Y position cout << (posHistoryL->positionsX[posHistoryL->oldest_point] - posHistoryL->positionsX[posHistoryL->velo_point])/posHistoryL->dis << endl; // Print left hand x velocity cout << posHistoryL->oldest_point << endl; // For debugging /// Read Bluetooth and send MIDI signals /// readBluetooth(*hSerialRight, szBuff, quads, midiout, 0); readBluetooth(*hSerialLeft, szBuff, quads, midiout, 40); } outfile.close(); remove (datafile); // disconnect (auto-happens on wiimote destruction anyway, but let's play nice) remote.Disconnect(); Beep(1000, 200); BRIGHT_WHITE; // for automatic 'press any key to continue' msg ///////////////////////////// CloseHandle(*hSerialLeft); CloseHandle(*hSerialRight); // Clean up //cleanup: //delete midiout; CloseHandle(console); //system("exit"); return 0; }
int main(){ HANDLE hSerial = CreateFile("COM8", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,0); // Must specify Windows serial port above, i.e. COM6 if(hSerial==INVALID_HANDLE_VALUE){ if(GetLastError()==ERROR_FILE_NOT_FOUND){ cout << "Does not exist" << endl; //serial port does not exist. Inform user. } cout << "Strange error" << endl; } DCB dcbSerialParams = {0}; dcbSerialParams.DCBlength=sizeof(dcbSerialParams); if (!GetCommState(hSerial, &dcbSerialParams)) { cout << "Can't get state" << endl; } dcbSerialParams.BaudRate=CBR_9600; // I didn't expect this number but it works dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; if(!SetCommState(hSerial, &dcbSerialParams)){ cout << "Can't set state" << endl; } char szBuff[1 + 1] = {0}; // First 1 for number of bytes, not sure about the second 1 DWORD dwBytesRead = 0; RtMidiOut *midiout = new RtMidiOut(); // Check available ports. unsigned int nPorts = midiout->getPortCount(); if ( nPorts == 0 ) { std::cout << "No ports available!\n"; goto cleanup; } // Open first available port. midiout->openPort( PORT ); while(1){ if(!ReadFile(hSerial, szBuff, 1, &dwBytesRead, NULL)){ // 1 for number of bytes cout << "Can't read" << endl; } cout << szBuff << endl; // print read data if(szBuff[0] == '0'){ midiOff(midiout, 52); midiOff(midiout, 50); midiOff(midiout, 48); } if(szBuff[0] == '4'){ midiOff(midiout, 52); midiOff(midiout, 50); midiOn(midiout, 48); } if(szBuff[0] == '2'){ midiOff(midiout, 48); midiOff(midiout, 52); midiOn(midiout, 50); } if(szBuff[0] == '6'){ midiOff(midiout, 48); midiOff(midiout, 50); midiOn(midiout, 52); } } CloseHandle(hSerial); // Clean up cleanup: delete midiout; return 0; }