Exemplo n.º 1
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.Frame.CanGoBack)
            {
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
                SystemNavigationManager.GetForCurrentView().BackRequested += Publish_BackRequested;
            }

            this.publisher = new BluetoothLEAdvertisementPublisher();

            ushort id = 0x1234;
            var manufacturerDataWriter = new DataWriter();
            manufacturerDataWriter.WriteUInt16(id);

            var manufacturerData = new BluetoothLEManufacturerData
            {
                CompanyId = 0xFFFE,
                Data = manufacturerDataWriter.DetachBuffer()
            };

            publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            this.Manufacturer = "12-34";

            publisher.Start();
        }
Exemplo n.º 2
0
        public ObservableBluetoothLEBeacon(
            byte[] payload,
            bool useExtendedFormat,
            bool isAnonymous,
            bool includeTxPower,
            Int16?txPower)
        {
            Context = GattSampleContext.Context;

            var payloadString = GattConvert.ToHexString(payload.AsBuffer());

            Name = payloadString.Substring(0, Math.Min(8, payloadString.Length));

            var advertisement = new BluetoothLEAdvertisement();

            advertisement.ManufacturerData.Add(new BluetoothLEManufacturerData(0x0006, payload.AsBuffer()));

            publisher = new BluetoothLEAdvertisementPublisher(advertisement);

            if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 10))
            {
                publisher.UseExtendedAdvertisement = useExtendedFormat;
                publisher.IsAnonymous = isAnonymous;
                publisher.IncludeTransmitPowerLevel        = includeTxPower;
                publisher.PreferredTransmitPowerLevelInDBm = txPower;
            }

            publisher.StatusChanged += Publisher_StatusChanged;
        }
Exemplo n.º 3
0
        private async Task <bool> SendCustomizedMessage(int msec, string message)
        {
            BluetoothLEAdvertisementPublisher publisher = new BluetoothLEAdvertisementPublisher();
            var manufacturerData = new BluetoothLEManufacturerData();

            // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
            manufacturerData.CompanyId = 0xFFFF;

            // Finally set the data payload within the manufacturer-specific section
            // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
            var writer = new DataWriter();
            //UInt16 uuidData = 0x1234;
            //writer.WriteUInt16(uuidData);
            string deviceData = message;

            writer.UnicodeEncoding = UnicodeEncoding.Utf8;
            writer.WriteString(deviceData);

            // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
            manufacturerData.Data = writer.DetachBuffer();

            // Add the manufacturer data to the advertisement publisher:
            publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            publisher.Start();
            await Task.Delay(msec);

            publisher.Stop();
            return(true);
        }
Exemplo n.º 4
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.Frame.CanGoBack)
            {
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
                SystemNavigationManager.GetForCurrentView().BackRequested += Publish_BackRequested;
            }

            this.publisher = new BluetoothLEAdvertisementPublisher();

            ushort id = 0x1234;
            var    manufacturerDataWriter = new DataWriter();

            manufacturerDataWriter.WriteUInt16(id);

            var manufacturerData = new BluetoothLEManufacturerData
            {
                CompanyId = 0xFFFE,
                Data      = manufacturerDataWriter.DetachBuffer()
            };

            publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            this.Manufacturer = "12-34";

            publisher.Start();
        }
Exemplo n.º 5
0
    /// <summary>
    /// Start to broadcast a Bluetooth advertisement.
    /// </summary>
    /// <returns></returns>
    public async Task SetupBluetoothAdvertisement()
    {
        var myIpAddress = GetMyIPAddress();

        OutputBluetoothConnectionMessage("Broadcasting from " + myIpAddress);

        this._connectionMadeTask = new TaskCompletionSource <bool>();

        this._socketListener = new StreamSocketListener();
        await this._socketListener.BindEndpointAsync(
            new HostName(myIpAddress), "8000");

        this._socketListener.ConnectionReceived += OnConnectionReceived;

        _publisher = new BluetoothLEAdvertisementPublisher();

        var manufactureData = new BluetoothLEManufacturerData();

        manufactureData.CompanyId = 0xFFFE;

        manufactureData.Data = WriteToBuffer(
            IPAddress.Parse(myIpAddress),
            8000);

        _publisher.Advertisement.ManufacturerData.Add(manufactureData);
        _publisher.Start();

        await Task.WhenAny(this._connectionMadeTask.Task, Task.Delay(-1));
    }
Exemplo n.º 6
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     // Create and initialize a new publisher instance.
     publisher = new BluetoothLEAdvertisementPublisher();
     watcher = new BluetoothLEAdvertisementWatcher();
     watcher.Received += OnAdvertisementReceived;
 }
Exemplo n.º 7
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     // Create and initialize a new publisher instance.
     publisher         = new BluetoothLEAdvertisementPublisher();
     watcher           = new BluetoothLEAdvertisementWatcher();
     watcher.Received += OnAdvertisementReceived;
 }
Exemplo n.º 8
0
 public void Stop()
 {
     if (this._publisher != null)
     {
         this._publisher.Stop();
         this._publisher = null;
     }
 }
Exemplo n.º 9
0
        protected void startPublisher(byte[] data)
        {
            BluetoothLEAdvertisement advertisement = new BluetoothLEAdvertisement();

            advertisement.ManufacturerData.Add(new BluetoothLEManufacturerData(COMPANY_ID, CryptographicBuffer.CreateFromByteArray(data)));
            m_publisher = new BluetoothLEAdvertisementPublisher(advertisement);
            m_publisher.StatusChanged += publisherStatusChangeHandler;
            m_publisher.Start();
        }
Exemplo n.º 10
0
 public void Stop()
 {
     if (IsStarted)
     {
         _advertisementPublisher.Stop();
         _advertisementPublisher = null;
         IsStarted = false;
     }
     Logger.Debug("Advertiser.Stoped");
 }
Exemplo n.º 11
0
 public void Stop()
 {
     if (IsStarted)
     {
         _advertisementPublisher.Stop();
         _advertisementPublisher = null;
         IsStarted = false;
     }
     Logger.Debug("Advertiser.Stoped");
 }
Exemplo n.º 12
0
        private static void Publisher_StatusChanged(BluetoothLEAdvertisementPublisher sender, BluetoothLEAdvertisementPublisherStatusChangedEventArgs args)
        {
            var sb = new StringBuilder();

            sb.AppendLine($"Handler: {nameof(Publisher_StatusChanged)}");
            sb.AppendLine($"Status: {args.Status.ToString()}");
            sb.AppendLine($"Error: {args.Error.ToString()}");
            sb.AppendLine($"----------------------------------");
            Console.WriteLine(sb.ToString());
        }
Exemplo n.º 13
0
 private async void Publisher_StatusChanged(BluetoothLEAdvertisementPublisher sender, BluetoothLEAdvertisementPublisherStatusChangedEventArgs args)
 {
     if (args.Error != Windows.Devices.Bluetooth.BluetoothError.Success)
     {
         await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
         {
             MessageDialog dialog = new MessageDialog("Error: " + args.Error.ToString(), "Can not start Watcher");
             await dialog.ShowAsync();
         });
     }
 }
        //---------------------------------------------------------------------
        // Method to handle if/when the publisher's status changes
        //---------------------------------------------------------------------

        // Event callback for when the status of the publisher changes. This
        // helps keep the publisher going if it is aborted by the system.
        private void OnPublisherStatusChanged(
            BluetoothLEAdvertisementPublisher publisher,
            BluetoothLEAdvertisementPublisherStatusChangedEventArgs eventArgs
            )
        {
            if (eventArgs.Status == BluetoothLEAdvertisementPublisherStatus.Aborted)
            {
                Debug.WriteLine("Advertisemen publisher aborted. Restarting.");
                publisher.Start();
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Invoked as an event handler when the status of the publisher changes.
        /// </summary>
        /// <param name="publisher">Instance of publisher that triggered the event.</param>
        /// <param name="eventArgs">Event data containing information about the publisher status change event.</param>
        private async void OnPublisherStatusChanged(
            BluetoothLEAdvertisementPublisher publisher,
            BluetoothLEAdvertisementPublisherStatusChangedEventArgs eventArgs)
        {
            // This event handler can be used to monitor the status of the publisher.
            // We can catch errors if the publisher is aborted by the system
            BluetoothLEAdvertisementPublisherStatus status = eventArgs.Status;
            BluetoothError error = eventArgs.Error;

            StatusChanged?.Invoke(publisher, eventArgs);
        }
Exemplo n.º 16
0
        protected void stopPublisher()
        {
            if (null == m_publisher)
            {
                m_logger.WriteLine("Publisher is not active");
                return;
            }

            m_publisher.Stop();
            m_publisher.StatusChanged -= publisherStatusChangeHandler; // unregister handler
            m_publisher = null;
        }
Exemplo n.º 17
0
        public void Start()
        {
            // Create and initialize a new publisher instance.
            this._publisher = new BluetoothLEAdvertisementPublisher();

            // Attach a event handler to monitor the status of the publisher, which
            // can tell us whether the advertising has been serviced or is waiting to be serviced
            // due to lack of resources. It will also inform us of unexpected errors such as the Bluetooth
            // radio being turned off by the user.
            this._publisher.StatusChanged += OnPublisherStatusChanged;

            // We need to add some payload to the advertisement. A publisher without any payload
            // or with invalid ones cannot be started. We only need to configure the payload once
            // for any publisher.

            // Add a manufacturer-specific section:
            // First, let create a manufacturer data section
            var manufacturerData = new BluetoothLEManufacturerData();

            // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
            manufacturerData.CompanyId = ManufacturerId;

            // Finally set the data payload within the manufacturer-specific section
            // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
            var    writer   = new DataWriter();
            UInt16 uuidData = 0x1234;

            writer.WriteUInt16(uuidData);

            // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
            manufacturerData.Data = writer.DetachBuffer();

            // Add the manufacturer data to the advertisement publisher:
            this._publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            // From old code (Which is not commented)
            var data = new BluetoothLEAdvertisementDataSection {
                Data = SolicitationData.AsBuffer()
            };

            this._publisher.Advertisement.DataSections.Add(data);

            try
            {
                // Calling publisher start will start the advertising if resources are available to do so
                this._publisher.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 18
0
        private void PublishiBeacon(byte[] dataArray)
        {
            var manufactureData = new BluetoothLEManufacturerData();

            //0x004C	Apple, Inc.
            manufactureData.CompanyId = 0x004c;
            //using System.Runtime.InteropServices.WindowsRuntime;
            manufactureData.Data = dataArray.AsBuffer();
            _blePublisher        = new BluetoothLEAdvertisementPublisher();
            _blePublisher.Advertisement.ManufacturerData.Add(manufactureData);
            //開始發佈
            _blePublisher.Start();
        }
Exemplo n.º 19
0
        public void Emit()
        {
            publisher = new BluetoothLEAdvertisementPublisher();
            var manufacturerData = new BluetoothLEManufacturerData();
            manufacturerData.CompanyId = 0xFFFE;
            var writer = new DataWriter();
            UInt16 uuidData = 0x1234;
            writer.WriteUInt16(uuidData);
            manufacturerData.Data = writer.DetachBuffer();
            publisher.Advertisement.ManufacturerData.Add(manufacturerData);
            publisher.Start();

        }
Exemplo n.º 20
0
        public Advertiser()
        {        
            var manufacturerData = new BluetoothLEManufacturerData(ManufacturerId, (new byte[] { 0x12, 0x34 }).AsBuffer());

            var advertisment = new BluetoothLEAdvertisement();

            var data = new BluetoothLEAdvertisementDataSection {Data = SolicitationData.AsBuffer()};

            advertisment.DataSections.Add(data);
            advertisment.ManufacturerData.Add(manufacturerData);

            this._publisher = new BluetoothLEAdvertisementPublisher(advertisment);
        }
Exemplo n.º 21
0
    /// <summary>
    /// Stop all Bluetooth broadcasting and watching
    /// </summary>
    void StopBroadcastingOrWatching()
    {
        if (_publisher != null)
        {
            _publisher.Stop();
            _publisher = null;
        }

        if (_watcher != null)
        {
            _watcher.Stop();
            _watcher = null;
        }
    }
Exemplo n.º 22
0
        public BLE()
        {
            publisher = new BluetoothLEAdvertisementPublisher();
            publisher.StatusChanged += OnPublisherStatusChanged;

            //generate new random iBeacon numbers
            Random rnd = new Random();

            iBeaconMajor = (ushort)rnd.Next(0, 65535);
            iBeaconMinor = (ushort)rnd.Next(0, 65535);

            //random 4 digits added to manufacturer specific advertisement text
            randomForManufacturerSpecific = Convert.ToString(rnd.Next(1000, 9999));
        }
Exemplo n.º 23
0
        public Advertiser()
        {
            var manufacturerData = new BluetoothLEManufacturerData(ManufacturerId, (new byte[] { 0x12, 0x34 }).AsBuffer());

            var advertisment = new BluetoothLEAdvertisement();

            var data = new BluetoothLEAdvertisementDataSection {
                Data = SolicitationData.AsBuffer()
            };

            advertisment.DataSections.Add(data);
            advertisment.ManufacturerData.Add(manufacturerData);

            this._publisher = new BluetoothLEAdvertisementPublisher(advertisment);
        }
        //---------------------------------------------------------------------
        // Init and ShutDown
        //---------------------------------------------------------------------

        // Initializes the publisher and begins publishing advertisements
        public void Start()
        {
            //
            // Step 1
            // Create the publisher
            //
            publisher = new BluetoothLEAdvertisementPublisher();

            //
            // Step 2
            // Add a payload to the advertisement. It must be less than 20
            // bytes or an exception will occur.
            //
            BluetoothLEManufacturerData manufacturerData = new BluetoothLEManufacturerData();

            // Add a manufacturer ID
            manufacturerData.CompanyId = 0xDEDE;    // Another reference to King DeDeDe

            // Add a string
            DataWriter writer = new DataWriter();

            writer.WriteString("IPv6ToBle");

            manufacturerData.Data = writer.DetachBuffer();

            // Add the manufacturer data to the publisher
            publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            // Register a status changed handler in case something happens to
            // the publisher
            publisher.StatusChanged += OnPublisherStatusChanged;

            // Start the publisher if resources are available to do so. It may
            // take a second to get started. This cannot run if other code is
            // using the Bluetooth radio, such as the GATT server.
            publisher.Start();

            if (publisher.Status == BluetoothLEAdvertisementPublisherStatus.Started)
            {
                Debug.WriteLine("Packet receiver advertisement publisher started.");
            }
            else
            {
                Debug.WriteLine("An error occurred when starting the advertisement" +
                                "publisher. Status: " + publisher.Status.ToString()
                                );
            }
        }
Exemplo n.º 25
0
        private void initPublisher()
        {
            publisher = new BluetoothLEAdvertisementPublisher();

            var manufacturerData = new BluetoothLEManufacturerData();

            manufacturerData.CompanyId = COMPANY_ID;

            var    writer   = new DataWriter();
            UInt16 uuidData = 0x0001;

            writer.WriteUInt16(uuidData);
            manufacturerData.Data = writer.DetachBuffer();

            publisher.Advertisement.ManufacturerData.Add(manufacturerData);
        }
Exemplo n.º 26
0
        public BeaconManagementService()
        {
            _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            // Create the Bluetooth LE watcher from the Windows 10 UWP
            _watcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active };

            // Create the Bluetooth LE publisher from the Windows 10 UWP
            _publisher = new BluetoothLEAdvertisementPublisher();

            // Construct the Universal Bluetooth Beacon manager
            _beaconManager = new BeaconManager();
            BeaconsList = _beaconManager.BluetoothBeacons;

            _resourceLoader = ResourceLoader.GetForCurrentView();
            StartScanning();
        }
Exemplo n.º 27
0
        /// <summary>
        /// Invoked as an event handler when the status of the publisher changes.
        /// </summary>
        /// <param name="publisher">Instance of publisher that triggered the event.</param>
        /// <param name="eventArgs">Event data containing information about the publisher status change event.</param>
        private async void OnAdvertiserStatusChanged(
            BluetoothLEAdvertisementPublisher publisher,
            BluetoothLEAdvertisementPublisherStatusChangedEventArgs eventArgs)
        {
            // This event handler can be used to monitor the status of the publisher.
            // We can catch errors if the publisher is aborted by the system
            BluetoothLEAdvertisementPublisherStatus status = eventArgs.Status;
            BluetoothError error = eventArgs.Error;

            if (error == BluetoothError.Success)
            {
                setStatus(status.ToString());

                switch (status)
                {
                case BluetoothLEAdvertisementPublisherStatus.Started:
                    setStatus("Connecting...");
                    try
                    {
                        var connectionTask   = this.AncsManager.Connect();
                        var connectionResult = await connectionTask;

                        //var connectionResult = await this.AncsManager.Connect();
                        if (connectionResult == true)
                        {
                            setStatus("Waiting for device...");
                        }
                        else
                        {
                            setStatus("No suitable device");
                        }
                    }
                    catch (Exception ex)
                    {
                        setStatus(ex.Message);
                    }

                    break;
                }
            }
            else
            {
                setStatus(String.Format("Error: {0}", error.ToString()));
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Invoked as an event handler when the status of the publisher changes.
        /// </summary>
        /// <param name="publisher">Instance of publisher that triggered the event.</param>
        /// <param name="eventArgs">Event data containing information about the publisher status change event.</param>
        private async void OnPublisherStatusChanged(
            BluetoothLEAdvertisementPublisher publisher,
            BluetoothLEAdvertisementPublisherStatusChangedEventArgs eventArgs)
        {
            // This event handler can be used to monitor the status of the publisher.
            // We can catch errors if the publisher is aborted by the system
            BluetoothLEAdvertisementPublisherStatus status = eventArgs.Status;
            BluetoothError error = eventArgs.Error;

            // Update the publisher status displayed in the sample
            // Serialize UI update to the main UI thread
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                PublisherStatusBlock.Text = string.Format("Published Status: {0}, Error: {1}",
                                                          status.ToString(),
                                                          error.ToString());
            });
        }
Exemplo n.º 29
0
        private async void OnPublisherStatusChangedAsync(BluetoothLEAdvertisementPublisher sender, BluetoothLEAdvertisementPublisherStatusChangedEventArgs args)
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                System.Diagnostics.Debug.WriteLine("Bluetooth LE Advertisement Publisher status changed to "
                                                   + args.Status);

                if (args.Status == BluetoothLEAdvertisementPublisherStatus.Aborted)
                {
                    // Aborted status most likely means that Bluetooth is not enabled (i.e. turned off)
                    MessageDialog messageDialog = new MessageDialog("Bluetooth LE Advertisement Publisher aborted. Make sure you have Bluetooth turned on on your device and try again.");
                    await messageDialog.ShowAsync();
                }

                IsPublisherStarted = (args.Status == BluetoothLEAdvertisementPublisherStatus.Started);
            });
        }
Exemplo n.º 30
0
        public BeaconManagementService()
        {
            _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            // Create the Bluetooth LE watcher from the Windows 10 UWP
            _watcher = new BluetoothLEAdvertisementWatcher {
                ScanningMode = BluetoothLEScanningMode.Active
            };

            // Create the Bluetooth LE publisher from the Windows 10 UWP
            _publisher = new BluetoothLEAdvertisementPublisher();

            // Construct the Universal Bluetooth Beacon manager
            _beaconManager = new BeaconManager();
            BeaconsList    = _beaconManager.BluetoothBeacons;

            _resourceLoader = ResourceLoader.GetForCurrentView();
            StartScanning();
        }
Exemplo n.º 31
0
        private void Publisher_StatusChanged(BluetoothLEAdvertisementPublisher sender,
                                             BluetoothLEAdvertisementPublisherStatusChangedEventArgs args)
        {
            Debug.WriteLine(args.Status);
            Debug.WriteLine(args.Error);
            lock (lockObject)
            {
                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    switch (args.Status)
                    {
                    case BluetoothLEAdvertisementPublisherStatus.Waiting:
                        TransitionToStarting.Begin();
                        state = DisplayStates.Wait;
                        break;

                    case BluetoothLEAdvertisementPublisherStatus.Started:
                        TransitionToBroad.Begin();
                        state = DisplayStates.Good;
                        break;

                    case BluetoothLEAdvertisementPublisherStatus.Stopping:
                        TransitionToStarting.Begin();
                        state = DisplayStates.Wait;
                        break;

                    case BluetoothLEAdvertisementPublisherStatus.Stopped:
                        Stop.Begin();
                        state = DisplayStates.Done;
                        break;

                    case BluetoothLEAdvertisementPublisherStatus.Created:
                        break;

                    case BluetoothLEAdvertisementPublisherStatus.Aborted:
                        TransitionToError.Begin();
                        state = DisplayStates.Error;
                        break;
                    }
                    Status.Text = args.Status.ToString();
                }).AsTask().Wait();
            }
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            BluetoothLEAdvertisementPublisher publisher = new BluetoothLEAdvertisementPublisher();

            var manufacturerData = new BluetoothLEManufacturerData();

            manufacturerData.CompanyId = 0xFFFE;

            var writer = new DataWriter();

            writer.WriteString("f**k you blair");

            manufacturerData.Data = writer.DetachBuffer();

            publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            publisher.Start();

            BluetoothLEAdvertisementWatcher xwatcher = new BluetoothLEAdvertisementWatcher();
            var filter = new BluetoothLEManufacturerData();

            filter.CompanyId = 0xFFFE;
            xwatcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(filter);
            xwatcher.Received += OnAdvertisementReceived;
            xwatcher.Start();

            async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
            {
                foreach (var arg in eventArgs.Advertisement.ManufacturerData)
                {
                    var data = new byte[arg.Data.Length];
                    using (var reader = DataReader.FromBuffer(arg.Data))
                    {
                        reader.ReadBytes(data);
                    }
                    var str = Encoding.ASCII.GetString(data);
                    Console.WriteLine(str);
                }
            }

            Console.ReadLine();
        }
Exemplo n.º 33
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public Scenario2_Publisher()
        {
            this.InitializeComponent();

            // Create and initialize a new publisher instance.
            publisher = new BluetoothLEAdvertisementPublisher();

            // We need to add some payload to the advertisement. A publisher without any payload
            // or with invalid ones cannot be started. We only need to configure the payload once
            // for any publisher.

#if ENABLE_ORIGINALCODE
            // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
            // manufacturerData.CompanyId = 0xFFFE;
            manufacturerData.CompanyId = companyId;

            // Finally set the data payload within the manufacturer-specific section
            // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
            var writer = new DataWriter();
            //UInt16 uuidData = 0x1234;
            //writer.WriteUInt16(uuidData);
            string deviceData = "Beacon02";
            writer.UnicodeEncoding = UnicodeEncoding.Utf8;
            writer.WriteString(deviceData);

            // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
            manufacturerData.Data = writer.DetachBuffer();

            // Add the manufacturer data to the advertisement publisher:
            publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            // Display the information about the published payload
            PublisherPayloadBlock.Text = string.Format("Published payload information: CompanyId=0x{0}, ManufacturerData=0x{1}",
                                                       manufacturerData.CompanyId.ToString("X"),
                                                       //uuidData.ToString("X"));
                                                       deviceData);
#endif
            // Display the current status of the publisher
            PublisherStatusBlock.Text = string.Format("Published Status: {0}, Error: {1}",
                                                      publisher.Status,
                                                      BluetoothError.Success);
        }
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public Scenario2_Publisher()
        {
            this.InitializeComponent();

            // Create and initialize a new publisher instance.
            publisher = new BluetoothLEAdvertisementPublisher();

            // We need to add some payload to the advertisement. A publisher without any payload
            // or with invalid ones cannot be started. We only need to configure the payload once
            // for any publisher.

            // Add a manufacturer-specific section:
            // First, let create a manufacturer data section
            var manufacturerData = new BluetoothLEManufacturerData();

            // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
            manufacturerData.CompanyId = 0x004C;

            // Finally set the data payload within the manufacturer-specific section
            // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
            var writer = new DataWriter();
            //UInt16 uuidData = 0x1234;
            //writer.WriteUInt16(uuidData);

            writer.WriteBytes(BleData.ReceivedData);
            // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
            manufacturerData.Data = writer.DetachBuffer();

            // Add the manufacturer data to the advertisement publisher:
            publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            // Display the information about the published payload
            PublisherPayloadBlock.Text = string.Format("Published payload information: CompanyId=0x{0}, ManufacturerData=0x{1}",
                manufacturerData.CompanyId.ToString("X"),
                BitConverter.ToString(BleData.ReceivedData));

            // Display the current status of the publisher
            PublisherStatusBlock.Text = string.Format("Published Status: {0}, Error: {1}",
                publisher.Status,
                BluetoothError.Success);
        }
Exemplo n.º 35
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var manufacturerData =
                new BluetoothLEManufacturerData();

            var writer = new DataWriter();

            writer.WriteString("Buy our socks for a dollar");
            manufacturerData.CompanyId = 0xFFFE;
            manufacturerData.Data      = writer.DetachBuffer();

            publisher =
                new BluetoothLEAdvertisementPublisher();

            publisher.Advertisement.ManufacturerData.Add(manufacturerData);
            publisher.StatusChanged += Publisher_StatusChanged;

            publisher.Start();

            base.OnNavigatedTo(e);
        }
Exemplo n.º 36
0
        private void BeaconPublishButton_Click(object sender, RoutedEventArgs e)
        {
            _publisher = new BluetoothLEAdvertisementPublisher();

            // Manufacturer specific data to customize
            var          writer   = new DataWriter();
            const ushort uuidData = 0x1234; // Custom payload

            writer.WriteUInt16(uuidData);
            var manufacturerData = new BluetoothLEManufacturerData
            {
                CompanyId = 0xFFFE,         // Custom manufacturer
                Data      = writer.DetachBuffer()
            };

            _publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            // Start publishing
            _publisher.Start();
            SetStatusOutput("Publishing Bluetooth Beacon");
        }
Exemplo n.º 37
0
        /// <summary>
        /// Starts advertizing based on the set values (beacon ID 1, ID 2 and ID 3).
        /// Note that this method does not validate the values and will throw exception, if the
        /// values are invalid.
        /// </summary>
        public void Start()
        {
            if (!IsStarted)
            {
                _beacon = new Beacon();
                _beacon.Id1 = BeaconId1;
                _beacon.ManufacturerId = ManufacturerId;
                _beacon.Code = BeaconCode;
                _beacon.Id2 = BeaconId2;
                _beacon.Id3 = BeaconId3;
                _beacon.MeasuredPower = DefaultMeasuredPower;

                _advertisementPublisher = new BluetoothLEAdvertisementPublisher();

                BluetoothLEAdvertisementDataSection dataSection = BeaconFactory.BeaconToSecondDataSection(_beacon);
                Logger.Debug("Advertiser.Start(): " + BeaconFactory.DataSectionToRawString(dataSection));
                _advertisementPublisher.Advertisement.DataSections.Add(dataSection);
                _advertisementPublisher.Start();

                IsStarted = true;
            }
        }
Exemplo n.º 38
0
        private void initPublisher()
        {
            publisher = new BluetoothLEAdvertisementPublisher();

            var manufacturerData = new BluetoothLEManufacturerData();
            manufacturerData.CompanyId = COMPANY_ID;

            var writer = new DataWriter();
            UInt16 uuidData = 0x0001;
            writer.WriteUInt16(uuidData);
            manufacturerData.Data = writer.DetachBuffer();

            publisher.Advertisement.ManufacturerData.Add(manufacturerData);


        }
Exemplo n.º 39
0
        private async void Publisher_StatusChanged(BluetoothLEAdvertisementPublisher sender, BluetoothLEAdvertisementPublisherStatusChangedEventArgs args)
        {
            if (args.Error != Windows.Devices.Bluetooth.BluetoothError.Success)
            {
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                {
                    MessageDialog dialog = new MessageDialog("Error: " + args.Error.ToString(), "Can not start Watcher");
                    await dialog.ShowAsync();
                });

            }
        }
Exemplo n.º 40
0
 private void InitializeAdvertiser()
 {
     _bluetoothLEAdvertisementPublisher = new BluetoothLEAdvertisementPublisher();
     _bluetoothLEAdvertisementPublisher.StatusChanged += OnPublisherStatusChangedAsync;
 }
Exemplo n.º 41
0
        private async void OnPublisherStatusChangedAsync(BluetoothLEAdvertisementPublisher sender, BluetoothLEAdvertisementPublisherStatusChangedEventArgs args)
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                {
                    System.Diagnostics.Debug.WriteLine("Bluetooth LE Advertisement Publisher status changed to "
                        + args.Status);

                    if (args.Status == BluetoothLEAdvertisementPublisherStatus.Aborted)
                    {
                        // Aborted status most likely means that Bluetooth is not enabled (i.e. turned off)
                        MessageDialog messageDialog = new MessageDialog("Bluetooth LE Advertisement Publisher aborted. Make sure you have Bluetooth turned on on your device and try again.");
                        await messageDialog.ShowAsync();
                    }

                    IsPublisherStarted = (args.Status == BluetoothLEAdvertisementPublisherStatus.Started);
                });
        }
Exemplo n.º 42
0
		public void Stop()
		{
			if (IsStarted)
			{
				_advertisementPublisher.Stop();
				_advertisementPublisher = null;
				IsStarted = false;
			}
		}
 public BluetoothLEAdvertisementPublisherEvents(BluetoothLEAdvertisementPublisher This)
 {
     this.This = This;
 }
Exemplo n.º 44
0
        private void BeaconPublishButton_Click(object sender, RoutedEventArgs e)
        {
            _publisher = new BluetoothLEAdvertisementPublisher();

            // Manufacturer specific data to customize
            var writer = new DataWriter();
            const ushort uuidData = 0x1234; // Custom payload
            writer.WriteUInt16(uuidData);
            var manufacturerData = new BluetoothLEManufacturerData
            {
                CompanyId = 0xFFFE,         // Custom manufacturer
                Data = writer.DetachBuffer()
            };
            _publisher.Advertisement.ManufacturerData.Add(manufacturerData);

            // Start publishing
            _publisher.Start();
            SetStatusOutput("Publishing Bluetooth Beacon");
        }
        /// <summary>
        /// Invoked as an event handler when the status of the publisher changes.
        /// </summary>
        /// <param name="publisher">Instance of publisher that triggered the event.</param>
        /// <param name="eventArgs">Event data containing information about the publisher status change event.</param>
        private async void OnPublisherStatusChanged(
            BluetoothLEAdvertisementPublisher publisher,
            BluetoothLEAdvertisementPublisherStatusChangedEventArgs eventArgs)
        {
            // This event handler can be used to monitor the status of the publisher.
            // We can catch errors if the publisher is aborted by the system
            BluetoothLEAdvertisementPublisherStatus status = eventArgs.Status;
            BluetoothError error = eventArgs.Error;

            // Update the publisher status displayed in the sample
            // Serialize UI update to the main UI thread
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                PublisherStatusBlock.Text = string.Format("Published Status: {0}, Error: {1}",
                    status.ToString(),
                    error.ToString());
            });
        }