Example #1
0
        /// <summary>
        /// The entry point of a background task.
        /// </summary>
        /// <param name="taskInstance">The current background task instance.</param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // In this example, the background task simply constructs a message communicated
            // to the App. For more interesting applications, a notification can be sent from here instead.
            _taskInstance           = taskInstance;
            _taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            _deferral = taskInstance.GetDeferral();

            // Store the message in a local settings indexed by this task's name so that the foreground App
            // can display this message.
            ApplicationData.Current.LocalSettings.Values[_taskInstance.Task.Name] = "started";

            string contentId = ApplicationData.Current.LocalSettings.Values[CONTENTID_TAG] as string;

            _receiver = new RemoteMessageReceiver(contentId);
            _receiver._taskInstance = _taskInstance;

            Debug.WriteLine("MessageListenerTask: Run()");

            bool emuAzure     = false;
            byte emuAzureFlag = 0;
            var  settings     = ApplicationData.Current.LocalSettings;

            byte.TryParse(settings.Values[CURRENTSCENARIO_EMUAZURE_TAG] as string, out emuAzureFlag);

            if (emuAzureFlag != 0)
            {
                emuAzure = true;
            }
            if (!emuAzure)
            {
                // create a task to listen for messages
                var ignored = Task.Run(async() =>
                {
                    Debug.WriteLine("MessageListenerTask: Start...");
                    await _receiver.Listen();
                    ApplicationData.Current.LocalSettings.Values[_taskInstance.Task.Name] = "stopped";
                    Debug.WriteLine("MessageListenerTask: Stopped!");
                    _deferral.Complete();
                });
            }
            else
            {
                ApplicationData.Current.LocalSettings.Values[_taskInstance.Task.Name] = "stopped";
                Debug.WriteLine("MessageListenerTask: Stopped!");
                _deferral.Complete();
            }
        }
Example #2
0
        /// <summary>
        /// The entry point of a background task.
        /// </summary>
        /// <param name="taskInstance">The current background task instance.</param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("[WatcherTask] " + DateTime.Now.ToString("hh\\:mm\\:ss\\.fff"));

            backgroundTaskInstance = taskInstance;
            _deferral = taskInstance.GetDeferral();

            var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementWatcherTriggerDetails;

            if (details != null)
            {
                // If the background watcher stopped unexpectedly, an error will be available here.
                var error = details.Error;

                // The Advertisements property is a list of all advertisement events received
                // since the last task triggered. The list of advertisements here might be valid even if
                // the Error status is not Success since advertisements are stored until this task is triggered
                IReadOnlyList <BluetoothLEAdvertisementReceivedEventArgs> advertisements = details.Advertisements;

                // The signal strength filter configuration of the trigger is returned such that further
                // processing can be performed here using these values if necessary. They are read-only here.
                var    rssiFilter = details.SignalStrengthFilter;
                string statusMsg  = DateTime.Now.ToString("hh\\:mm\\:ss\\.fff") + " "
                                    + string.Format("ErrorStatus: {0}, EventCount: {1}, HighDBm: {2}, LowDBm: {3}, Timeout: {4}, Sampling: {5}",
                                                    error.ToString(),
                                                    advertisements.Count.ToString(),
                                                    rssiFilter.InRangeThresholdInDBm.ToString(),
                                                    rssiFilter.OutOfRangeThresholdInDBm.ToString(),
                                                    rssiFilter.OutOfRangeTimeout.GetValueOrDefault().TotalMilliseconds.ToString(),
                                                    rssiFilter.SamplingInterval.GetValueOrDefault().TotalMilliseconds.ToString());
                Debug.WriteLine("---- BTWatcherTask: " + statusMsg);

                // In this example, the background task simply constructs a message communicated
                // to the App. For more interesting applications, a notification can be sent from here instead.
                string eventMessage = "";
                Dictionary <string, BluetoothLEAdvertisementReceivedEventArgs> eventList = new Dictionary <string, BluetoothLEAdvertisementReceivedEventArgs>(advertisements.Count);

                string beaconPrefix = ApplicationData.Current.LocalSettings.Values[BEACONPREFIX_TAG] as string;

                // Advertisements can contain multiple events that were aggregated, each represented by
                // a BluetoothLEAdvertisementReceivedEventArgs object.
                foreach (var eventArgs in advertisements)
                {
                    // Check if there are any manufacturer-specific sections.
                    // If there is, print the raw data of the first manufacturer section (if there are multiple).
                    string manufacturerDataString = "";
                    var    manufacturerSections   = eventArgs.Advertisement.ManufacturerData;
                    if (manufacturerSections.Count > 0)
                    {
                        var manufacturerData = manufacturerSections[0];
                        var data             = new byte[manufacturerData.Data.Length];
                        using (var reader = DataReader.FromBuffer(manufacturerData.Data))
                        {
                            reader.ReadBytes(data);
                        }
                        manufacturerDataString = System.Text.Encoding.UTF8.GetString(data);

                        if (beaconPrefix != null && beaconPrefix.Length > 0)
                        {
                            // case sensitive comparison
                            if (manufacturerDataString.Substring(0, beaconPrefix.Length) != beaconPrefix)
                            {
                                continue;
                            }
                        }
                    }

                    // workaround: filtering abnormal -127 events
                    if (!eventList.ContainsKey(manufacturerDataString))
                    {
                        eventList.Add(manufacturerDataString, eventArgs);
                    }
                    else if (eventArgs.RawSignalStrengthInDBm > -127)
                    {
                        eventList[manufacturerDataString] = eventArgs;
                    }
                }

                foreach (var btevent in eventList)
                {
                    eventMessage += string.Format("{0} {1} {2}\n",
                                                  btevent.Key,
                                                  btevent.Value.RawSignalStrengthInDBm.ToString(),
                                                  btevent.Value.Timestamp.ToString("hh\\:mm\\:ss\\.fff"));
                }

                // Store the message in a local settings indexed by this task's name so that the foreground App
                // can display this message.

                ApplicationData.Current.LocalSettings.Values[taskInstance.Task.Name] = eventMessage.Trim();

                Debug.WriteLine(eventMessage);

                bool emuAzure     = false;
                byte emuAzureFlag = 0;
                byte.TryParse(ApplicationData.Current.LocalSettings.Values[CURRENTSCENARIO_EMUAZURE_TAG] as string, out emuAzureFlag);
                if (emuAzureFlag != 0)
                {
                    emuAzure = true;
                }

                if (!emuAzure)
                {
                    // initial a separate task to send beacon message to cloud
                    var ignored = Task.Run(async() =>
                    {
                        // send message to IoT Hub, no retry...
                        IoTHubMessageSender iotHubMsgSender = new IoTHubMessageSender();
                        try
                        {
                            if (iotHubMsgSender.Init())
                            {
                                foreach (var eventArgs in advertisements)
                                {
                                    var manufacturerSections = eventArgs.Advertisement.ManufacturerData;
                                    if (manufacturerSections.Count > 0)
                                    {
                                        var defaultDataSection = manufacturerSections[0];
                                        var data = new byte[defaultDataSection.Data.Length];
                                        using (var reader = DataReader.FromBuffer(defaultDataSection.Data))
                                        {
                                            reader.ReadBytes(data);
                                        }
                                        string senderDeviceId = System.Text.Encoding.UTF8.GetString(data);
                                        await iotHubMsgSender.sendDataAsync(senderDeviceId, (int)eventArgs.RawSignalStrengthInDBm, eventArgs.Timestamp.UtcDateTime);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("BTWatcherTask.senderLoop Exception: " + ex.Message);
                        }
                        _deferral.Complete();
                    });
                }
                else
                {
                    // simulate a cloud to device message if "emuAzure" enabled
                    if (details != null && details.Error == Windows.Devices.Bluetooth.BluetoothError.Success)
                    {
                        if (eventMessage.Trim().Length > 0)
                        {
                            string contentId = ApplicationData.Current.LocalSettings.Values[CONTENTID_TAG] as string;

                            RemoteMessageReceiver _receiver = new RemoteMessageReceiver(contentId);
                            _receiver.OneshotProcess(rssiFilter.InRangeThresholdInDBm, rssiFilter.OutOfRangeThresholdInDBm);
                        }
                    }
                    _deferral.Complete();
                }
            }
            else
            {
                _deferral.Complete();
            }
        }