private async void streamSwitch_Toggled(object sender, RoutedEventArgs e) { int aCount = 0; // Callback counter var model = (DataContext as MainViewModel).MyModel; if (streamSwitch.IsOn) { back.IsEnabled = false; // Disable the back button metawear.OnUnexpectedDisconnect = async () => { Console.WriteLine("Unexpectedly lost connection"); var dialog = new MessageDialog("Unexpectedly lost Bluetooth connection - exit & restart program", "Bluetooth Connection lost"); dialog.Options = MessageDialogOptions.None; dialog.Commands.Add(new UICommand("OK", cmd => { })); dialog.DefaultCommandIndex = 0; dialog.CancelCommandIndex = 0; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => dialog.ShowAsync()); }; // Make sure the Q's are empty ... IMUDataQ.Clear(); tokenSource = new CancellationTokenSource(); dpCT = tokenSource.Token; // Kick off the task to process pairs of datum .... dpTask = Task.Run(() => ProcessData(dpCT, false, 1)); // Run the Processing task on the new IMUDataQ data until cancelled // Set up the device ... sensorFusion = metawear.GetModule(); sensorFusion.Configure(Mode.Ndof, AccRange._2g, GyroRange._250dps); // Set up the callback function for Linear Acceleration data stream ... await sensorFusion.LinearAcceleration.AddRouteAsync(source => source.Stream(data => { FusedIMUPen datum; datum.IMU.tStamp = data.Timestamp; datum.IMU.LinearAcc = data.Value(); IMUDataQ.Enqueue(datum); })); ILed led = metawear.GetModule(); led.EditPattern(MbientLab.MetaWear.Peripheral.Led.Color.Red, Pattern.Solid); // Now that the callback is set up start the data stream on the device ... sensorFusion.LinearAcceleration.Start(); sensorFusion.Start(); led.Play(); } else { // Streaming is switched off ... sensorFusion.Stop(); sensorFusion.LinearAcceleration.Stop(); var led = metawear.GetModule(); led.Stop(true); // Tell the processing task to finish ... Thread.Sleep(100); tokenSource.Cancel(); await dpTask ; // Tidy up the resources on the device metawear.TearDown(); back.IsEnabled = true; // Enable the Back button FusePenDataButton.IsEnabled = true; } }