private void service_CommandReceived(object sender, BluetoothCommandResponseEventArgs e) { string command = e.Command; Data = command; e.Response = _commands.TryGetValue(command, out var response) ? response : "ERR:COMMAND_UNKNOWN"; }
void OnCommandReceived(BluetoothCommandResponseEventArgs args) { EventHandler <BluetoothCommandResponseEventArgs> ev = CommandReceived; ev?.Invoke(this, args); }
/// <summary> /// Listeners the accept bluetooth client. /// </summary> /// <param name="token"> /// The token. /// </param> private async Task Listener(CancellationTokenSource token) { try { while (true) { if (token.IsCancellationRequested) { return; } // Are we still listening for a client if (_client == null) { _client = _listener.AcceptBluetoothClient(); _stream = _client.GetStream(); } // If we have a client see if there is new data if (_client != null && _stream != null) { Debug.WriteLine($"Client connected = true"); while (true) { if (token.IsCancellationRequested) { return; } if (_stream.DataAvailable) { Debug.WriteLine("Data Available"); byte[] readBuffer = new byte[1024]; int bytesRead = await _stream.ReadAsync(readBuffer, 0, readBuffer.Length); string command = System.Text.Encoding.ASCII.GetString(readBuffer, 0, bytesRead); if (!string.IsNullOrEmpty(command)) { Debug.WriteLine($"Command received: {command}"); BluetoothCommandResponseEventArgs args = new BluetoothCommandResponseEventArgs() { Command = command }; OnCommandReceived(args); Debug.WriteLine($"Sending response: {args.Response}"); var writeBuffer = Encoding.UTF8.GetBytes(args.Response); await _stream.WriteAsync(writeBuffer, 0, writeBuffer.Length); } } else { Thread.Sleep(200); } } } } } catch (Exception ex) { // todo handle the exception // for the sample it will be ignored Debug.WriteLine($"Exception thrown: {ex.Message}"); } }