public void StateChanged(string state) { bleState = (ConnectState)Enum.Parse(typeof(ConnectState), state); switch (bleState) { default: break; } AndroidCall.AndroidToast("蓝牙的状态改变了,当前状态-" + state); log.text = bleState.ToString(); }
//void SerialPortErrorReceived(object sender, SerialErrorReceivedEventArgs e) //{ // Debug.WriteLine($"SerialPort exception: {e.EventType.ToString()}"); // log.Error($"SerialPort Error: {e.EventType.ToString()}"); // //MessageDialog.ShowAsync($"SerialPort Error: {e.EventType.ToString()}", "TNC Connect Error", MessageBoxButton.OK); // _serialPort.Close(); // return; //} //delegate void CloseDialogWindow(Window window); //void CloseWindow(Window window) => window.Close(); //public void CloseDlgWindow(Window window) //{ // if ((window.Dispatcher.CheckAccess())) // { // window.Close(); // } // else // { // window.Dispatcher.Invoke(DispatcherPriority.Normal, new CloseDialogWindow(CloseWindow), window); // } //} public async Task <bool> BBSConnectThreadProcAsync() { _packetMessagesSent.Clear(); _packetMessagesReceived.Clear(); SerialDevice serialDevice = EventHandlerForDevice.Current.Device; serialDevice.BaudRate = (uint)_tncDevice.CommPort?.Baudrate; serialDevice.StopBits = (SerialStopBitCount)_tncDevice.CommPort?.Stopbits; serialDevice.DataBits = Convert.ToUInt16(_tncDevice.CommPort.Databits); serialDevice.Parity = (SerialParity)_tncDevice.CommPort?.Parity; serialDevice.Handshake = (SerialHandshake)_tncDevice.CommPort.Flowcontrol; serialDevice.ReadTimeout = new TimeSpan(0, 0, 1); // hours, min, sec //serialDevice.ReadTimeout = new TimeSpan(0, 0, 0); // hours, min, sec serialDevice.WriteTimeout = new TimeSpan(0, 0, 0); bool carrierDetectState = serialDevice.CarrierDetectState; bool dataSetReadyState = serialDevice.DataSetReadyState; bool breakSignalState = serialDevice.BreakSignalState; bool isDataTerminalReadyEnabled = serialDevice.IsDataTerminalReadyEnabled; bool isRequestToSendEnabled = serialDevice.IsRequestToSendEnabled; _serialPort = new SerialPort(); //_serialPort.RtsEnable = _TncDevice.CommPort.Flowcontrol == _serialPort.Handshake.RequestToSend ? true : false; //_serialPort..ErrorReceived += new SerialErrorReceivedEventHandler(SerialPortErrorReceived); LogHelper(LogLevel.Info, "\n"); LogHelper(LogLevel.Info, $"{DateTime.Now.ToString()}"); LogHelper(LogLevel.Info, $"{_tncDevice.Name}: {serialDevice.PortName}, {serialDevice.BaudRate}, {serialDevice.DataBits}, {serialDevice.StopBits}, {serialDevice.Parity}, {serialDevice.Handshake}"); try { _connectState = ConnectState.ConnectStateNone; string readText = ""; string readCmdText = ""; try { _connectState = ConnectState.ConnectStatePrepareTNCType; if (_tncDevice.Name == "XSC_Kantronics_KPC3-Plus") { readCmdText = await KPC3PlusAsync(); } else if (_tncDevice.Name == "XSC_Kenwood_TM-D710A" || _tncDevice.Name == "XSC_Kenwood_TH-D72A") { bool success = await KenwoodAsync(); if (!success) { throw new IOException(); //return false; } } // Send Pre-Commands string preCommands = _tncDevice.InitCommands.Precommands; string[] preCommandLines = preCommands.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); _connectState = ConnectState.ConnectStatePrepare; foreach (string commandLine in preCommandLines) { await _serialPort.WriteAsync(commandLine + "\r\n"); //readText = await _serialPort.ReadLine(); // Read command //log.Info(readCmdText + _TNCPrompt + readText); readText = await _serialPort.ReadToAsync(_TNCPrompt); // Result for command //log.Info(readText); //readCmdText = await _serialPort.ReadTo(_TNCPrompt); // Next command } } catch (Exception e) { if (e is IOException) { await Utilities.ShowMessageDialogAsync("Looks like the USB cable to the TNC is disconnected, or the radio is off", "TNC Connect Error"); return(false); } LogHelper(LogLevel.Error, $"{e.Message}"); await Utilities.ShowMessageDialogAsync("Failed setting up the TNC"); return(false); } // Connect to JNOS TimeSpan readTimeout = _serialPort.ReadTimeout; _serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 60, 0); BBSConnectTime = DateTime.Now; _connectState = ConnectState.ConnectStateBBSTryConnect; await _serialPort.WriteAsync("connect " + _messageBBS + "-1" + "\r\x05"); //readText = await _serialPort.ReadLineAsync(); // Read command string readConnectText = await _serialPort.ReadLineAsync(); // Read command response if (readConnectText.ToLower().Contains(_tncDevice.Prompts.Timeout.ToLower())) { await Utilities.ShowMessageDialogAsync("Timeout connecting to the BBS.\nIs the BBS connect name and frequency correct?\nIs the antenna connected.\nThe BBS may be out of reach.", "BBS Connect Error"); goto Disconnect; } _connectState = ConnectState.ConnectStateBBSConnected; readConnectText = await _serialPort.ReadToAsync(_BBSPrompt); // read connect response //Debug.WriteLine(readConnectText + _BBSPrompt); //log.Info(readText + "\n" + readConnectText + _BBSPrompt); _serialPort.ReadTimeout = readTimeout; // Test await _serialPort.WriteAsync("B\r\x05"); // Disconnect from BBS (JNOS) readText = await _serialPort.ReadToAsync(_TNCPrompt); //readText = await _serialPort.ReadTo(_BBSPrompt); // Next command //Debug.WriteLine(readText + "\n"); await _serialPort.WriteAsync("XM 0\r\x05"); readText = await _serialPort.ReadToAsync(_BBSPrompt); // Read command //Debug.WriteLine(readText); //log.Info(readText); //readCmdText = await _serialPort.ReadLine(); // Read prompt //Debug.WriteLine(readCmdText); //log.Info(readCmdText); // Send messages foreach (PacketMessage packetMessage in _packetMessagesToSend) { _error = true; if (_error) { break; } if (packetMessage.BBSName == _messageBBS) { SendMessageAsync(packetMessage); //_serialPort.ReadTimeout = new TimeSpan(0, 0, 4, 0, 0); //try //{ // await _serialPort.Write("SP " + packetMessage.MessageTo + "\r"); // await _serialPort.Write(packetMessage.MessageSubject + "\r"); // await _serialPort.Write(packetMessage.MessageBody + "\r\x1a\r\x05"); // readText = await _serialPort.ReadLine(); // Read SP // Debug.WriteLine(readText); // log.Info(readText); // readText = await _serialPort.ReadTo(") >"); // read response // Debug.WriteLine(readText + _BBSPrompt); // log.Info(readText + _BBSPrompt); // readText = await _serialPort.ReadTo("\n"); // Next command // Debug.WriteLine(readText + "\n"); // packetMessage.MessageSentTime = DateTime.Now; // _packetMessagesSent.Add(packetMessage); //} //catch (Exception e) //{ // log.Error("Send message exception:", e); // //_serialPort.DiscardInBuffer(); // //_serialPort.DiscardOutBuffer(); // _error = true; //} //_serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 5, 0); } } if (!readConnectText.Contains("0 messages") && !_error) { // ReceiveMessages(""); } if (_Areas != null && !_error) { foreach (string area in _Areas) { // ReceiveMessages(area); } } //SendMessageReceipts(); // Send message receipts await _serialPort.WriteAsync("B\r\x05"); // Disconnect from BBS (JNOS) //readText = await _serialPort.ReadLine(); // Read command //Debug.WriteLine(readText); //log.Info(readText); Disconnect: //readText = await _serialPort.ReadLine(); // Read disconnect response //Debug.WriteLine(readText); //log.Info(readText); BBSDisconnectTime = DateTime.Now; //serialPort.Write(cmd, 0, 1); // Ctrl-C to return to cmd mode. NOT for Kenwood SendMessageReceipts(); // TODO testing _serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 5, 0); readCmdText = await _serialPort.ReadToAsync(_TNCPrompt); // Next command //Debug.WriteLine(readCmdText + _TNCPrompt); // Send PostCommands string postCommands = _tncDevice.InitCommands.Postcommands; string[] postCommandLines = postCommands.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); _connectState = ConnectState.ConnectStatePost; foreach (string commandLine in postCommandLines) { await _serialPort.WriteAsync(commandLine + "\r"); readText = await _serialPort.ReadLineAsync(); // Read command //log.Info(readCmdText + _TNCPrompt + readText); //readText = await _serialPort.ReadLine(); // Command result //log.Info(readText); readCmdText = await _serialPort.ReadToAsync(_TNCPrompt); // Next command } // Enter converse mode and send FCC call sign _connectState = ConnectState.ConnectStateConverseMode; await _serialPort.WriteAsync(_tncDevice.Commands.Conversmode + "\r"); readText = await _serialPort.ReadLineAsync(); // Read command //log.Info(readCmdText + _TNCPrompt + readText); string fccId = $"FCC Station ID = {ViewModels.SettingsPageViewModel.IdentityPartViewModel.UserCallsign}"; await _serialPort.WriteAsync(fccId + "\r"); readText = await _serialPort.ReadLineAsync(); //log.Info(readText); await _serialPort.WriteAsync("\x03\r"); // Ctrl-C exits converse mode readCmdText = await _serialPort.ReadToAsync(_TNCPrompt); //log.Info(readCmdText + _TNCPrompt); } catch (Exception e) { //Debug.WriteLineLine($"Serial port exception: {e.GetType().ToString()}"); log.Error($"Serial port exception. Connect state: {Enum.Parse(typeof(ConnectState), _connectState.ToString())}.", e); if (_connectState == ConnectState.ConnectStateBBSTryConnect) { //await _serialPort.Write("XM 0\r\x05"); await Utilities.ShowMessageDialogAsync("It appears that the radio is tuned to the wrong frequency,\nor the BBS was out of reach", "BBS Connect Error"); throw; } else if (_connectState == ConnectState.ConnectStatePrepareTNCType) { //MessageDialog.Show("Unable to connect to the TNC.\nIs the TNC on?\nFor Kenwood; is the radio in \"packet12\" mode?", "BBS Connect Error", MessageBoxButton.OK); } else if (_connectState == ConnectState.ConnectStateConverseMode) { await Utilities.ShowMessageDialogAsync($"Error sending FCC Identification - {ViewModels.SettingsPageViewModel.IdentityPartViewModel.UserCallsign}.", "TNC Converse Error"); } else if (_connectState == ConnectState.ConnectStateBBSConnected) { await _serialPort.WriteAsync("B\r\x05"); log.Error("BBS Error Disconnect"); } //else if (e.Message.Contains("not exist")) else if (e is IOException) { await Utilities.ShowMessageDialogAsync("Looks like the USB cable to the TNC is disconnected, or the radio is off", "TNC Connect Error"); } else if (e is UnauthorizedAccessException) { await Utilities.ShowMessageDialogAsync($"The COM Port ({_tncDevice.CommPort.Comport}) is in use by another application. ", "TNC Connect Error"); } else { log.Fatal($"Connect state: {Enum.Parse(typeof(ConnectState), _connectState.ToString())} Exception: {e.Message}"); } //_serialPort.Debug.WriteLine("B\r\n"); await Utilities.ShowMessageDialogAsync("Failed to communicate with the TNC"); return(false); } finally { } //CloseDlgWindow(ConnectDlg); return(true); }
private void _UpdateScreenConfiguration() { if (_curState == ConnectState.Connected) { IPAddress address = AvatarServerManager.Instance.serverConfig.Address; int port = AvatarServerManager.Instance.serverConfig.Port; feedbackText.gameObject.SetActive(true); feedbackText.text = string.Format("Connected to {0}:{1}", address.ToString(), port); connectButton.gameObject.SetActive(false); disconnectButton.gameObject.SetActive(true); cancelButton.gameObject.SetActive(true); configButton.gameObject.SetActive(false); connectingIndicator.SetActive(false); } else if (_curState == ConnectState.Disconnected) { feedbackText.gameObject.SetActive(true); if (AvatarServerManager.Instance.serverConfig.IsConfigured) { IPAddress address = AvatarServerManager.Instance.serverConfig.Address; int port = AvatarServerManager.Instance.serverConfig.Port; feedbackText.gameObject.SetActive(true); feedbackText.text = string.Format("Connect to {0}:{1}?", address.ToString(), port); connectButton.gameObject.SetActive(true); disconnectButton.gameObject.SetActive(false); cancelButton.gameObject.SetActive(true); configButton.gameObject.SetActive(true); connectingIndicator.SetActive(false); } else { feedbackText.gameObject.SetActive(true); feedbackText.text = string.Format("Please configure your server address."); connectButton.gameObject.SetActive(false); disconnectButton.gameObject.SetActive(false); cancelButton.gameObject.SetActive(true); configButton.gameObject.SetActive(true); connectingIndicator.SetActive(false); } } else if (_curState == ConnectState.Connecting) { IPAddress address = AvatarServerManager.Instance.serverConfig.Address; int port = AvatarServerManager.Instance.serverConfig.Port; feedbackText.gameObject.SetActive(true); feedbackText.text = string.Format("Connecting to {0}:{1}", address.ToString(), port); connectButton.gameObject.SetActive(false); disconnectButton.gameObject.SetActive(false); cancelButton.gameObject.SetActive(true); configButton.gameObject.SetActive(false); connectingIndicator.SetActive(true); } else if (_curState == ConnectState.ConnectTimeout) { IPAddress address = AvatarServerManager.Instance.serverConfig.Address; int port = AvatarServerManager.Instance.serverConfig.Port; feedbackText.gameObject.SetActive(true); feedbackText.text = string.Format("Could not connect to {0}:{1}", address.ToString(), port); connectButton.gameObject.SetActive(true); disconnectButton.gameObject.SetActive(false); cancelButton.gameObject.SetActive(true); configButton.gameObject.SetActive(true); connectingIndicator.SetActive(false); } else if (_curState == ConnectState.InvalidAddress) { feedbackText.gameObject.SetActive(true); feedbackText.text = "Invalid server address.\nNeed to configure the server address."; connectButton.gameObject.SetActive(false); disconnectButton.gameObject.SetActive(false); cancelButton.gameObject.SetActive(true); configButton.gameObject.SetActive(true); connectingIndicator.SetActive(false); } else { Debug.LogError("[ServerConnectScreen] Connect state " + _curState.ToString() + " is not implemented."); } }