Beispiel #1
0
        public Server(string serverName, List <string> teamNames)
        {
            this.serverName = serverName;
            teams           = new Dictionary <string, List <Guid> >();
            foreach (string teamName in teamNames)
            {
                teams[teamName] = new List <Guid>();
            }

            //initialization
            services         = new List <Guid>();
            adapter          = CrossBleAdapter.Current;
            lockStatus       = "C";
            deviceIdentities = new Dictionary <Guid, string>();
            buzzDevice       = Guid.Empty;

            adapter.WhenReadyCreateServer().Subscribe(server =>
            {
                Debug.WriteLine("Got a server");
                //when does this fire?
                gattServer = server;
                //create services
                CreateBuzzerService();
                //add characteristics
                CreateLockStatusChar();
                CreateBuzzChar();
                CreateIdentityChar();
                CreateTeamChar();
                StartServer();
            });

            InitializeComponent();
            Server_Name.Text = "Server Name: " + serverName;
        }
Beispiel #2
0
        public GattService(CBPeripheralManager manager, IGattServer server, Guid serviceUuid, bool primary) : base(server, serviceUuid, primary)
        {
            this.manager = manager;
#if __TVOS__
#else
            this.Native = new CBMutableService(serviceUuid.ToCBUuid(), primary);
#endif
        }
Beispiel #3
0
 public GattService(GattContext context, IGattServer server, Guid uuid, bool primary) : base(server, uuid, primary)
 {
     this.context = context;
     this.Native  = new BluetoothGattService(
         UUID.FromString(uuid.ToString()),
         primary ? GattServiceType.Primary : GattServiceType.Secondary
         );
 }
 /// <summary>
 /// Stop the server
 /// </summary>
 public void StopServer()
 {
     this.adapter.Advertiser.Stop();
     this.OnEvent("GATT Server Stopped");
     this.server.Dispose();
     this.server      = null;
     this.serverState = ServerState.Stopped;
 }
        public ConnectedDevicesPage(IGattServer gattServer)
        {
            GattServer          = gattServer;
            ConnectedDeviceList = new ObservableCollection <IBluetoothDevice>();

            InitializeComponent();
            DeviceListView.ItemsSource = ConnectedDeviceList;
        }
Beispiel #6
0
 public ClientDeviceConfigPage(IGattServer gattServer, ClientCharacteristicConfigurationDescriptorWrapper clientCharacteristicConfigurationDescriptorWrapper)
 {
     ConnectedDeviceList = new ObservableCollection <Model>();
     GattServer          = gattServer;
     ClientCharacteristicConfigurationDescriptorWrapper = clientCharacteristicConfigurationDescriptorWrapper;
     InitializeComponent();
     DeviceListView.ItemsSource    = ConnectedDeviceList;
     DeviceListView.ItemAppearing += DeviceListView_ItemAppearing;
 }
Beispiel #7
0
        protected AbstractGattService(IGattServer server, Guid serviceUuid, bool primary)
        {
            this.Server = server;

            this.Uuid      = serviceUuid;
            this.IsPrimary = primary;

            this.internalList    = new List <IGattCharacteristic>();
            this.Characteristics = new ReadOnlyCollection <IGattCharacteristic>(this.internalList);
        }
        async Task BuildServer()
        {
            try
            {
                this.OnEvent("GATT Server Starting");
                this.server = await this.adapter.CreateGattServer();

                var counter = 0;
                var service = this.server.CreateService(Guid.Parse("A495FF20-C5B1-4B44-B512-1370F02D74DE"), true);
                this.BuildCharacteristics(service, Guid.Parse("A495FF21-C5B1-4B44-B512-1370F02D74DE")); // scratch #1
                this.BuildCharacteristics(service, Guid.Parse("A495FF22-C5B1-4B44-B512-1370F02D74DE")); // scratch #2
                this.BuildCharacteristics(service, Guid.Parse("A495FF23-C5B1-4B44-B512-1370F02D74DE")); // scratch #3
                this.BuildCharacteristics(service, Guid.Parse("A495FF24-C5B1-4B44-B512-1370F02D74DE")); // scratch #4
                this.BuildCharacteristics(service, Guid.Parse("A495FF25-C5B1-4B44-B512-1370F02D74DE")); // scratch #5
                this.server.AddService(service);
                this.ServerText = "Stop Server";

                this.timer = Observable
                             .Interval(TimeSpan.FromSeconds(1))
                             .Select(_ => Observable.FromAsync(async ct =>
                {
                    var subscribed = service.Characteristics.Where(x => x.SubscribedDevices.Count > 0);
                    foreach (var ch in subscribed)
                    {
                        counter++;
                        await ch.BroadcastObserve(Encoding.UTF8.GetBytes(counter.ToString()));
                    }
                }))
                             .Merge(5)
                             .Subscribe();

                this.server
                .WhenAnyCharacteristicSubscriptionChanged()
                .Subscribe(x =>
                           this.OnEvent($"[WhenAnyCharacteristicSubscriptionChanged] UUID: {x.Characteristic.Uuid} - Device: {x.Device.Uuid} - Subscription: {x.IsSubscribing}")
                           );

                //descriptor.WhenReadReceived().Subscribe(x =>
                //    this.OnEvent("Descriptor Read Received")
                //);
                //descriptor.WhenWriteReceived().Subscribe(x =>
                //{
                //    var write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
                //    this.OnEvent($"Descriptor Write Received - {write}");
                //});
                this.OnEvent("GATT Server Started");
            }
            catch (Exception ex)
            {
                this.dialogs.Alert("Error building gatt server - " + ex);
            }
        }
        public ServerViewModel()
        {
            this.adapter = CrossBleAdapter.Current;
            this.dialogs = UserDialogs.Instance;

            this.adapter
            .WhenStatusChanged()
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => this.Status = x);

            this.ToggleServer = ReactiveCommand.Create(() =>
            {
                if (this.adapter.Status != AdapterStatus.PoweredOn)
                {
                    this.dialogs.Alert("Could not start GATT Server.  Adapter Status: " + this.adapter.Status);
                    return;
                }

                if (!this.adapter.Features.HasFlag(AdapterFeatures.ServerGatt))
                {
                    this.dialogs.Alert("GATT Server is not supported on this platform configuration");
                    return;
                }

                if (this.server == null)
                {
                    this.BuildServer();
                    this.adapter.Advertiser.Start(new AdvertisementData
                    {
                        LocalName = "My GATT"
                                    //ManufacturerData = new ManufacturerData()
                    });
                }
                else
                {
                    this.ServerText = "Start Server";
                    this.adapter.Advertiser.Stop();
                    this.OnEvent("GATT Server Stopped");
                    this.server.Dispose();
                    this.server = null;
                    this.timer?.Dispose();
                }
            });

            this.Clear = ReactiveCommand.Create(() => this.Output = String.Empty);
        }
        public ServerViewModel(IUserDialogs dialogs)
        {
            this.dialogs = dialogs;

            this.ToggleServer = ReactiveCommand.CreateFromTask(async _ =>
            {
                if (this.adapter.Status != AdapterStatus.PoweredOn)
                {
                    this.dialogs.Alert("Could not start GATT Server.  Adapter Status: " + this.adapter.Status);
                    return;
                }

                if (!this.adapter.Features.HasFlag(AdapterFeatures.ServerGatt))
                {
                    this.dialogs.Alert("GATT Server is not supported on this platform configuration");
                    return;
                }

                if (this.server == null)
                {
                    await this.BuildServer();
                    this.adapter.Advertiser.Start(new AdvertisementData
                    {
                        LocalName = "My GATT"
                                    //ManufacturerData = new ManufacturerData()
                    });
                }
                else
                {
                    this.ServerText = "Start Server";
                    this.adapter.Advertiser.Stop();
                    this.OnEvent("GATT Server Stopped");
                    this.server.Dispose();
                    this.server = null;
                    this.timer?.Dispose();
                }
            });

            this.Clear = ReactiveCommand.Create(() => this.Output = String.Empty);
        }
        /// <summary>
        /// Start a LE server and pass the identifier to the client manager
        /// </summary>
        /// <returns>An awaitable task</returns>
        public async Task StartServer()
        {
            this.serverState = ServerState.Starting;
            try
            {
                this.server = await this.adapter.CreateGattServer();

                var serviceId = Guid.Parse(Constants.ServiceUUID);
                var service   = this.server.CreateService(serviceId, true);

                this.indexOfCharacteristicDescriptions = new Dictionary <Guid, string>();
                this.indexOfCharacteristicDescriptions.Add(Constants.ImageCharacteristic, "Image sent");
                this.indexOfCharacteristicDescriptions.Add(Constants.ImageReceivedCharacteristic, "Image Received");

                ////this.indexOfCharacteristics = new Dictionary<Guid, Plugin.BluetoothLE.Server.IGattCharacteristic>();
                this.BuildCharacteristics(service, Constants.ImageReceivedCharacteristic, isNotification: true);
                this.BuildCharacteristics(service, Constants.ImageCharacteristic);

                this.server.AddService(service);

                this.server.WhenAnyCharacteristicSubscriptionChanged().Subscribe(x =>
                {
                    this.OnEvent($"[WhenAnyCharacteristicSubscriptionChanged] UUID: {x.Characteristic.Uuid} - Device: {x.Device.Uuid} - Subscription: {x.IsSubscribing}");
                });

                this.OnEvent("GATT Server Started");
                this.serverState = ServerState.Started;
            }
            catch (Exception ex)
            {
                this.serverState = ServerState.FailedToStart;
                this.logger.Error(ex, "Error building gatt server - ");
                this.dialogService.Notice("Bluetooth LE service failed to start");
            }
            finally
            {
                this.completionMonitor.Release();
            }
        }
Beispiel #12
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;
            }
        }
        void BuildServer()
        {
            if (this.server != null)
            {
                return;
            }

            try
            {
                this.server = this.adapter.CreateGattServer();
                var service = this.server.AddService(Guid.NewGuid(), true);

                var characteristic = service.AddCharacteristic(
                    Guid.NewGuid(),
                    CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteWithoutResponse,
                    GattPermissions.Read | GattPermissions.Write
                    );
                var notifyCharacteristic = service.AddCharacteristic
                                           (
                    Guid.NewGuid(),
                    CharacteristicProperties.Notify,
                    GattPermissions.Read | GattPermissions.Write
                                           );

                //var descriptor = characteristic.AddDescriptor(Guid.NewGuid(), Encoding.UTF8.GetBytes("Test Descriptor"));

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

                    if (this.notifyBroadcast == null)
                    {
                        this.OnEvent("Starting Subscriber Thread");
                        this.notifyBroadcast = Observable
                                               .Interval(TimeSpan.FromSeconds(1))
                                               .Where(x => notifyCharacteristic.SubscribedDevices.Count > 0)
                                               .Subscribe(_ =>
                        {
                            try
                            {
                                var dt    = DateTime.Now.ToString("g");
                                var bytes = Encoding.UTF8.GetBytes(dt);
                                notifyCharacteristic
                                .BroadcastObserve(bytes)
                                .Subscribe(x =>
                                {
                                    var state = x.Success ? "Successfully" : "Failed";
                                    var data  = Encoding.UTF8.GetString(x.Data, 0, x.Data.Length);
                                    this.OnEvent($"{state} Broadcast {data} to device {x.Device.Uuid} from characteristic {x.Characteristic}");
                                });
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Error during broadcast: " + ex);
                            }
                        });
                    }
                });

                characteristic.WhenReadReceived().Subscribe(x =>
                {
                    var write = this.CharacteristicValue;
                    if (write.IsEmpty())
                    {
                        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}");
                });

                server
                .WhenRunningChanged()
                .Catch <bool, ArgumentException>(ex =>
                {
                    this.dialogs.Alert("Error Starting GATT Server - " + ex);
                    return(Observable.Return(false));
                })
                .Subscribe(started =>
                {
                    if (!started)
                    {
                        this.ServerText = "Start Server";
                        this.OnEvent("GATT Server Stopped");
                    }
                    else
                    {
                        this.notifyBroadcast?.Dispose();
                        this.notifyBroadcast = null;

                        this.ServerText = "Stop Server";
                        this.OnEvent("GATT Server Started");
                        foreach (var s in server.Services)
                        {
                            this.OnEvent($"Service {s.Uuid} Created");
                            foreach (var ch in s.Characteristics)
                            {
                                this.OnEvent($"Characteristic {ch.Uuid} Online - Properties {ch.Properties}");
                            }
                        }
                    }
                });

                server
                .WhenAnyCharacteristicSubscriptionChanged()
                .Subscribe(x =>
                           this.OnEvent($"[WhenAnyCharacteristicSubscriptionChanged] UUID: {x.Characteristic.Uuid} - Device: {x.Device.Uuid} - Subscription: {x.IsSubscribing}")
                           );

                //descriptor.WhenReadReceived().Subscribe(x =>
                //    this.OnEvent("Descriptor Read Received")
                //);
                //descriptor.WhenWriteReceived().Subscribe(x =>
                //{
                //    var write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
                //    this.OnEvent($"Descriptor Write Received - {write}");
                //});
            }
            catch (Exception ex)
            {
                this.dialogs.Alert("Error building gatt server - " + ex);
            }
        }
Beispiel #14
0
 private void InitializeGattServer()
 {
     _gattServer = new Bluetooth_GATTServer_Common.GattServer(GattCharacteristicIdentifiers.ServiceId, _logger);//Common.GattServer(GattCharacteristicIdentifiers.ServiceId, _logger);
     _gattServer.OnChararteristicWrite += _gattServer_OnChararteristicWrite;;
 }
 public UwpGattService(IGattServer server, Guid serviceUuid, bool primary) : base(server, serviceUuid, primary)
 {
 }
Beispiel #16
0
 private static void InitializeGattServer()
 {
     _gattServer = new Common.GattServer(GattCharacteristicIdentifiers.ServiceId, _logger);
     _gattServer.OnChararteristicWrite += GattServerOnChararteristicWrite;
 }
Beispiel #17
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);
            }
        }