Exemplo n.º 1
0
        private void CreateIdentityChar()
        {
            //create characteristic which allows devices to self report nick names
            identityChar = buzzerService.AddCharacteristic(StaticGuids.identityCharGuid,
                                                           CharacteristicProperties.Write | CharacteristicProperties.Read, GattPermissions.Read | GattPermissions.Write);
            identityChar.WhenWriteReceived().Subscribe(writeRequest =>
            {
                printdebug("identity write request");
                string identityWrite = Encoding.UTF8.GetString(writeRequest.Value);

                if (identityWrite[0] == ':')
                {
                    teams[identityWrite.Substring(1)].Add(writeRequest.Device.Uuid);
                    updateTeams();
                }
                else
                {
                    Debug.WriteLine("Identity provided: " + identityWrite);
                    deviceIdentities[writeRequest.Device.Uuid] = identityWrite;
                }
            });
            //inform connected devices of their own UUID
            identityChar.WhenReadReceived().Subscribe(read =>
            {
                read.Value = Encoding.UTF8.GetBytes(read.Device.Uuid.ToString());
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// 创建鼠标移动特征
        /// </summary>
        private void CreateMouseMotionCharacteristic()
        {
            mouseMotionCharacteristic = controllerService.AddCharacteristic
                                        (
                RemoteUuids.MouseMotionCharacteristicGuid,
                CharacteristicProperties.Notify | CharacteristicProperties.Read,
                GattPermissions.Read
                                        );

            mouseMotionCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                ; //当订阅发生改变时
            });

            mouseMotionCharacteristic.WhenReadReceived().Subscribe(x =>
            {
                if (OnReadReceived != null)
                {
                    cursorPoint = OnReadReceived();
                }
                byte[] posDataBytes = new byte[2 * sizeof(double)];
                var xBytes          = BitConverter.GetBytes(cursorPoint.X);
                var yBytes          = BitConverter.GetBytes(cursorPoint.Y);
                System.Diagnostics.Debug.WriteLine(cursorPoint.X.ToString() + ", " + cursorPoint.Y.ToString());
                xBytes.CopyTo(posDataBytes, 0);
                yBytes.CopyTo(posDataBytes, sizeof(double));
                x.Value = posDataBytes;

                x.Status = GattStatus.Success;
            });
        }
Exemplo n.º 3
0
        private void CreateTeamChar()
        {
            teamChar = buzzerService.AddCharacteristic(StaticGuids.teamCharGuid,
                                                       CharacteristicProperties.Indicate | CharacteristicProperties.Notify,
                                                       GattPermissions.Read | GattPermissions.Write
                                                       );

            //when a new device is added give all team information
            teamChar.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                teamChar.Broadcast(teamInfo(), e.Device);
            });
        }
Exemplo n.º 4
0
        private void CreateMouseEventCharacteristic()
        {
            mouseEventCharacteristic = controllerService.AddCharacteristic
                                       (
                RemoteUuids.MouseEventCharacteristicGuid,
                CharacteristicProperties.Notify,
                GattPermissions.Read
                                       );

            mouseEventCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                ; //当订阅发生改变时
            });
        }
Exemplo n.º 5
0
        //创建字符串操作特征
        private void CreateStringOperationCharacteristic()
        {
            stringOperationCharacteristic = controllerService.AddCharacteristic
                                            (
                RemoteUuids.StringOperationCharacteristicGuid,
                CharacteristicProperties.Notify,
                GattPermissions.Read
                                            );

            stringOperationCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                ; //当订阅发生改变时
            });

            int number = 0;
        }
Exemplo n.º 6
0
 private void CreateBuzzChar()
 {
     buzzChar = buzzerService.AddCharacteristic(StaticGuids.buzzCharGuid,
                                                CharacteristicProperties.Write, GattPermissions.Read | GattPermissions.Write);
     buzzChar.WhenWriteReceived().Subscribe(writeRequest =>
     {
         if (lockStatus == "O")
         {
             buzzDevice       = writeRequest.Device.Uuid;
             string buzzName  = deviceIdentities[buzzDevice];
             Buzz_Player.Text = buzzName;
             lockStatus       = "C";
             lockStatusChar.Broadcast(Encoding.UTF8.GetBytes(lockStatus + buzzDevice.ToString() + buzzName));
         }
     });
 }
Exemplo n.º 7
0
        /// <summary>
        /// 创建文件管理特征
        /// </summary>
        private void CreateFileManageCharacteristic()
        {
            fileManageCharacteristic = controllerService.AddCharacteristic
                                       (
                RemoteUuids.FileManageCharacteristicGuid,
                CharacteristicProperties.Notify | CharacteristicProperties.Read | CharacteristicProperties.Write,
                GattPermissions.Read | GattPermissions.Write
                                       );

            fileManageCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                ;
            });

            fileManageCharacteristic.WhenReadReceived().Subscribe(x =>
            {
                var response = 3;
                x.Value      = BitConverter.GetBytes(response);

                x.Status = GattStatus.Success;
            });

            //收到目录数据
            fileManageCharacteristic.WhenWriteReceived().Subscribe(x =>
            {
                List <string> items  = new List <string>();
                int stringBeginIndex = 0;
                int stringEndIndex   = 0;
                for (int i = 0; i < x.Value.Length; ++i)
                {
                    if (x.Value[i] == 0)
                    {
                        stringEndIndex = i;
                        byte[] path    = new byte[stringEndIndex - stringBeginIndex];
                        Array.Copy(x.Value, stringBeginIndex, path, 0, stringEndIndex - stringBeginIndex);
                        items.Add(Encoding.UTF8.GetString(path));
                        stringBeginIndex = stringEndIndex + 1;
                    }
                }
                System.Diagnostics.Debug.WriteLine("Received inside");
                OnFileManageWriteCompleted?.Invoke(items);
            });
        }
Exemplo n.º 8
0
        private void CreateLockStatusChar()
        {
            //create characteristic to inform connected devices about the lock out
            //status of the buzzer unit

            //lockStatusGuid = Guid.NewGuid();
            lockStatusChar = buzzerService.AddCharacteristic(StaticGuids.lockStatusGuid,
                                                             CharacteristicProperties.Indicate | CharacteristicProperties.Notify,
                                                             GattPermissions.Read | GattPermissions.Write
                                                             );

            lockStatusChar.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                Debug.WriteLine("Got subscriptions: " + e.ToString());
                Debug.WriteLine("UUID" + lockStatusChar.Uuid.ToString());
                //TODO factor this out into a method
                lockStatusChar.Broadcast(Encoding.UTF8.GetBytes(lockStatus + buzzDevice.ToString()));
            });
        }
Exemplo n.º 9
0
        /// <summary>
        /// 创建键盘操作特征
        /// </summary>
        private void CreateKeyboardOperationCharacteristic()
        {
            keyboardOpCharacteristic = controllerService.AddCharacteristic
                                       (
                RemoteUuids.KeyboardOperationCharacteristicGuid,
                CharacteristicProperties.Notify | CharacteristicProperties.Read,
                GattPermissions.Read
                                       );

            keyboardOpCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                ; //当订阅发生改变时
            });

            int number = 0;

            keyboardOpCharacteristic.WhenReadReceived().Subscribe(x =>
            {
                var response = ++number;
                x.Value      = BitConverter.GetBytes(response);

                x.Status = GattStatus.Success;
            });
        }
Exemplo n.º 10
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);
                });
            }
        }
Exemplo n.º 11
0
        private async void Start_Server()
        {
            var server  = CrossBleAdapter.Current.CreateGattServer();
            var service = server.AddService(Guid.NewGuid(), true);

            var characteristic = service.AddCharacteristic(
                Guid.Parse(Constants.GUID_SEND),
                CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,
                GattPermissions.Read | GattPermissions.Write
                );

            notifyCharacteristic = service.AddCharacteristic
                                   (
                Guid.Parse(Constants.GUID_NOTIFY),
                CharacteristicProperties.Indicate | CharacteristicProperties.Notify,
                GattPermissions.Read | GattPermissions.Write
                                   );

            IDisposable notifyBroadcast = null;

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

                if (notifyBroadcast == null)
                {
                    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);
                    });
                }
            });

            characteristic.WhenReadReceived().Subscribe(x =>
            {
                // you must set a reply value
                x.Value = Mess_To_Byte(BluetoothMessageTypes.ACKNOWLEDGE);

                BluetoothMessageTypes mess = Byte_To_Mess(x.Value);
                byte[] data = null;

                if (x.Value.Length >= NUM_BYTES_IN_MESSAGE_TYPE)
                {
                    data = new byte[x.Value.Length - NUM_BYTES_IN_MESSAGE_TYPE];

                    for (int i = 0; i < data.Length; ++i)
                    {
                        data[i] = x.Value[i + NUM_BYTES_IN_MESSAGE_TYPE];
                    }
                }

                BluetoothEventArgs e = new BluetoothEventArgs(mess, data);
                BluetoothRecHandeler.DynamicInvoke(e);

                x.Status = GattStatus.Success; // you can optionally set a status, but it defaults to Success
            });
            characteristic.WhenWriteReceived().Subscribe(x =>
            {
                var write = Encoding.UTF8.GetString(x.Value, 0, x.Value.Length);
                // do something value
            });

            await server.Start(new Plugin.BluetoothLE.Server.AdvertisementData
            {
                LocalName = "TestServer"
            });

            var scanner = CrossBleAdapter.Current.Scan().Subscribe(scanResult =>
            {
                // do something with it
                // the scanresult contains the device, RSSI, and advertisement packet
            });

            scanner.Dispose(); // to stop scanning
        }
Exemplo n.º 12
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);
            }
        }
Exemplo n.º 13
0
        /// <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;
                }
            });
        }