Esempio n. 1
0
        public async Task GetClipsAsync(ClipType clipType, DeviceInformationDisplay deviceInfoDisplay)
        {
            SentryEventItemsViewSource.Clear();

            if (null == deviceInfoDisplay)
            {
                return;
            }

            var sentryClipsFolder = await deviceInfoDisplay.StorageFolder.GetFolderAsync("TeslaCam\\SentryClips");

            List <string> fileTypeFilter = new List <string>();

            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".png");
            fileTypeFilter.Add(".bmp");
            fileTypeFilter.Add(".gif");

            var query = sentryClipsFolder.CreateFolderQueryWithOptions(new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter));

            var folders = await query.GetFoldersAsync();


            foreach (var folder in folders)
            {
                var thumbSource = folder.Path + @"\thumb.png";
                var jsonPath    = folder.Path + @"\event.json";

                StorageFile sfi = await StorageFile.GetFileFromPathAsync(thumbSource);

                StorageFile json = await StorageFile.GetFileFromPathAsync(jsonPath);

                var thumbImage = await FromStorageFile(sfi);

                var jonText = await StringFromStorageFile(json);

                var clipEvent = new ClipEvent(jonText);

                var files = await folder.GetFilesAsync();

                var videoPaths = new List <string>();

                foreach (var file in files)
                {
                    if (file.FileType != ".mp4")
                    {
                        continue;
                    }

                    videoPaths.Add(file.Path);
                }

                var videos = videoPaths.Select(path => new Video(path)).ToList().AsReadOnly();


                SentryEventItemsViewSource.Add(new Clip(thumbImage, clipEvent, ClipType.Sentry, videos));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Handle background task completion.
        /// </summary>
        /// <param name="task">The task that is reporting completion.</param>
        /// <param name="e">Arguments of the completion report.</param>
        private async void OnBackgroundTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs eventArgs)
        {
            // We get the advertisement(s) processed by the background task
            if (ApplicationData.Current.LocalSettings.Values.Keys.Contains(taskName))
            {
                string backgroundMessage = (string)ApplicationData.Current.LocalSettings.Values[taskName];
                List <BLEAdvertisementInfo> advertisements = JsonConvert.DeserializeObject <List <BLEAdvertisementInfo> >(backgroundMessage);

                BluetoothAdapter defaultBtAdapter = await BluetoothAdapter.GetDefaultAsync();

                string localBtAddress = string.Join(":",
                                                    BitConverter.GetBytes(defaultBtAdapter.BluetoothAddress).Reverse().Select(b => b.ToString("X2"))).Substring(6).ToLower();

                foreach (var advertisement in advertisements)
                {
                    // Display these information on the list
                    advertisement.DeviceInformation = await GetDeviceInfo(localBtAddress, advertisement.ToBtAddressString());
                }

                // Serialize UI update to the main UI thread
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    ReceivedAdvertisementListBox.Items.Add(backgroundMessage);
                    foreach (var advertisement in advertisements)
                    {
                        // Display these information on the list
                        ReceivedAdvertisementListBox.Items.Add(getAdvertisementInfo(advertisement));
                    }


                    // Watcher may have stopped while we were waiting for our chance to run.
                    DeviceInformationDisplay devInfoDisplay = new DeviceInformationDisplay(advertisements[0].DeviceInformation);
                    int devInfoDisplayIndex = resultCollection.IndexOf(devInfoDisplay);
                    if (devInfoDisplayIndex == -1)
                    {
                        resultCollection.Add(devInfoDisplay);

                        // Show Popup
                        var content = new ToastContentBuilder()
                                      .AddToastActivationInfo("picOfHappyCanyon", ToastActivationType.Foreground)
                                      .AddButton("Connect", ToastActivationType.Foreground, devInfoDisplay.DeviceInformation.Id /*$"action=connect&deviceid={devInfoDisplay.DeviceInformation.Id}"*/)
                                      .AddText($"Connect to {devInfoDisplay.DeviceInformation.Id}")
                                      .AddText("Check this out, Happy Canyon in Utah!")
                                      .GetToastContent();

                        // Create the notification
                        var notif = new ToastNotification(content.GetXml());

                        // And show it!
                        ToastNotificationManager.CreateToastNotifier().Show(notif);
                    }
                    else
                    {
                        // Ignore
                    }
                });
            }
        }
Esempio n. 3
0
        private async void TryPair(string val)
        {
            DeviceInformationDisplay _deviceInformationDisplayConnect = ResultCollection.Where(r => r.Id == val).FirstOrDefault();

            DevicePairingKinds ceremoniesSelected = DevicePairingKinds.ConfirmOnly;
            //  ProtectionLevelSelectorInfo protectionLevelInfo = (ProtectionLevelSelectorInfo)protectionLevelComboBox.SelectedItem;

            DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

            DeviceInformationCustomPairing customPairing = _deviceInformationDisplayConnect.DeviceInformation.Pairing.Custom;


            customPairing.PairingRequested += PairingRequestedHandler;

            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            customPairing.PairingRequested -= PairingRequestedHandler;


            StopWatcher();

            var bleDevice = await BluetoothLEDevice.FromIdAsync(_deviceInformationDisplayConnect.Id);



            var accService = await GattDeviceService.FromIdAsync(_deviceInformationDisplayConnect.Id);

            //Get the accelerometer data characteristic
            var accData = accService.GetCharacteristics(new Guid("151c0000-4580-4111-9ca1-5056f3454fbc"))[0];

            //Subcribe value changed

            //accData.ValueChanged += AccData_ValueChanged;
            accData.ValueChanged += test;

            //Set configuration to notify
            await accData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            //Get the accelerometer configuration characteristic
            var accConfig = accService.GetCharacteristics(new Guid("151c0000-4580-4111-9ca1-5056f3454fbc"))[0];

            GattReadResult Resultat = await accConfig.ReadValueAsync();

            var Output = Resultat.Value.ToArray();

            Debug.WriteLine("Acc: " + Output.Count());
            Debug.WriteLine("Registre 0:" + Output[0].ToString());
            Debug.WriteLine("Registre 1:" + Output[1].ToString());

            Output[0] = 0x7F;

            await accConfig.WriteValueAsync(Output.AsBuffer());
        }
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            if (deviceInfoDisp != null)
            {
                PairButton.IsEnabled = false;
                bool paired = true;
                //if (deviceInfoDisp.IsPaired != true)
                //{
                paired = false;
                DevicePairingKinds           ceremoniesSelected = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch;
                DevicePairingProtectionLevel protectionLevel    = DevicePairingProtectionLevel.Default;

                // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

                customPairing.PairingRequested += PairingRequestedHandler;
                DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                customPairing.PairingRequested -= PairingRequestedHandler;

                if (result.Status == DevicePairingResultStatus.Paired)
                {
                    paired = true;
                }
                else
                {
                    //UserOut.Text = "Pairing Failed " + result.Status.ToString();
                }
                //UpdatePairingButtons();
                //}

                if (paired)
                {
                    // device is paired, set up the sensor Tag
                    //UserOut.Text = "Setting up SensorTag";

                    //DeviceInfoConnected = deviceInfoDisp;

                    //Start watcher for Bluetooth LE Services
                    //StartBLEWatcher();
                }
                PairButton.IsEnabled = true;
            }
        }
Esempio n. 5
0
        private async Task PairDevice(DeviceInformationDisplay targetDevice)
        {
            pairSucceed = false;
            if (dispatcherTimer.IsEnabled)
            {
                dispatcherTimer.Stop();
            }

            // Gray out the pair button and results view while pairing is in progress.
            rootPage.Log(String.Format("BT_MANANGER::PairDevice::STATUS:  Pairing with {0} started. Please wait...", targetDevice.Name));

            DevicePairingResult dpr = await targetDevice.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);

            pairSucceed = (dpr.Status == DevicePairingResultStatus.Paired) || (dpr.Status == DevicePairingResultStatus.AlreadyPaired);
            rootPage.Log(
                String.Format("BT_MANANGER::PairDevice::{0}: Pairing result = {1}", pairSucceed ? "STATUS" : "ERROR", dpr.Status.ToString()));

            if (!pairSucceed)
            {
                dispatcherTimer.Start();
            }
        }
Esempio n. 6
0
        private async void unpairButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            Debug.WriteLine("Unpair");

            unpairButton.IsEnabled = false;
            DeviceInfoConnected    = null;

            Debug.WriteLine("Disable Sensors");
            for (int i = 0; i < NUM_SENSORS; i++)
            {
                if (serviceList[i] != null)
                {
                    await disableSensor(i);
                }
            }

            Debug.WriteLine("UnpairAsync");
            try
            {
                DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync();

                string unpairResult = $"Unpairing result = {dupr.Status}";
                Debug.WriteLine(unpairResult);
                paringMessageInformationTextBleck.Text = unpairResult;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unpair exception = " + ex.Message);
            }

            for (int i = 0; i < NUM_SENSORS; i++)
            {
                serviceList[i] = null;
            }

            UpdatePairingButtons();
        }
Esempio n. 7
0
 private async void LoadDeviceVideos(DeviceInformationDisplay selectedDevice)
 {
     await _clipsFolderReader.GetClipsAsync(ClipType.Sentry, selectedDevice);
 }
Esempio n. 8
0
        private void InitilizedWatcher()
        {
            handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    var info = new DeviceInformationDisplay(deviceInfo);
                    if (!info.IsPaired && info.CanPair)
                    {
                        ResultCollection.Add(info);
                    }
                });
            });
            deviceWatcher.Added += handlerAdded;

            handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding updated DeviceInformation in the collection and pass the update object
                    // to the Update method of the existing DeviceInformation. This automatically updates the object
                    // for us.
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            deviceInfoDisp.Update(deviceInfoUpdate);

                            //// If the item being updated is currently "selected", then update the pairing buttons
                            ////DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
                            //if (deviceInfoDisp == selectedDeviceInfoDisp)
                            //{
                            //    //UpdatePairingButtons();
                            //}
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Updated += handlerUpdated;

            handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    // Find the corresponding DeviceInformation in the collection and remove it
                    foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
                    {
                        if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
                        {
                            ResultCollection.Remove(deviceInfoDisp);
                            break;
                        }
                    }
                });
            });
            deviceWatcher.Removed += handlerRemoved;

            handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    foreach (var item in ResultCollection)
                    {
                        Debug.WriteLine(String.Format("Name         = {0}", item.Name));
                        Debug.WriteLine(String.Format("Id           = {0}", item.Id));
                        Debug.WriteLine(String.Format("NameIsPaired = {0}", item.IsPaired));
                        listView.ItemsSource       = ResultCollection.Select(s => new { s.Name, s.Id });
                        listView.DisplayMemberPath = "Name";
                        listView.SelectedValuePath = "Id";
                    }


                    enumberationCompletedEvent.StopEventHandle += EnumberationCompletedEvent_StopEventHandle;
                    EnumberationCompletedEventArgs args         = new EnumberationCompletedEventArgs();
                    args.Button       = btnStart;
                    args.ProgressRing = progressRing;
                    args.TextBlock    = lblComplete;
                    enumberationCompletedEvent.EnumberationCompleted(args);
                });
            });
            deviceWatcher.EnumerationCompleted += handlerEnumCompleted;

            handlerStopped = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    //rootPage.NotifyUser(
                    //    String.Format("{0} devices found. Watcher {1}.",
                    //        ResultCollection.Count,
                    //        DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
                    //    NotifyType.StatusMessage);
                });
            });
            deviceWatcher.Stopped += handlerStopped;
        }