// ------------------------------------------------------------------------
    // Polls messages from the queue that the SerialThread object keeps. Once a
    // message has been polled it is removed from the queue. There are some
    // special messages that mark the start/end of the communication with the
    // device.
    // ------------------------------------------------------------------------
    void Update()
    {
        // If the user prefers to poll the messages instead of receiving them
        // via SendMessage, then the message listener should be null.
        if (messageListener == null)
        {
            return;
        }

        // Read the next message from the queue
        string message = serialThread.ReadSerialMessage();

        if (message == null)
        {
            return;
        }

        // Check if the message is plain data or a connect/disconnect event.
        if (ReferenceEquals(message, SERIAL_DEVICE_CONNECTED))
        {
            messageListener.SendMessage("OnConnectionEvent", true);
        }
        else if (ReferenceEquals(message, SERIAL_DEVICE_DISCONNECTED))
        {
            messageListener.SendMessage("OnConnectionEvent", false);
        }
        else
        {
            messageListener.SendMessage("OnMessageArrived", message);
        }
    }
    public string ReadSerialMessage()
    {
        if (serialThread == null)
        {
            return(null);
        }

        string data = serialThread.ReadSerialMessage(); // Read the next message from the queue

        if (ReferenceEquals(data, SerialController.SERIAL_DEVICE_CONNECTED))
        {
            Debug.Log("Connection established to " + portName);
            failures = 0;
            return(null);
        }
        else if (ReferenceEquals(data, SerialController.SERIAL_DEVICE_DISCONNECTED))
        {
            failures++;
            if (maxFailuresAllowed > 0 && failures >= maxFailuresAllowed) //shut ourselves down
            {
                enabled = false;
            }
            Debug.LogWarning("Connection attempt failed or disconnection detected on " + portName + ". Attempting reconnection");
            return(null);
        }

        return(data);
    }
    public string ReadSerialMessage()
    {
        if (serialThread == null)
        {
            return(null);
        }

        string data = serialThread.ReadSerialMessage(); // Read the next message from the queue

        if (ReferenceEquals(data, SerialController.SERIAL_DEVICE_CONNECTED))
        {
            hypercube.input._debugLog("<color=#00ff00>Connection established to " + portName + "</color>");
            failures    = 0;
            isConnected = true;
            return(null);
        }
        else if (ReferenceEquals(data, SerialController.SERIAL_DEVICE_DISCONNECTED))
        {
            isConnected = false;
            failures++;
            if (maxFailuresAllowed > 0 && failures >= maxFailuresAllowed) //shut ourselves down
            {
                enabled = false;
            }

            hypercube.input._debugLog("<color=orange>Serial connection attempt failed or disconnection occurred on '" + portName + "'.</color>");
            return(null);
        }

        return(data);
    }
    // Use this for initialization
    IEnumerator Start()
    {
        // Connect to the robot and start the serial thread
        var serialThread = new SerialThread(portName, baudRate, delayBeforeReconnecting, maxUnreadMessages);
        var thread       = new Thread(new ThreadStart(serialThread.RunForever));

        thread.Start();

        // Connect to the Tellynet web socket server
        var ws = new WebSocket(tellynetSocketProtocol + tellynetServer + tellynetPort);

        try {
            ws.Connect();
            socket = ws;

            //Send a room specific join message to Tellynet
            ws.Send("join #letsrobot");

            //Grabs messages from TellyNet
            ws.OnMessage += (sender, e) => {
                //Check to see if robot says first.
                string botReply = serialThread.ReadSerialMessage();

                if (botReply != null)
                {
                    Debug.Log("Bot replied: " + botReply);
                }


                Console.WriteLine("Laputa says: " + e.Data);
                string reply = e.Data;
                if (e.IsText)
                {
                    //The messages from TellyNet are JSON objects
                    try {
                        SimpleJSON.JSONNode msg = SimpleJSON.JSON.Parse(reply);

                        //This is a special use case for the bitslapper,
                        //We need to develop a whole new command protocol instead.
                        if (msg ["bits"].Value != "")
                        {
                            Debug.Log(msg ["bits"].Value);
                            var bitAmount = int.Parse(msg ["bits"].Value);
                            if (bitAmount >= 100)
                            {
                                toRobot = "bitslap";
                            }
                            else if (bitAmount <= 99 && bitAmount >= 10)
                            {
                                toRobot = "bittyslap";
                            }
                        }
                        else
                        {
                            //Comment this out if you don't want to send all messages to robot
                            toRobot = msg["message"].Value;
                        }

                        //example of how to grab user chat messages from TellyNet.
                        Debug.Log(msg ["username"].Value + ": " + msg ["message"].Value);
                    } catch (KeyNotFoundException) {
                    }
                    //If there is a message we can send the robot, that happens here.
                    if (toRobot != null)
                    {
                        serialThread.SendSerialMessage(toRobot);
                        Debug.Log(toRobot);
                        toRobot = "";
                    }
                }
            };
        } catch { Debug.Log("Can't connect to TellyNet"); }
        yield return(0);
    }