Esempio n. 1
0
        void BuildCharacteristics(Plugin.BluetoothLE.Server.IGattService service, Guid characteristicId)
        {
            var characteristic = service.AddCharacteristic(
                characteristicId,
                CharacteristicProperties.Notify | CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,
                GattPermissions.Read | GattPermissions.Write
                );

            characteristic
            .WhenDeviceSubscriptionChanged()
            .Subscribe(e =>
            {
                var @event = e.IsSubscribed ? "Subscribed" : "Unsubcribed";
                this.OnEvent($"Device {e.Device.Uuid} {@event}");
                this.OnEvent($"Charcteristic Subcribers: {characteristic.SubscribedDevices.Count}");
            });

            characteristic.WhenReadReceived().Subscribe(x =>
            {
                var write = this.CharacteristicValue;
                if (String.IsNullOrWhiteSpace(write))
                {
                    write = "(NOTHING)";
                }

                x.Value = Encoding.UTF8.GetBytes(write);
                this.OnEvent("Characteristic Read Received");
            });
            characteristic.WhenWriteReceived().Subscribe(x =>
            {
                var write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
                this.OnEvent($"Characteristic Write Received - {write}");
            });
        }
Esempio n. 2
0
        /// <summary>
        /// 创建服务
        /// </summary>
        private async Task CreateService()
        {
            var server = await CrossBleAdapter.Current.CreateGattServer();

            controllerService = server.CreateService(RemoteUuids.RemoteXServiceGuid, true);

            //创建特征
            CreateKeyboardOperationCharacteristic();
            CreateFileManageCharacteristic();
            CreateStringOperationCharacteristic();
            CreateMouseMotionCharacteristic();
            CreateMouseEventCharacteristic();

            //添加服务
            server.AddService(controllerService);
        }
Esempio n. 3
0
        private async Task BuildServer(ClientPage clientPage)
        {
            try
            {
                adapter = CrossBleAdapter.Current;
                server  = await adapter.CreateGattServer();

                Plugin.BluetoothLE.Server.IGattService service = server.CreateService(Guid.Parse("569A1101-B87F-490C-92CB-11BA5EA5167C"), true);
                BuildCharacteristics(service, Guid.Parse("569A2003-B87F-490C-92CB-11BA5EA5167C"), clientPage, CharacteristicsType.TX_Write);
                BuildCharacteristics(service, Guid.Parse("569A2002-B87F-490C-92CB-11BA5EA5167C"), clientPage, CharacteristicsType.RX_Notify);
                BuildCharacteristics(service, Guid.Parse("569A2001-B87F-490C-92CB-11BA5EA5167C"), clientPage, CharacteristicsType.TX_Write);
                BuildCharacteristics(service, Guid.Parse("569A2000-B87F-490C-92CB-11BA5EA5167C"), clientPage, CharacteristicsType.RX_Notify);
                server.AddService(service);

                //Plugin.BluetoothLE.Server.IGattCharacteristic characteristic = service.AddCharacteristic
                //(
                //    Guid.NewGuid(),
                //    CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,
                //    GattPermissions.Read | GattPermissions.Write
                //);

                //Plugin.BluetoothLE.Server.IGattCharacteristic notifyCharacteristic = service.AddCharacteristic
                //(
                //    Guid.NewGuid(),
                //    CharacteristicProperties.Indicate | CharacteristicProperties.Notify,
                //    GattPermissions.Read | GattPermissions.Write
                //);

                adapter.Advertiser.Start(new AdvertisementData
                {
                    LocalName = "My GATT"
                });
            }
            catch (Exception ex) {
                Exception exception = ex;
            }
        }
Esempio n. 4
0
 private void CreateBuzzerService()
 {
     services.Add(StaticGuids.buzzerServiceGuid);
     buzzerService = gattServer.CreateService(StaticGuids.buzzerServiceGuid, true);
 }
Esempio n. 5
0
        private void BuildCharacteristics(Plugin.BluetoothLE.Server.IGattService service, Guid characteristicId, ClientPage clientPage, CharacteristicsType type)
        {
            //Plugin.BluetoothLE.Server.IGattCharacteristic characteristic = service.AddCharacteristic(characteristicId,
            //    CharacteristicProperties.Notify | CharacteristicProperties.Read |
            //    CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,
            //    GattPermissions.Read | GattPermissions.Write );

            //characteristic.WhenReadReceived().Subscribe(x =>
            //{
            //    string write = "@@@@";
            //    if (string.IsNullOrWhiteSpace(write))
            //    {
            //        write = "0000";
            //    }

            //    x.Value = Encoding.UTF8.GetBytes(write);
            //});

            //characteristic.WhenWriteReceived().Subscribe(x =>
            //{
            //    string write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
            //    clientPage.ReceivedText(write);
            //});

            if (type == CharacteristicsType.RX_Notify)
            {
                Plugin.BluetoothLE.Server.IGattCharacteristic RX_NotifyCharacteristic =
                    service.AddCharacteristic(characteristicId, CharacteristicProperties.Notify, GattPermissions.Read);

                RX_NotifyCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e => {
                    RX_NotifyCharacteristic.Broadcast(Encoding.UTF8.GetBytes("Device successfully subscribed"));
                });


                //IDisposable notifyBroadcast = null;
                //notifyCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
                //{
                //    var @event = e.IsSubscribed ? "Subscribed" : "Unsubcribed";

                //    if (notifyBroadcast == null)
                //    {
                //        this.notifyBroadcast = Observable
                //            .Interval(TimeSpan.FromSeconds(1))
                //            .Where(x => notifyCharacteristic.SubscribedDevices.Count > 0)
                //            .Subscribe(_ =>
                //            {
                //                Debug.WriteLine("Sending Broadcast");
                //                var dt = DateTime.Now.ToString("g");
                //                var bytes = Encoding.UTF8.GetBytes(dt);
                //                notifyCharacteristic.Broadcast(bytes);
                //            });
                //    }
                //});
            }

            if (type == CharacteristicsType.TX_Write)
            {
                Plugin.BluetoothLE.Server.IGattCharacteristic TX_WriteCharacteristic =
                    service.AddCharacteristic(characteristicId, CharacteristicProperties.Write, GattPermissions.Write);

                TX_WriteCharacteristic.WhenWriteReceived().Subscribe(x =>
                {
                    string write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
                    clientPage.ReceivedText(write);
                });
            }
        }
Esempio n. 6
0
        public async Task CreateServer()
        {
            if (CrossBleAdapter.Current.Status == AdapterStatus.PoweredOn)
            {
                try
                {
                    RaiseInfoEvent("Creating Gatt Server");
                    _server = await CrossBleAdapter.Current.CreateGattServer();

                    RaiseInfoEvent("Gatt Server Created");
                    _service = _server.CreateService(_primaryServiceUUID, true);
                    RaiseInfoEvent("Primary Service Created");

                    _serverReadWriteCharacteristic = _service.AddCharacteristic
                                                     (
                        _readWriteCharacteristicUUID,
                        CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,
                        GattPermissions.Read | GattPermissions.Write
                                                     );

                    //_serverNotifyCharacteristic = _service.AddCharacteristic
                    //(
                    //    _notifyServiceUUID,
                    //    CharacteristicProperties.Indicate | CharacteristicProperties.Notify,
                    //    GattPermissions.Read | GattPermissions.Write
                    //);

                    _serverReadWriteCharacteristic.WhenReadReceived().Subscribe(x =>
                    {
                        _serverReadCount++;
                        x.Value  = Encoding.UTF8.GetBytes($"Server Response: {_serverReadCount}");
                        x.Status = GattStatus.Success; // you can optionally set a status, but it defaults to Success
                        RaiseInfoEvent("Received Read Request");
                    });

                    _serverReadWriteCharacteristic.WhenWriteReceived().Subscribe(x =>
                    {
                        var textReceivedFromClient = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
                        RaiseInfoEvent(textReceivedFromClient);
                    });

                    RaiseInfoEvent("Characteristics Added");

                    var adData = new AdvertisementData
                    {
                        LocalName    = _serverName,
                        ServiceUuids = new List <Guid> {
                            _primaryServiceUUID
                        }
                    };

                    var manufacturerData = new ManufacturerData
                    {
                        CompanyId = 1,
                        Data      = Encoding.UTF8.GetBytes("Tomorrow Never Dies")
                    };
                    adData.ManufacturerData = manufacturerData;
                    RaiseInfoEvent("Starting Ad Service");
                    CrossBleAdapter.Current.Advertiser.Start(adData);

                    RaiseInfoEvent("Server and Service Started");
                    RaiseServerClientStarted(true);
                }
                catch (Exception e)
                {
                    RaiseErrorEvent(e);
                }
            }
            else
            {
                var exception = new Exception("Bluetooth is OFF");
                RaiseErrorEvent(exception);
            }
        }
        /// <summary>
        /// Create a characteristic
        /// </summary>
        /// <param name="service">The service</param>
        /// <param name="characteristicId">The characteristic identifier</param>
        /// <param name="isNotification">True if a notification characteristic</param>
        private void BuildCharacteristics(Plugin.BluetoothLE.Server.IGattService service, Guid characteristicId, bool isNotification = false)
        {
            Plugin.BluetoothLE.Server.IGattCharacteristic characteristic = null;
            if (isNotification)
            {
                characteristic = service.AddCharacteristic(
                    characteristicId,
                    CharacteristicProperties.Indicate | CharacteristicProperties.Read | CharacteristicProperties.Notify,
                    GattPermissions.Read | GattPermissions.Write);
            }
            else
            {
                characteristic = service.AddCharacteristic(
                    characteristicId,
                    CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,
                    GattPermissions.Read | GattPermissions.Write);
            }

            ////this.indexOfCharacteristics.Add(characteristicId, characteristic);

            characteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                var @event = e.IsSubscribed ? "Subscribed" : "Unsubcribed";
                this.OnEvent($"Device {e.Device.Uuid} {@event}");
                this.OnEvent($"Charcteristic Subcribers: {characteristic.SubscribedDevices.Count}");
            });

            characteristic.WhenReadReceived().Subscribe(x =>
            {
                this.OnEvent($"{this.indexOfCharacteristicDescriptions[characteristic.Uuid]} characteristic Read Received");

                if (Constants.ImageReceivedCharacteristic == characteristic.Uuid)
                {
                    var deviceId        = x.Device.Uuid;
                    byte[] dataSoFar    = null;
                    bool hasStoredValue = this.partialImagePerDevice.TryGetValue(deviceId, out dataSoFar);

                    if (hasStoredValue)
                    {
                        Guid imageId;
                        x.Status = this.HandleImage(deviceId, dataSoFar, out imageId);
                        if (x.Status == GattStatus.Success)
                        {
                            x.Value = Encoding.UTF8.GetBytes(imageId.ToString());
                        }

                        this.partialImagePerDevice.Remove(deviceId);
                    }
                    else
                    {
                        this.logger.Error($"Reading Image from {deviceId}, end of image marker read, but there is no stored image");
                        x.Status = GattStatus.Failure;
                    }
                }
            });

            characteristic.WhenWriteReceived().Subscribe(x =>
            {
                var deviceId = x.Device.Uuid;

                if (Constants.ImageCharacteristic == characteristic.Uuid)
                {
                    this.logger.Info($"Reading Image from {deviceId}, appending {x.Value.Length} bytes");
                    byte[] dataSoFar = null;
                    long bytesSoFar  = x.Value.Length;
                    if (this.partialImagePerDevice.TryGetValue(deviceId, out dataSoFar))
                    {
                        byte[] rv = new byte[dataSoFar.Length + x.Value.Length];
                        System.Buffer.BlockCopy(dataSoFar, 0, rv, 0, dataSoFar.Length);
                        System.Buffer.BlockCopy(x.Value, 0, rv, dataSoFar.Length, x.Value.Length);
                        this.partialImagePerDevice[deviceId] = rv;
                        bytesSoFar += dataSoFar.Length;
                    }
                    else
                    {
                        this.partialImagePerDevice.Add(deviceId, x.Value);
                    }

                    this.NotifyBytesReceived?.Invoke(this, new BytesReceivedEventArgs(bytesSoFar, deviceId));
                    x.Status = GattStatus.Success;
                }
            });
        }