Exemplo n.º 1
0
        // GattServiceProvider

        private void OnAdvertisementStatusChanged(GattServiceProvider serviceProvider, GattServiceProviderAdvertisementStatusChangedEventArgs args)
        {
            Utils.Info("AdvertisementStatusChanged error: {0} status: {1}", args.Error.ToString(), args.Status.ToString());

            if (mStatus != Status.Advertise)
            {
                return;
            }

            if (args.Status == GattServiceProviderAdvertisementStatus.Started)
            {
                Utils.Info("advertising..");
            }
            else if (args.Error != BluetoothError.Success)
            {
                Utils.Error("error: {0}", args.Error.ToString());

                if (args.Error == BluetoothError.RadioNotAvailable)
                {
                    mCallback.OnBluetoothRequire();
                }

                mServiceProvider.StopAdvertising();

                SetStatus(Status.Ready);

                mCallback.OnFail();
            }
        }
        private async void PublishButton_ClickAsync()
        {
            // Server not initialized yet - initialize it and start publishing
            if (serviceProvider == null)
            {
                var serviceStarted = await ServiceProviderInitAsync();

                if (serviceStarted)
                {
                    rootPage.NotifyUser("Service successfully started", NotifyType.StatusMessage);
                    PublishButton.Content = "Stop Service";
                }
                else
                {
                    rootPage.NotifyUser("Service not started", NotifyType.ErrorMessage);
                }
            }
            else
            {
                // BT_Code: Stops advertising support for custom GATT Service
                serviceProvider.StopAdvertising();
                serviceProvider       = null;
                PublishButton.Content = "Start Service";
            }
        }
        private async Task CreateCharacteristics(GattServiceProvider gattServiceProvider)
        {
            var statusCharacteristicParams = new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Read | GattCharacteristicProperties.Notify,
                WriteProtectionLevel     = GattProtectionLevel.Plain,
                UserDescription          = "Status Characteristic"
            };

            statusCharacteristicParams.PresentationFormats.Add(GattPresentationFormat.FromParts(GattPresentationFormatTypes.Utf8,
                                                                                                GattPresentationFormatExponent,
                                                                                                GattPresentationFormatUnitless,
                                                                                                GattPresentationFormatNamespaceId,
                                                                                                GattPresentationFormatDescription));

            var statusCharacteristicResult = await gattServiceProvider.Service.CreateCharacteristicAsync(
                BluetoothConstants.StatusCharacteristicUuid,
                statusCharacteristicParams);

            if (statusCharacteristicResult.Error != BluetoothError.Success)
            {
                throw new InvalidOperationException($"Failed to create GATT status characteristic with error {statusCharacteristicResult.Error}");
            }

            _statusCharacteristic = statusCharacteristicResult.Characteristic;

            var commandCharacteristicResult = await gattServiceProvider.Service.CreateCharacteristicAsync(
                BluetoothConstants.CommandCharacteristicUuid,
                new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Write
                                           | GattCharacteristicProperties.WriteWithoutResponse,
                WriteProtectionLevel = GattProtectionLevel.Plain,
                UserDescription      = "Command Characteristic"
            });

            if (commandCharacteristicResult.Error != BluetoothError.Success)
            {
                throw new InvalidOperationException($"Failed to create GATT command characteristic with error {commandCharacteristicResult.Error}");
            }

            var brightnessCharacteristicResult = await gattServiceProvider.Service.CreateCharacteristicAsync(
                BluetoothConstants.BrightnessCharacteristicUuid,
                new GattLocalCharacteristicParameters
            {
                CharacteristicProperties = GattCharacteristicProperties.Write
                                           | GattCharacteristicProperties.WriteWithoutResponse,
                WriteProtectionLevel = GattProtectionLevel.Plain,
                UserDescription      = "Brightness Characteristic"
            });

            if (brightnessCharacteristicResult.Error != BluetoothError.Success)
            {
                throw new InvalidOperationException($"Failed to create GATT brightness characteristic with error {brightnessCharacteristicResult.Error}");
            }

            _statusCharacteristic.ReadRequested += StatusCharacteristic_ReadRequested;
            commandCharacteristicResult.Characteristic.WriteRequested    += CommandCharacteristic_WriteRequested;
            brightnessCharacteristicResult.Characteristic.WriteRequested += BrightnessCharacteristic_WriteRequested;
        }
Exemplo n.º 4
0
 private void ServiceProvider_AdvertisementStatusChanged(GattServiceProvider sender, GattServiceProviderAdvertisementStatusChangedEventArgs args)
 {
     if (args.Status != GattServiceProviderAdvertisementStatus.Started)
     {
         IsPublishing = false;
     }
 }
 public void Dispose()
 {
     // Windows BLE seems to get unreliable if services etc aren't disposed correctly.
     if (continueButtonCharacteristic != null)
     {
         continueButtonCharacteristic.ReadRequested            -= readContinueButtonValue;
         continueButtonCharacteristic.SubscribedClientsChanged -= subscribedClientsChanged;
         continueButtonCharacteristic = null;
     }
     if (stopButtonCharacteristic != null)
     {
         stopButtonCharacteristic.ReadRequested -= readStopButtonValue;
         stopButtonCharacteristic = null;
     }
     if (remoteCanContinueCharacteristic != null)
     {
         remoteCanContinueCharacteristic.WriteRequested -= writeRemoteCanContinue;
         remoteCanContinueCharacteristic = null;
     }
     if (remoteCanStopCharacteristic != null)
     {
         remoteCanStopCharacteristic.WriteRequested -= writeRemoteCanStop;
         remoteCanStopCharacteristic = null;
     }
     if (userMessageCharacteristic != null)
     {
         userMessageCharacteristic.WriteRequested -= writeUserMessage;
         userMessageCharacteristic = null;
     }
     if (cascableService != null)
     {
         cascableService.StopAdvertising();
         cascableService = null;
     }
 }
Exemplo n.º 6
0
        private void CleanupInternal()
        {
            if (mStatus == Status.Advertise)
            {
                mServiceProvider.StopAdvertising();
            }

            SetStatus(Status.Invalid);

            if (mInitializationCancelTokenSource != null)
            {
                mInitializationCancelTokenSource.Dispose();
                mInitializationCancelTokenSource = null;
            }

            mUploadCharacteristic   = null;
            mDownloadCharacteristic = null;
            mServiceProvider        = null;

            mSubscribedCentrals.Clear();


            // TODO


            mCallback = null;
            mFinished = true;
        }
Exemplo n.º 7
0
        private void HandleError()
        {
            mUploadCharacteristic   = null;
            mDownloadCharacteristic = null;
            mServiceProvider        = null;

            mCallback.OnFail();
        }
Exemplo n.º 8
0
        internal async Task <bool> Initialize()
        {
            try
            {
                GattServiceProviderResult result = await GattServiceProvider.CreateAsync(_serviceId);

                if (result.Error != BluetoothError.Success)
                {
                    Robot.Message("can't create GATT BlueTooth service with id " + _serviceId.ToString(), MessageType.Error);
                    Robot.Message("without bluetooth service, remote controller won't work", MessageType.Warning);
                    return(_init);
                }
                _service = result.ServiceProvider;

                byte[] value = new byte[] { 0x21 };
                var    constantParameters = new GattLocalCharacteristicParameters
                {
                    CharacteristicProperties = (GattCharacteristicProperties.Read),
                    StaticValue         = value.AsBuffer(),
                    ReadProtectionLevel = GattProtectionLevel.Plain,
                };

                GattLocalCharacteristicResult characteristicResult = await _service.Service.CreateCharacteristicAsync(_notifyId, new GattLocalCharacteristicParameters
                {
                    CharacteristicProperties = GattCharacteristicProperties.Notify,
                    ReadProtectionLevel      = GattProtectionLevel.Plain,
                    StaticValue = value.AsBuffer()
                });

                if (characteristicResult.Error != BluetoothError.Success)
                {
                    Robot.Message("can't create GATT BlueTooth service with id " + _serviceId.ToString(), MessageType.Error);
                    Robot.Message("without bluetooth service, remote controller won't work", MessageType.Warning);
                    return(_init);
                }
                _notifyCharacteristic = characteristicResult.Characteristic;
                //_notifyCharacteristic.SubscribedClientsChanged += _btNotify_SubscribedClientsChanged;

                GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters
                {
                    IsDiscoverable = true,
                    IsConnectable  = true
                };
                _service.StartAdvertising(advParameters);
                Robot.Message("created Bluetooth GATT service with id " + _serviceId.ToString(), MessageType.Success);
                _init = true;
            }
            catch (Exception x)
            {
                while (x != null)
                {
                    Robot.Message(x.Message, MessageType.Error);
                    x = x.InnerException;
                }
                Robot.Message("without bluetooth service, remote controller won't work", MessageType.Warning);
            }
            return(_init);
        }
Exemplo n.º 9
0
        private async void createServiceProvider()
        {
            var result = await GattServiceProvider.CreateAsync(serviceUuid);

            if (result.Error == BluetoothError.Success)
            {
                serviceProvider = result.ServiceProvider;
            }
        }
        private void ServiceProvider_AdvertisementStatusChanged(GattServiceProvider sender, GattServiceProviderAdvertisementStatusChangedEventArgs args)
        {
            // Created - The default state of the advertisement, before the service is published for the first time.
            // Stopped - Indicates that the application has canceled the service publication and its advertisement.
            // Started - Indicates that the system was successfully able to issue the advertisement request.
            // Aborted - Indicates that the system was unable to submit the advertisement request, or it was canceled due to resource contention.

            rootPage.NotifyUser($"New Advertisement Status: {sender.AdvertisementStatus}", NotifyType.StatusMessage);
        }
Exemplo n.º 11
0
        // Assumes that the lock is being held.
        private void PublishService(GattServiceProvider provider)
        {
            var advertisingParameters = new GattServiceProviderAdvertisingParameters
            {
                IsDiscoverable = true,
                IsConnectable  = true // Peripheral role support is required for Windows to advertise as connectable.
            };

            provider.StartAdvertising(advertisingParameters);
        }
 protected override void OnNavigatedFrom(NavigationEventArgs e)
 {
     if (serviceProvider != null)
     {
         if (serviceProvider.AdvertisementStatus != GattServiceProviderAdvertisementStatus.Stopped)
         {
             serviceProvider.StopAdvertising();
         }
         serviceProvider = null;
     }
 }
Exemplo n.º 13
0
        //---------------------------------------------------------------------
        // Method to create the GATT service provider
        //---------------------------------------------------------------------

        // <param name="uuid"> The UUID of the service to create </param>
        protected async Task CreateServiceProvider(Guid uuid)
        {
            GattServiceProviderResult creationResult = await GattServiceProvider.CreateAsync(uuid);

            if (creationResult.Error != BluetoothError.Success)
            {
                throw new CreateServiceException(creationResult);
            }

            ServiceProvider = creationResult.ServiceProvider;
        }
        /// <summary>
        /// Creates the Gatt Service provider
        /// </summary>
        /// <param name="uuid">UUID of the Service to create</param>
        protected async Task CreateServiceProvider(Guid uuid)
        {
            // Create Service Provider - similar to RFCOMM APIs
            GattServiceProviderResult result = await GattServiceProvider.CreateAsync(uuid);

            if (result.Error != BluetoothError.Success)
            {
                throw new CreateServiceException(result);
            }

            ServiceProvider = result.ServiceProvider;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates the Gatt Service provider
        /// </summary>
        /// <param name="uuid">UUID of the Service to create</param>
        protected async Task CreateServiceProvider(Guid uuid)
        {
            // Create Service Provider - similar to RFCOMM APIs
            GattServiceProviderResult result = await GattServiceProvider.CreateAsync(uuid);

            if (result.Error != BluetoothError.Success)
            {
                throw new System.Exception(string.Format($"Error occured while creating the BLE service provider, Error Code:{result.Error}"));
            }

            ServiceProvider = result.ServiceProvider;
        }
 private void ServiceProvider_AdvertisementStatusChanged(GattServiceProvider sender, GattServiceProviderAdvertisementStatusChangedEventArgs args)
 {
     if ((args.Status == GattServiceProviderAdvertisementStatus.Stopped) ||
         (args.Status == GattServiceProviderAdvertisementStatus.Aborted))
     {
         IsAdvertising = false;
     }
     else
     {
         IsAdvertising = true;
     }
 }
Exemplo n.º 17
0
        /// <summary>
        /// 创建服务
        /// </summary>
        private async Task CreateService()
        {
            GattServiceProviderResult result = await GattServiceProvider.CreateAsync(remoteGuid);

            if (result.Error == BluetoothError.Success)
            {
                serviceProvider = result.ServiceProvider;
            }
            else
            {
                throw new Exception();
            }
            CreateCharacteristics();
        }
Exemplo n.º 18
0
        public async Task Build()
        {
            this.native = await GattServiceProvider.CreateAsync(this.Uuid);

            foreach (var ch in this.characteristics)
            {
                await ch.Build(this.native);
            }

            this.native.ServiceProvider.StartAdvertising(new GattServiceProviderAdvertisingParameters
            {
                IsConnectable  = true,
                IsDiscoverable = true
            });
        }
Exemplo n.º 19
0
        private void ServiceProvider_AdvertisementStatusChanged(GattServiceProvider sender, GattServiceProviderAdvertisementStatusChangedEventArgs args)
        {
            Debug.WriteLine($"ServiceProvider ({this.Name}) advertisementstatuschanged : {args.Status}");

            if (args.Status == GattServiceProviderAdvertisementStatus.Started)
            {
                isPublishing = true;
            }
            else
            {
                Debug.WriteLine($"ServiceProvider ({this.Name}) advertisementstatuschanged - ERROR!");
                IsPublishing = false;
                OnPropertyChanged(new PropertyChangedEventArgs("ServiceStartError"));
            }
        }
Exemplo n.º 20
0
 private void UnpublishService(GattServiceProvider provider)
 {
     try
     {
         if ((provider.AdvertisementStatus == GattServiceProviderAdvertisementStatus.Started) ||
             (provider.AdvertisementStatus == GattServiceProviderAdvertisementStatus.Aborted))
         {
             provider.StopAdvertising();
             SubscribedHidClientsChanged?.Invoke(null);
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine("Failed to stop advertising due to: " + e.Message);
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Start up the bl;uetooth listeners, set UUIDs/ble-specific information.
        /// </summary>
        /// <returns></returns>
        private async Task MainAsync()
        {
            // Check if adapter supports peripheral and bluetooth low energy
            peripheralSupported = await CheckPeripheralRoleSupportAsync();

            if (!peripheralSupported)
            {
                Environment.Exit(1);
            }


            if (serviceProvider == null)
            {
                ServiceProviderInitAsync().Wait();
                if (serviceStarted)
                {
                    // Advertising server as connectable and discoverable.
                    advParameters = new GattServiceProviderAdvertisingParameters
                    {
                        // IsConnectable determines whether a call to publish will attempt to start advertising and
                        // put the service UUID in the ADV packet (best effort)
                        IsConnectable  = peripheralSupported,
                        IsDiscoverable = true
                    };

                    // Start server
                    serviceProvider.StartAdvertising(advParameters);


                    this.hasStarted = true;
                    if (this.setIndicate == true)
                    {
                        this.setIndicate = false;
                        Indicate();
                    }
                }
            }
            else
            {
                // Stops advertising support
                serviceProvider.StopAdvertising();
                serviceProvider = null;
            }
        }
Exemplo n.º 22
0
        public async Task Init()
        {
            this.native = await GattServiceProvider.CreateAsync(this.Uuid);

            if (this.native.Error != BluetoothError.Success)
            {
                throw new ArgumentException();
            }

            foreach (var ch in this.Characteristics.OfType <IUwpGattCharacteristic>())
            {
                await ch.Init(this.native.ServiceProvider.Service);
            }

            this.native.ServiceProvider.StartAdvertising(new GattServiceProviderAdvertisingParameters
            {
                IsConnectable  = true,
                IsDiscoverable = true
            });
        }
Exemplo n.º 23
0
        public async Task Initialize()
        {
            var cellaGatService = await GattServiceProvider.CreateAsync(_serviceId);

            if (cellaGatService.Error == BluetoothError.RadioNotAvailable)
            {
                throw new Exception("BLE not enabled");
            }
            ;

            if (cellaGatService.Error == BluetoothError.Success)
            {
                _gattServiceProvider = cellaGatService.ServiceProvider;
            }

            _gattServiceProvider.AdvertisementStatusChanged += async(sender, args) =>
            {
                await _logger.LogMessageAsync(
                    sender.AdvertisementStatus == GattServiceProviderAdvertisementStatus.Started?
                    "GATT server started." :
                    "GATT server stopped.");
            };
        }
Exemplo n.º 24
0
        private async void SetupGatt()
        {
            var ba = await BluetoothAdapter.GetDefaultAsync();

            if (ba == null)
            {
                notifyIcon.Text = String.Format("{0} (No Bluetooth adapter found!)", Application.ProductName);
                return;
            }

            if (!ba.IsPeripheralRoleSupported)
            {
                notifyIcon.Text = String.Format("{0} (Peripheral mode not supported!)", Application.ProductName);
                return;
            }

            var sr = await GattServiceProvider.CreateAsync(SVC_UUID);

            if (sr.Error != BluetoothError.Success)
            {
                notifyIcon.Text = String.Format("{0} (Error creating service!)", Application.ProductName);
                return;
            }
            serviceProvider = sr.ServiceProvider;

            var cr = await serviceProvider.Service.CreateCharacteristicAsync(CHR_UUID, CHR_PARAMS);

            if (cr.Error != BluetoothError.Success)
            {
                notifyIcon.Text = String.Format("{0} (Error creating characteristic!)", Application.ProductName);
                return;
            }
            localCharacteristic = cr.Characteristic;

            localCharacteristic.WriteRequested += CharacteristicWriteRequested;
            serviceProvider.StartAdvertising(ADV_PARAMS);
        }
        internal async Task StartAsync()
        {
            if (_gattServiceProvider == null)
            {
                var serviceProviderResult = await GattServiceProvider.CreateAsync(BluetoothConstants.ServiceUuid);

                if (serviceProviderResult.Error != BluetoothError.Success)
                {
                    throw new InvalidOperationException($"Failed to create GATT service with error {serviceProviderResult.Error}");
                }

                _gattServiceProvider = serviceProviderResult.ServiceProvider;

                await CreateCharacteristics(_gattServiceProvider);
            }

            var advertisingParameters = new GattServiceProviderAdvertisingParameters
            {
                IsConnectable  = (await BluetoothAdapter.GetDefaultAsync())?.IsPeripheralRoleSupported ?? false,
                IsDiscoverable = true
            };

            _gattServiceProvider.StartAdvertising(advertisingParameters);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Check that the service has started, start up the characteristics required for the BLE Service
        /// </summary>
        /// <returns></returns>
        private async Task ServiceProviderInitAsync()
        {
            // Initialize and starting a custom GATT Service
            MainService = await GattServiceProvider.CreateAsync(Constants.serviceProviderUuid);

            if (MainService.Error == BluetoothError.Success)
            {
                serviceProvider = MainService.ServiceProvider;
            }
            else
            {
                // An error occurred.
                serviceStarted = false;
            }

            characteristicResult = await serviceProvider.Service.CreateCharacteristicAsync(Constants.ReadCharacteristicUuid, Constants.gattReadParameters);

            if (characteristicResult.Error != BluetoothError.Success)
            {
                // An error occurred.
                serviceStarted = false;
            }
            readCharacteristic = characteristicResult.Characteristic;
            readCharacteristic.ReadRequested += ReadCharacteristic_ReadRequested;


            characteristicResult = await serviceProvider.Service.CreateCharacteristicAsync(Constants.WriteCharacteristicUuid, Constants.gattWriteParameters);

            if (characteristicResult.Error != BluetoothError.Success)
            {
                // An error occurred.
                serviceStarted = false;
            }
            writeCharacteristic = characteristicResult.Characteristic;
            writeCharacteristic.WriteRequested += WriteCharacteristic_WriteRequested;
        }
Exemplo n.º 27
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            var adapter = await BluetoothAdapter.GetDefaultAsync();

            var serviceResult =
                await GattServiceProvider.CreateAsync(Guid.Parse(SensorUUIDs.UUID_ACC_SERV));

            accService = serviceResult.ServiceProvider;
            accService.AdvertisementStatusChanged += AccService_AdvertisementStatusChanged;

            var param = new GattLocalCharacteristicParameters();

            param.CharacteristicProperties =
                GattCharacteristicProperties.Indicate |
                GattCharacteristicProperties.Read;

            param.WriteProtectionLevel = GattProtectionLevel.Plain;

            param.UserDescription = "accelerometer";

            var charResult =
                await accService.Service.CreateCharacteristicAsync(Guid.Parse(SensorUUIDs.UUID_ACC_DATA), param);

            accData = charResult.Characteristic;
            accData.ReadRequested += AccData_ReadRequested;
            accService.StartAdvertising(new GattServiceProviderAdvertisingParameters()
            {
                IsDiscoverable = true, IsConnectable = true
            });

            serviceResult =
                await GattServiceProvider.CreateAsync(Guid.Parse(SensorUUIDs.UUID_ENV_SERV));

            envService = serviceResult.ServiceProvider;

            param = new GattLocalCharacteristicParameters();
            param.CharacteristicProperties =
                GattCharacteristicProperties.Indicate |
                GattCharacteristicProperties.Read;

            param.UserDescription = "temperature";

            charResult =
                await envService.Service.CreateCharacteristicAsync(Guid.Parse(SensorUUIDs.UUID_ENV_TEMP), param);

            tempData = charResult.Characteristic;
            tempData.ReadRequested += TempData_ReadRequested;

            param = new GattLocalCharacteristicParameters();
            param.CharacteristicProperties =
                GattCharacteristicProperties.Indicate |
                GattCharacteristicProperties.Read;

            param.UserDescription = "pressure";

            charResult =
                await envService.Service.CreateCharacteristicAsync(Guid.Parse(SensorUUIDs.UUID_ENV_PRES), param);

            pressData = charResult.Characteristic;
            pressData.ReadRequested += PressData_ReadRequested;
            envService.StartAdvertising(new GattServiceProviderAdvertisingParameters()
            {
                IsDiscoverable = true, IsConnectable = true
            });

            timer          = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick    += Timer_Tick;
            //timer.Start();

            base.OnNavigatedTo(e);
        }
        private async void setup()
        {
            var result = await GattServiceProvider.CreateAsync(cascableBasicUserInputServiceGuid);

            if (result.Error != BluetoothError.Success)
            {
                Debug.WriteLine("Failed to create BLE service!!");
                return;
            }

            cascableService = result.ServiceProvider;

            var continueButtonResult = await cascableService.Service.CreateCharacteristicAsync(continueButtonDownCharacteristicGuid, readAndNotifyParameters);

            if (continueButtonResult.Error != BluetoothError.Success)
            {
                Debug.WriteLine("Failed to create Continue Button Characteristic!!");
                return;
            }

            continueButtonCharacteristic = continueButtonResult.Characteristic;
            continueButtonCharacteristic.ReadRequested            += readContinueButtonValue;
            continueButtonCharacteristic.SubscribedClientsChanged += subscribedClientsChanged;

            var stopButtonResult = await cascableService.Service.CreateCharacteristicAsync(stopButtonDownCharacteristicGuid, readAndNotifyParameters);

            if (stopButtonResult.Error != BluetoothError.Success)
            {
                Debug.WriteLine("Failed to create Stop Button Characteristic!!");
                return;
            }

            stopButtonCharacteristic = stopButtonResult.Characteristic;
            stopButtonCharacteristic.ReadRequested += readStopButtonValue;

            var remoteCanContinueResult = await cascableService.Service.CreateCharacteristicAsync(remoteCanContinueCharacteristicGuid, writeParameters);

            if (remoteCanContinueResult.Error != BluetoothError.Success)
            {
                Debug.WriteLine("Failed to create Remote Can Continue Characteristic!!");
                return;
            }

            remoteCanContinueCharacteristic = remoteCanContinueResult.Characteristic;
            remoteCanContinueCharacteristic.WriteRequested += writeRemoteCanContinue;

            var remoteCanStopResult = await cascableService.Service.CreateCharacteristicAsync(remoteCanStopCharacteristicGuid, writeParameters);

            if (remoteCanStopResult.Error != BluetoothError.Success)
            {
                Debug.WriteLine("Failed to create Remote Can Stop Characteristic!!");
                return;
            }

            remoteCanStopCharacteristic = remoteCanStopResult.Characteristic;
            remoteCanStopCharacteristic.WriteRequested += writeRemoteCanStop;

            var userMessageResult = await cascableService.Service.CreateCharacteristicAsync(userMessageCharacteristicGuid, writeParameters);

            if (userMessageResult.Error != BluetoothError.Success)
            {
                Debug.WriteLine("Failed to create User Message Characteristic!!");
                return;
            }

            userMessageCharacteristic = userMessageResult.Characteristic;
            userMessageCharacteristic.WriteRequested += writeUserMessage;

            cascableService.StartAdvertising(advertisingParameters);
            Debug.WriteLine("Service is now advertising!");
        }
Exemplo n.º 29
0
 private void AccService_AdvertisementStatusChanged(GattServiceProvider sender, GattServiceProviderAdvertisementStatusChangedEventArgs args)
 {
     Debug.WriteLine(args.Status);
 }
        /// <summary>
        /// Uses the relevant Service/Characteristic UUIDs to initialize, hook up event handlers and start a service on the local system.
        /// </summary>
        /// <returns></returns>
        private async Task <bool> ServiceProviderInitAsync()
        {
            // BT_Code: Initialize and starting a custom GATT Service using GattServiceProvider.
            GattServiceProviderResult serviceResult = await GattServiceProvider.CreateAsync(Constants.CalcServiceUuid);

            if (serviceResult.Error == BluetoothError.Success)
            {
                serviceProvider = serviceResult.ServiceProvider;
            }
            else
            {
                rootPage.NotifyUser($"Could not create service provider: {serviceResult.Error}", NotifyType.ErrorMessage);
                return(false);
            }

            GattLocalCharacteristicResult result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.Op1CharacteristicUuid, Constants.gattOperandParameters);

            if (result.Error == BluetoothError.Success)
            {
                op1Characteristic = result.Characteristic;
            }
            else
            {
                rootPage.NotifyUser($"Could not create operand1 characteristic: {result.Error}", NotifyType.ErrorMessage);
                return(false);
            }
            op1Characteristic.WriteRequested += Op1Characteristic_WriteRequestedAsync;

            result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.Op2CharacteristicUuid, Constants.gattOperandParameters);

            if (result.Error == BluetoothError.Success)
            {
                op2Characteristic = result.Characteristic;
            }
            else
            {
                rootPage.NotifyUser($"Could not create operand2 characteristic: {result.Error}", NotifyType.ErrorMessage);
                return(false);
            }

            op2Characteristic.WriteRequested += Op2Characteristic_WriteRequestedAsync;

            result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.OperatorCharacteristicUuid, Constants.gattOperatorParameters);

            if (result.Error == BluetoothError.Success)
            {
                operatorCharacteristic = result.Characteristic;
            }
            else
            {
                rootPage.NotifyUser($"Could not create operator characteristic: {result.Error}", NotifyType.ErrorMessage);
                return(false);
            }

            operatorCharacteristic.WriteRequested += OperatorCharacteristic_WriteRequestedAsync;

            // Add presentation format - 32-bit unsigned integer, with exponent 0, the unit is unitless, with no company description
            GattPresentationFormat intFormat = GattPresentationFormat.FromParts(
                GattPresentationFormatTypes.UInt32,
                PresentationFormats.Exponent,
                Convert.ToUInt16(PresentationFormats.Units.Unitless),
                Convert.ToByte(PresentationFormats.NamespaceId.BluetoothSigAssignedNumber),
                PresentationFormats.Description);

            Constants.gattResultParameters.PresentationFormats.Add(intFormat);

            result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.ResultCharacteristicUuid, Constants.gattResultParameters);

            if (result.Error == BluetoothError.Success)
            {
                resultCharacteristic = result.Characteristic;
            }
            else
            {
                rootPage.NotifyUser($"Could not create result characteristic: {result.Error}", NotifyType.ErrorMessage);
                return(false);
            }
            resultCharacteristic.ReadRequested            += ResultCharacteristic_ReadRequestedAsync;
            resultCharacteristic.SubscribedClientsChanged += ResultCharacteristic_SubscribedClientsChanged;

            // BT_Code: Indicate if your sever advertises as connectable and discoverable.
            GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters
            {
                // IsConnectable determines whether a call to publish will attempt to start advertising and
                // put the service UUID in the ADV packet (best effort)
                IsConnectable = peripheralSupported,

                // IsDiscoverable determines whether a remote device can query the local device for support
                // of this service
                IsDiscoverable = true
            };

            serviceProvider.AdvertisementStatusChanged += ServiceProvider_AdvertisementStatusChanged;
            serviceProvider.StartAdvertising(advParameters);
            return(true);
        }