예제 #1
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;
            });
        }
예제 #2
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());
            });
        }
예제 #3
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);
            });
        }
예제 #4
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;
            });
        }
예제 #5
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;
                }
            });
        }