// Keep trying to connect until successful public IEnumerator KeepTryingToConnect() { // ensure is singleton if (connect_loop_running) { Debug.Log("Connection management loop already running!"); yield break; } // run forever, so auto-reconnect if connection is dropped while (true) { connect_loop_running = true; if (!nt.isConnected()) { tryToConnect(100); } else { last_connected_time = nt.getTimeStamp(); } // check again in .5s yield return(new WaitForSeconds(.5f)); } connect_loop_running = false; }
// Awake is called **before** any Start methods. // so we make sure the NoiseTag controller is ready before // any game objects which may want to use it! void Awake() { if (_instance != null && _instance != this) { Destroy(this.gameObject); return; } _instance = this; DontDestroyOnLoad(this.gameObject); // keep the controller arround... // Switch to 640 x 480 full-screen at 60 hz, and put // VSYNC on, so we a) run fast, b) are time-accurate. Screen.SetResolution(Screen.width, Screen.height, FullScreenMode.ExclusiveFullScreen); // FORCE!! Sync framerate to monitors refresh rate // get the current display rate, and set the vSyncCount to get as close as possible // for the code bits QualitySettings.vSyncCount = 1; if (FRAMESPERCODEBIT <= 0) // set framesperbit to be close to target framerate { int refreshRate = Screen.currentResolution.refreshRate; float framesperbit = refreshRate / QualitySettings.vSyncCount / targetFrameRate; FRAMESPERCODEBIT = (int)Math.Round(framesperbit + .1); } nt = new Noisetag(new System.IO.StringReader(codebook.text), null, null); // setup the event handlers when the connection is up. // debug message handler : prints all new messages nt.stopFlicker(); // reset state nt.addMessageHandler(newMessageHandler); nt.addSelectionHandler(selectionHandler); nt.addPredictionHandler(newPredictionHandler); nt.addSignalQualityHandler(signalQualityHandler); nt.addNewTargetHandler(newTargetHandler); nt.setFramesPerBit(FRAMESPERCODEBIT); // init the info on the set of objIDs we are managing.. if (objIDs == null) { objIDs = new int[127]; for (int i = 0; i < objIDs.Length; i++) { objIDs[i] = i + 1; // N.B. objid > 0 } } if (registeredobjIDs == null) { registeredobjIDs = new NoisetagBehaviour[objIDs.Length]; } nframe = 0; isRunning = false; // magic co-routine to record accurately the time the last frame was drawn StartCoroutine(recordFrameTime()); // magic co-routine to make and maintain the decoder connection last_connected_time = nt.getTimeStamp(); StartCoroutine(KeepTryingToConnect()); }
// add a coroutine to record exact time-stamps for the frame rendering.. public IEnumerator recordFrameTime() { while (true) // so we never terminate { yield return(new WaitForEndOfFrame()); lastframetime = nt.getTimeStamp(); } }