// Incoming thread - listen for input events from controller private void IncomingThread() { Debug.Log("In thread started."); // Read in data to this buffer Byte[] buffer = new Byte[bufferSize]; // Details number of bytes read on inPort int bytesRead = 0; while (programActive) { try { // Try reading inPort bytesRead = inPort.Read(buffer, 0, bufferSize); // If something was read into buffer if (bytesRead > 0) { // Parse byte to int int inputEvent = buffer[0] - 48; // avoids actually converting/parsing // Send to input manager to handle inputMgr.ReceiveInputEvent(inputEvent); } } catch (Exception e) { Debug.Log("In thread error: " + e.Message); } } // Close the com port if still open if (inPort.IsOpen) { inPort.Close(); } Debug.Log("In thread dead"); }
} // end GetPortNames() // Listens for controller input, sends input events to InputMgr via its function call void ProcessData(int id) { // For some reason, id is 1 more than it should be at this point id -= 1; // dirty hack Debug.Log("Arduino thread " + id + " started. Attempting to pair..."); // True when paired, allows main loop to run bool paired = false; // consider removing // Attempt to pair with arduino using given port at id // Send pair request message ports[id].Write("P"); Debug.Log(id + " pair request sent."); // Read response string response = ports[id].ReadLine(); Debug.Log("Reply: " + response); if (response == "Paired") { paired = true; Debug.Log(id + " paired with arduino"); } else { Debug.Log(id + " pairing failed"); } // Thread main loop, runs while game is still being played and if paired while (paired && programActive) { try { // The string being recieved from arduino should be converted to int int message = Convert.ToInt32(ports[id].ReadLine()); // Send the input data to InputMgr to handle input logic for this event inputMgr.ReceiveInputEvent(message); } catch (TimeoutException) { /* Do nothing, loop will be reset */ } } // If program disabled, unpair if (!programActive) { // Send unpair request ports[id].Write("U"); // Mark response string reply = ports[id].ReadLine().ToString(); Debug.Log("Unpair reply: " + reply); // No longer paired paired = false; // Close all open serial ports foreach (SerialPort sp in ports) { // Close the serial port if still open if (sp != null && sp.IsOpen) { sp.Close(); } } } Debug.Log("Thread out"); }