/// <summary> /// The method to invoke when data is received on the serial port communication channel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnDataReceived(object sender, SerialDataReceivedEventArgs e) { string input = String.Empty; if (connectionStatus == ConnectionStatus.Disconnected || !connection.IsOpen) { ThreadHelper.SetCOMConnectionStatus("Disconnected"); Debug.Log("Serial not connected"); return; } try { //Debug.Log("Receiving..."); input = connection.ReadLine(); Debug.Log(input); //Debug.Log(ConnectionStatus); JObject inputParsed = Parse(input); if (inputParsed != null) { if (connectionStatus == ConnectionStatus.Handshake && inputParsed.ContainsKey("serial_handshake")) { //if (inputParsed["serial_handshake"].ToObject<string>() != "failed") if (true) { available_settings = inputParsed["serial_handshake"].ToObject <SerialSettingsCollection>(); if (HandshakeResponse_callback != null) { InvokeHandshakeResponseCallback(available_settings); } } else { // Handshake failed } } if (ConnectionStatus == ConnectionStatus.WaitingConnectInit && inputParsed.ContainsKey("connect")) { string param = inputParsed["connect"].ToObject <string>(); if (param == "init") { ConnectAcceptResponse(); } } if (ConnectionStatus == ConnectionStatus.Connected) { ThreadHelper.SetCOMConnectionStatus("Connected to " + stream_label); DeliverSubscriptions(); } } } catch (Newtonsoft.Json.JsonReaderException ex) { Debug.Log("Invalid JSON"); Debug.Log(ex); } catch (TimeoutException ex) { Debug.Log("Serial.OnDataReceived timeout exception captured\nSettings:"); Debug.Log(connection.BaudRate); Debug.Log(ex); if (connection.IsOpen) { Debug.Log(connection.ReadExisting()); connection.Close(); } } catch (Exception ex) { Debug.Log("Exception caught in SerialHandler.OnDataReceived()"); Debug.Log(input); Debug.Log(ex); } if (!connection.IsOpen) { if (Program.settings.comSettings.baud_rate != 0) { connection.BaudRate = Program.settings.comSettings.baud_rate; connection.Parity = default_settings.Parity; connection.DataBits = default_settings.DataBits; connection.StopBits = default_settings.StopBits; connection.NewLine = default_settings.NewLine; } try { Debug.Log("Reopening connection..."); connection.Open(); } catch (Exception) { } } }