示例#1
0
        // Helper function for async Read callback
        protected virtual async void Characteristic_ReadRequested(
            GattLocalCharacteristic sender,
            GattReadRequestedEventArgs args,
            Deferral deferral = null
            )
        {
            Debug.WriteLine($"base.Characteristic_ReadRequested Entry");

            // Get an event deferral for async operations if we don't have one
            if (deferral == null)
            {
                deferral = args.GetDeferral();
            }

            //
            // Normally, GetRequestAsync() is recommended to run on a UI thread
            // because, even with paired devices, the device may prompt the
            // user for consent. But, we're running in a background service so
            // we won't run this on a UI thread. According to one of the devs
            // on the core Bluetooth team, because this is for a "test
            // application," consent prompts are not currently part of MS's
            // policy and it will be auto-accepted.
            //
            var request = await args.GetRequestAsync();

            request.RespondWithValue(Value);
            Debug.WriteLine($"Characteristic ReadRequested- Length: " +
                            $"{request.Length}, State: {request.State}, " +
                            $"Offset: {request.Offset}"
                            );

            deferral.Complete();

            Debug.WriteLine("base.Characteristic_ReadRequested Exit");
        }
示例#2
0
        private async void TreadmillDataCharacteristic_ReadRequestedAsync(GattLocalCharacteristic sender,
                                                                          GattReadRequestedEventArgs args)
        {
            using (args.GetDeferral())
            {
                var request = await args.GetRequestAsync();

                request.RespondWithValue(GetTreadmillDataPackage(_currentSpeed));
            }
        }
示例#3
0
        //---------------------------------------------------------------------
        // Event callback for Read
        //---------------------------------------------------------------------

        protected virtual void Characteristic_ReadRequested(
            GattLocalCharacteristic sender,
            GattReadRequestedEventArgs args
            )
        {
            // Get an event deferral for async operations
            var deferral = args.GetDeferral();

            Characteristic_ReadRequested(sender, args, deferral);
        }
        private async void AccData_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            var deferral = args.GetDeferral();
            var request  = await args.GetRequestAsync();

            var writer = new DataWriter();

            writer.WriteBytes(new byte[6] {
                0x12, 0x12, 0x12, 0x12, 0x12, 0x12
            });
            request.RespondWithValue(writer.DetachBuffer());
            deferral.Complete();
        }
        private async void readStopButtonValue(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            var deferral = args.GetDeferral();

            var writer = new DataWriter();

            writer.ByteOrder = ByteOrder.LittleEndian;
            writer.WriteByte((byte)stopButtonState);

            var request = await args.GetRequestAsync();

            request.RespondWithValue(writer.DetachBuffer());

            deferral.Complete();
        }
示例#6
0
        /// <summary>
        /// Updates the Value which is what gets send back by the <see cref="base.Characteristic_ReadRequested"/>. It verifies that the
        /// source data is bigger than a single read request so that a ReadBlobRequest has to be done
        /// </summary>
        /// <param name="args"></param>
        private async Task UpdateValue(GattReadRequestedEventArgs args)
        {
            DataWriter writer         = new DataWriter();
            int        maxPayloadSize = args.Session.MaxPduSize - 1;

            // start getting the read request
            var requestTask = args.GetRequestAsync();

            // make sure our source data is bigger than a single read request to make sure a ReadBlobRequest is done
            if (longCharacteristicData.Length < maxPayloadSize)
            {
                // This should not be required as the server should only be processing one request at a time
                // but it's better to be safe than sorry
                lock (dataLock)
                {
                    longCharacteristicData = new byte[(int)(maxPayloadSize * 2.5)];

                    for (int i = 0; i < longCharacteristicData.Length; i++)
                    {
                        longCharacteristicData[i] = (byte)(i % 10);
                    }
                }
            }

            // finish getting the read request
            GattReadRequest request = await requestTask;
            int             offset  = (int)request.Offset;

            // calculate the size of the data we send back
            int chunk = Math.Min(maxPayloadSize, longCharacteristicData.Length - offset);

            Debug.WriteLine($"UpdateValue: payloadSize: {maxPayloadSize}, chunk {chunk}");

            // prep the data we send back
            var readValue = String.Empty;
            var buffer    = new byte[chunk];

            buffer.Initialize();

            // copy from source to target
            Array.Copy(longCharacteristicData, longCharacteristicReadOffset, buffer, 0, chunk);

            // write to our internal Value which will be used to send back the data
            writer.WriteBytes(buffer);
            readValue = buffer.BytesToString();
            Debug.WriteLine("MicrosoftReadLongCharacteristic: Read request value: {readValue}");
            Value = writer.DetachBuffer();
        }
        private async void WifiListCharacteristic_ReadRequestedAsync(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            using (args.GetDeferral())
            {
                // Get the request information.  This requires device access before an app can access the device's request.
                GattReadRequest request = await args.GetRequestAsync();

                if (request == null)
                {
                    // No access allowed to the device.  Application should indicate this to the user.
                    return;
                }

                var writer = new DataWriter();

                var result = JsonConvert.SerializeObject(
                    new WIfiNetworkPayload
                {
                    AvailableAdapters =
                        this.WiFiAdapter.NetworkReport.AvailableNetworks.Select(x => new WifiNetwork {
                        Ssid = x.Ssid
                    })
                });

                writer.WriteString(result);
                //var wifiAdapters =
                //writer.WriteString("{ \"AvailableAdapters\": [{ \"Ssid\": \"ilab\" }, { \"Ssid\": \"uqconnect\" }] }");

                // Gatt code to handle the response
                request.RespondWithValue(writer.DetachBuffer());
            }
        }
        private async void RossCharacteristic_ReadRequestedAsync(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            using (args.GetDeferral())
            {
                // Get the request information.  This requires device access before an app can access the device's request.
                GattReadRequest request = await args.GetRequestAsync();

                if (request == null)
                {
                    // No access allowed to the device.  Application should indicate this to the user.
                    return;
                }

                var writer = new DataWriter();

                writer.WriteString("1.5.14.0");

                // Gatt code to handle the response
                request.RespondWithValue(writer.DetachBuffer());
            }
        }
示例#9
0
        private async void Characteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            var deferral = args.GetDeferral();

            // Our familiar friend - DataWriter.
            var writer = new DataWriter();
            // populate writer w/ some data.
            // ...

            var request = await args.GetRequestAsync();

            request.RespondWithValue(writer.DetachBuffer());

            deferral.Complete();
        }
示例#10
0
        /// <summary>
        /// Base implementation for the read callback
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <param name="deferral">The deferral in case a specific implementation had to do async tasks</param>
        protected virtual async void Characteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args, Deferral deferral = null)
        {
            // Grab the event deferral before performing any async operations in the handler.
            if (deferral == null)
            {
                deferral = args.GetDeferral();
            }

            Debug.WriteLine($"({this.GetType()})Entering base.Characteristic_ReadRequested");

            // In order to get the remote request, access to the device must be provided by the user.
            // This can be accomplished by calling BluetoothLEDevice.RequestAccessAsync(), or by getting the request on the UX thread.
            //
            // Note that subsequent calls to RequestAccessAsync or GetRequestAsync for the same device do not need to be called on the UX thread.
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                CoreDispatcherPriority.Normal,
                async() =>
            {
                var request = await args.GetRequestAsync();
                request.RespondWithValue(Value);
                Debug.WriteLine($"Characteristic_ReadRequested - Length {request.Length}, State: {request.State}, Offset: {request.Offset}");
            });
        }
        private async void StatusCharacteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            var deferral = args.GetDeferral();

            var request = await args.GetRequestAsync();

            if (request == null)
            {
                return;
            }

            request.RespondWithValue(GetStatusBuffer());

            deferral.Complete();
        }
示例#12
0
        private async void OnCharacteristicReadRequested(GattLocalCharacteristic characteristic, GattReadRequestedEventArgs args)
        {
            Utils.Info("OnReadRequested: {0}", args.Session.DeviceId.Id);

            using (var deferral = args.GetDeferral())
            {
                var request = await args.GetRequestAsync().AsTask();

                Utils.Info("length: {0} offset: {1}", request.Length, request.Offset);

                lock (mLockObject)
                {
                    if ((mStatus != Status.Ready) && (mStatus != Status.Advertise))
                    {
                        Utils.Error("invalid status: {0}", mStatus.ToString());
                        request.RespondWithProtocolError(GattProtocolError.RequestNotSupported);
                        return;
                    }

                    var context = mSubscribedCentrals.Where(ctx => ctx.client.Session.DeviceId.Id == args.Session.DeviceId.Id).FirstOrDefault();
                    if (context == null)
                    {
                        Utils.Error("not subscribed");
                        request.RespondWithProtocolError(GattProtocolError.InsufficientAuthentication);
                        return;
                    }

                    if (request.Offset != 0)
                    {
                        Utils.Error("invalid parameter");
                        request.RespondWithProtocolError(GattProtocolError.InvalidPdu);
                        return;
                    }

                    byte[] value;

                    if (context.sendBufferWriter.BaseStream.Length > 0)
                    {
                        value = ProcessSendBuffer(context, (int)request.Length);
                        Utils.Info("respond: {0} bytes remain {1} bytes {2}", value.Length, context.sendBufferWriter.BaseStream.Length, context.client.Session.DeviceId.Id);
                    }
                    else
                    {
                        Utils.Info("respond: empty");
                        value = new byte[0];
                        context.valueWriting = false;
                    }

                    request.RespondWithValue(value.AsBuffer());
                }
            }
        }
示例#13
0
        /// <summary>
        /// Read request callback to update the value
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected override async void Characteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            Deferral deferral = args.GetDeferral();

            Debug.WriteLine($"MSFTLongReadCharacteristic: ReadRequested - MaxPduSize {args.Session.MaxPduSize}");
            await UpdateValue(args);

            base.Characteristic_ReadRequested(sender, args, deferral);
        }
        private async void ResultCharacteristic_ReadRequestedAsync(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            // BT_Code: Process a read request.
            using (args.GetDeferral())
            {
                // Get the request information.  This requires device access before an app can access the device's request.
                GattReadRequest request = await args.GetRequestAsync();

                if (request == null)
                {
                    // No access allowed to the device.  Application should indicate this to the user.
                    rootPage.NotifyUser("Access to device not allowed", NotifyType.ErrorMessage);
                    return;
                }

                var writer = new DataWriter();
                writer.ByteOrder = ByteOrder.LittleEndian;
                writer.WriteInt32(resultVal);

                // Can get details about the request such as the size and offset, as well as monitor the state to see if it has been completed/cancelled externally.
                // request.Offset
                // request.Length
                // request.State
                // request.StateChanged += <Handler>

                // Gatt code to handle the response
                request.RespondWithValue(writer.DetachBuffer());
            }
        }
        /// <summary>
        /// Base implementation for the read callback
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void Characteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            // Grab the event deferral before performing any async operations in the handler.
            var deferral = args.GetDeferral();

            Debug.WriteLine($"({this.GetType()})Entering base.Characteristic_ReadRequested");

            // In order to get the remote request, access to the device must be provided by the user.
            // This can be accomplished by calling BluetoothLEDevice.RequestAccessAsync(), or by getting the request on the UX thread.
            //
            // Note that subsequent calls to RequestAccessAsync or GetRequestAsync for the same device do not need to be called on the UX thread.
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(
                async() =>
            {
                var request = await args.GetRequestAsync();
                if (request != null)
                {
                    Debug.WriteLine($"Characteristic_ReadRequested - Length {request.Length}, State: {request.State}, Offset: {request.Offset}");

                    if (!ReadRequested(args.Session, request))
                    {
                        request.RespondWithValue(Value);
                    }
                }
                else
                {
                    var Msg = new MessageDialog("There was a communication issue. As a temporary workaround, please try pairing the device with Windows first.", "BLE HackMe Comm. Issue");
                    await Msg.ShowAsync();
                }

                deferral.Complete();
            });
        }
示例#16
0
        /// <summary>
        /// Event handler for reading Current time
        /// </summary>
        /// <param name="sender">The source of the Write request</param>
        /// <param name="args">Details about the request</param>
        private async void ReadCharacteristicReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            var request = await args.GetRequestAsync();

            request.RespondWithValue(GattServicesHelper.ConvertValueToBuffer(DateTime.Now));
        }
 /// <summary>
 /// Read request callback to update the value
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 protected override void Characteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
 {
     System.Diagnostics.Debug.WriteLine("Entering MSFTReadRequest.Characteristic_ReadRequested");
     UpdateValue();
     base.Characteristic_ReadRequested(sender, args);
 }
示例#18
0
        /// <summary>
        /// Method for handling stdin on the Write Characteristic UUID
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void ReadCharacteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            var deferral = args.GetDeferral();
            var writer   = new DataWriter();

            // Buffer to fill cmd output.
            byte[] cmdCharacter = new byte[1];

            //set the last time the client requested a read - used for indicate

            // Checks if buffer captured data.
            if (cmd.getQueueLength() > 0)
            {
                cmd.setLastReadTime();
                if (cmd.getQueueLength() < 510)
                {
                    cmdCharacter = cmd.getQueuedData(cmd.getQueueLength());
                }
                else
                {
                    cmdCharacter = cmd.getQueuedData(510);
                }
                writer.WriteBytes(cmdCharacter);
                var request = await args.GetRequestAsync();

                request.RespondWithValue(writer.DetachBuffer());
            }
            else
            {
                var empty = new DataWriter();
                empty.WriteByte(0);
                var request = await args.GetRequestAsync();

                request.RespondWithValue(empty.DetachBuffer());
            }

            // Deferal ensures the await task is done.
            deferral.Complete();
        }
示例#19
0
        /// <summary>
        /// Base implementation for the read callback
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected virtual void Characteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            // Grab the event deferral before performing any async operations in the handler.
            var deferral = args.GetDeferral();

            Characteristic_ReadRequested(sender, args, deferral);
        }