예제 #1
0
        public BackgroundManager()
        {
            localSettings = ApplicationData.Current.LocalSettings;
            var configResources = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView("config");

            notificationHubName     = configResources.GetString("NotificationHubName");
            notificationHubEndpoint = configResources.GetString("NotificationHubEndpoint");
            client = DigitServiceBuilder.Get();
        }
예제 #2
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            var details = (GattCharacteristicNotificationTriggerDetails)taskInstance.TriggerDetails;
            var value   = new BatteryStatusConverter().GetValueFromBuffer(details.Value);
            var client  = DigitServiceBuilder.Get();
            await client.LogAsync($"Battery notification. Value: {value}");

            _deferral.Complete();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            GeovisitTriggerDetails visit = (GeovisitTriggerDetails)taskInstance.TriggerDetails;
            var client  = DigitServiceBuilder.Get();
            var reports = visit.ReadReports();
            var msg     = string.Join("\n", reports.Select(r => $"{r.Timestamp} {r.StateChange} {r.Position.Coordinate.Point}").ToArray());
            await client.LogAsync($"Geovisit:\n{msg}");

            _deferral.Complete();
        }
예제 #4
0
        public async void RegisterPushChannel()
        {
            var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

            var oldChannel = (localSettings.Values["PushChannelUri"] as string);

            if (null == oldChannel || oldChannel != channel.Uri)
            {
                var hub    = new NotificationHub(notificationHubName, notificationHubEndpoint);
                var result = await hub.RegisterNativeAsync(channel.Uri);

                if (result.RegistrationId != null)
                {
                    var pushChannelRegistration = new PushChannelRegistration()
                    {
                        Uri = result.RegistrationId
                    };
                    try //retry here because it's one of the calls where the user is active
                    {
                        await client.SetupPushChannelAsync(pushChannelRegistration);
                    }
                    catch (UnauthorizedException)
                    {
                        var authenticationProvider = DigitServiceBuilder.AuthenticationProvider();
                        await authenticationProvider.AuthenticateUser();

                        try
                        {
                            await client.SetupPushChannelAsync(pushChannelRegistration);
                        }
                        catch (UnauthorizedException e)
                        {
                            await client.LogAsync($"Authorization error while push channel registration: {e.Message}", 3);

                            return;
                        }
                    }
                    catch (DigitServiceException s)
                    {
                        await client.LogAsync($"Failed to register notification channel: {s.Message}", 3);

                        return;
                    }
                    localSettings.Values["PushChannelUri"] = channel.Uri;
                    await client.LogAsync($"Successfully registered notification channel {result.RegistrationId}", 1);
                }
                else
                {
                    await client.LogAsync($"Failed to register channel at hub", -1);
                }
            }
        }
예제 #5
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            var          client       = DigitServiceBuilder.Get();
            var          data         = (ActivitySensorTriggerDetails)taskInstance.TriggerDetails;
            var          reports      = data.ReadReports();
            var          last         = reports.OrderByDescending(p => p.Reading.Timestamp).FirstOrDefault();
            var          storedString = ApplicationData.Current.LocalSettings.Values["Activity"] as string;
            ActivityType?stored       = null;

            if (Enum.TryParse(storedString, out ActivityType output))
            {
                stored = output;
            }
            if (null != last)
            {
                ActivityType activity = ActivityType.Idle;
                bool         known    = true;
                switch (last.Reading.Activity)
                {
                case ActivityType.Fidgeting:
                case ActivityType.Idle:
                case ActivityType.Stationary:
                    activity = ActivityType.Idle;
                    break;

                case ActivityType.Biking:
                case ActivityType.InVehicle:
                    activity = ActivityType.InVehicle;
                    break;

                case ActivityType.Walking:
                case ActivityType.Running:
                    activity = ActivityType.Walking;
                    break;

                default:
                    known = false;
                    break;
                }
                if (known && (!stored.HasValue || stored.Value != activity))
                {
                    await client.LogAsync($"{activity}");

                    ApplicationData.Current.LocalSettings.Values["Activity"] = activity.ToString();
                }
            }
            await client.LogAsync(string.Join("\n", reports.Select(r => $"{r.Reading.Activity} Confidence {r.Reading.Confidence} at {r.Reading.Timestamp}")));

            _deferral.Complete();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            object trigger = taskInstance.TriggerDetails;
            var    client  = DigitServiceBuilder.Get();
            var    opts    = new DigitBLEOptions();

            if (opts.IsConfigured)
            {
                var isConnected = (await BluetoothLEDevice.FromIdAsync(opts.DeviceId)).ConnectionStatus == BluetoothConnectionStatus.Connected;
            }
            else
            {
                await client.LogAsync($"Device Connection Task error: no device configured.", 3);
            }
            _deferral.Complete();
        }
예제 #7
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            var client = DigitServiceBuilder.Get();

            try
            {
                var opts = new DigitBLEOptions();
                if (opts.IsConfigured)
                {
                    var bleClient      = new DigitBLEClient(opts);
                    var batteryService = new BatteryService(bleClient, client);
                    await batteryService.TimeTriggeredMeasurement();
                }
            }
            catch (Exception e)
            {
                await client.LogAsync($"Unhandled background exception: {e.Message}", 3);
            }
            _deferral.Complete();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            var details = (BluetoothLEAdvertisementWatcherTriggerDetails)taskInstance.TriggerDetails;
            var client  = DigitServiceBuilder.Get();

            if (details.Advertisements != null && details.Advertisements.Count > 0)
            {
                var packets = details.Advertisements.Select(v => new DigitAdvertisementPacket(v));
                var latest  = packets.OrderByDescending(v => v.Timestamp).First();
                if (!latest.TimeKnown.HasValue || !latest.TimeKnown.Value)
                {
                    var opts = new DigitBLEOptions();
                    if (opts.IsConfigured)
                    {
                        var bleClient = new DigitBLEClient(opts);
                        try
                        {
                            await bleClient.SetTime(DateTime.Now);

                            await client.LogAsync($"Sent current time to watch (advertisement requested)", 1);
                        }
                        catch (DigitBLEExpcetion e)
                        {
                            await client.LogAsync($"Could not send time (advertisement requested): ${e.Message}", 3);
                        }
                    }
                    else
                    {
                        await client.LogAsync($"Adv Task error: no device configured.", 3);
                    }
                }
                if (new AdvertisementWatcherManager().RegisterAdvertisementWatcherTask())
                {
                    await client.LogAsync($"Re-registered advertisement watcher task");
                }
            }
            _deferral.Complete();
        }
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var client = DigitServiceBuilder.Get();

            if (ResultsListView.SelectedItem is BluetoothLEDeviceDisplay selected)
            {
                bool claimed = false;
                try
                {
                    claimed = await client.Device["12345"].ClaimAsync();
                }
                catch (DigitServiceException exc)
                {
                    await client.LogAsync($"Could not claim device: ${exc.Message}");
                }
                if (claimed)
                {
                    var opts = new DigitBLEOptions();
                    opts.StoreDeviceId(selected.Id);
                    DigitId = selected.Id;
                    var  bleClient = new DigitBLEClient(opts);
                    bool paired    = false;
                    try
                    {
                        paired = await bleClient.Pair();
                    }
                    catch (DigitBLEExpcetion ex)
                    {
                        await client.LogAsync($"Pairing failed: {ex.Message}", 3);
                    }
                    var pairInformation = paired ? "(paired)" : "";
                    await client.LogAsync($"Selected device {selected.Id} as digit{pairInformation}.");

                    var man = new BackgroundManager();
                    man.RegisterDeviceConnectionBackgroundTask(selected.Id);
                }
            }
        }
        private async Task ConfigureTasks()
        {
            bool isInternetConnected = NetworkInterface.GetIsNetworkAvailable();

            if (!isInternetConnected)
            {
                ContentDialog noWifiDialog = new ContentDialog
                {
                    Title           = "No Network connection",
                    Content         = "Check your connection and try again.",
                    CloseButtonText = "Ok"
                };
                ContentDialogResult result = await noWifiDialog.ShowAsync();
            }
            else
            {
                var authenticationProvider = DigitServiceBuilder.AuthenticationProvider();
                if (!await authenticationProvider.HasValidAccessToken())
                {
                    await authenticationProvider.AuthenticateUser();
                }
                var client = DigitServiceBuilder.Get();
                var man    = new BackgroundManager();
                if (await man.CheckAccess())
                {
                    man.RegisterPushChannel();
                    man.RegisterPushBackgroundTask();
                    man.RegisterAdvertisementWatcherTask();
                    man.RegisterGeolocationTasks();
                    man.RegisterTimeTriggerTask();
                    //man.RegisterActivityTriggerTask();
                }
                else
                {
                    await client.LogAsync("Background tasks disabled", 3);
                }
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            var client = DigitServiceBuilder.Get();

            try
            {
                RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
                await client.LogAsync($"Received push {notification.Content}");

                var opts = new DigitBLEOptions();


                var content = JsonConvert.DeserializeObject <PushPayload>(notification.Content);
                switch (content.Action)
                {
                case PushActions.MeasureBattery:
                    if (opts.IsConfigured)
                    {
                        var bleClient      = new DigitBLEClient(opts);
                        var batteryService = new BatteryService(bleClient, client);
                        await batteryService.AddBatteryMeasurement();
                    }
                    else
                    {
                        await client.LogAsync($"Push error: no device configured.", 3);
                    }
                    break;

                case PushActions.SendTime:
                    if (opts.IsConfigured)
                    {
                        var bleClient = new DigitBLEClient(opts);
                        try
                        {
                            await bleClient.SetTime(DateTime.Now);
                        }
                        catch (DigitBLEExpcetion e)
                        {
                            await client.LogAsync($"Could not send time: {e.Message}", 3);
                        }
                    }
                    else
                    {
                        await client.LogAsync($"Push error: no device configured.", 3);
                    }
                    break;

                case PushActions.SendLocation:
                    var locationService = new LocationService(client);
                    await locationService.SendCurrentLocation();

                    break;

                default: break;
                }
            }
            catch (Exception e)
            {
                await client.LogAsync($"Unhandled background exception: {e.Message}", 3);
            }
            _deferral.Complete();
        }