BackgroundTasks.AdvertisementWatcherTask.Run C# (CSharp) Method

Run() public method

The entry point of a background task.
public Run ( IBackgroundTaskInstance taskInstance ) : void
taskInstance IBackgroundTaskInstance
return void
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            backgroundTaskInstance = taskInstance;
            var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementWatcherTriggerDetails;
            if (details != null)
            {
                _deferral = backgroundTaskInstance.GetDeferral();
                taskInstance.Canceled += (s, e) => _deferral.Complete();

                var localStorage = ApplicationData.Current.LocalSettings.Values;
                _bridge = new Bridge(localStorage["bridgeIp"].ToString(), localStorage["userId"].ToString()); 
                try
                {
                    _lights = await _bridge.GetLightsAsync();
                }
                catch (Exception)
                {
                    _deferral.Complete();
                    return; 
                }
                foreach(var item in details.Advertisements)
                {
                    Debug.WriteLine(item.RawSignalStrengthInDBm);
                }

                // -127 is a BTLE magic number that indicates out of range. If we hit this, 
                // turn off the lights. Send the command regardless if they are on/off
                // just to be safe, since it will only be sent once.
                if (details.Advertisements.Any(x => x.RawSignalStrengthInDBm == -127))
                {
                    foreach (Light light in _lights)
                    {
                        light.State.On = false;
                        await Task.Delay(250);
                    }
                }
                // If there is no magic number, we are in range. Toggle any lights reporting
                // as off to on. Do not spam the command to lights arleady on. 
                else
                {
                    foreach (Light light in _lights.Where(x => !x.State.On))
                    {
                        light.State.On = true;
                        await Task.Delay(250);
                    }
                }
                // Wait 1 second before exiting to ensure all HTTP requests have sent.
                await Task.Delay(1000);
                _deferral.Complete();
            }
        }
    }
AdvertisementWatcherTask