Ejemplo n.º 1
0
        protected async Task <bool> SetupCharacteristicNotifyAsync(Guid characteristicUUID, bool enable, TypedEventHandler <GattCharacteristic, GattValueChangedEventArgs> callback)
        {
            if (Service == null)
            {
                await ConnectServiceAsync();
            }

            if (Service != null)
            {
                GattCharacteristic characteristic = Service.GetCharacteristics(characteristicUUID).FirstOrDefault();
                if (characteristic != null)
                {
                    GattClientCharacteristicConfigurationDescriptorValue value = enable ? GattClientCharacteristicConfigurationDescriptorValue.Notify : GattClientCharacteristicConfigurationDescriptorValue.None;

                    GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(value);

                    if (status == GattCommunicationStatus.Success)
                    {
                        if (enable)
                        {
                            characteristic.ValueChanged += callback;
                        }
                        else
                        {
                            characteristic.ValueChanged -= callback;
                        }

                        return(true);
                    }
                }
            }

            return(false);
        }
        public async Task SetReadPeriod(byte time)
        {
            if (time < 10)
            {
                throw new ArgumentOutOfRangeException("time", "Period can't be lower than 100ms");
            }

            var charForUuid = await deviceService.GetCharacteristicsForUuidAsync(new Guid(SensorTagUuid.UUID_MOV_PERI));

            if (charForUuid.Characteristics.Count > 0)
            {
                GattCharacteristic dataCharacteristic = charForUuid.Characteristics[0];

                byte[] data = new byte[] { time };
                GattCommunicationStatus status = await dataCharacteristic.WriteValueAsync(data.AsBuffer());

                if (status == GattCommunicationStatus.Unreachable)
                {
                    throw new ArgumentOutOfRangeException();
                }
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }
        }
        public void MotorControl(bool isForwardLeft, byte speedLeft, bool isForwardRight, byte speedRight)
        {
            const byte MotorControlType    = 0x01;
            const byte MortorTargetIDLeft  = 0x01;
            const byte MortorTargetIDRight = 0x02;

            byte[] data = new byte[7]
            {
                MotorControlType, MortorTargetIDLeft, (isForwardLeft ? (byte)0x01 : (byte)0x02), speedLeft, MortorTargetIDRight, (isForwardRight ? (byte)0x01 : (byte)0x02), speedRight
            };
            var writer = new DataWriter();

            writer.WriteBytes(data);
            Task task = Task.Run(async() =>
            {
                GattCommunicationStatus result = await CharacteristicMotorControl.WriteValueAsync(writer.DetachBuffer());
                if (result == GattCommunicationStatus.Success)
                {
                    // Successfully wrote to device
                    Debug.WriteLine("MotorControl Success");
                }
                else
                {
                    Debug.WriteLine("MotorControl Failure");
                }
            });

            task.Wait();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Send image size information
        /// </summary>
        /// <returns></returns>
        private async Task <bool> sendImageSize()
        {
            try
            {
                var folder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(this.bin_file));

                StorageFile img = await folder.GetFileAsync(Path.GetFileName(this.bin_file));

                IBuffer firmwareImage_buffer = await FileIO.ReadBufferAsync(img);

                this.firmwareImage = firmwareImage_buffer.ToArray();
                packet             = service.GetCharacteristics(new Guid(DFUService.DFUPacket)).FirstOrDefault();

                IBuffer buffer = ImageSizeCommand(GetSizeOfImage());

                GattCommunicationStatus status = await packet.WriteValueAsync(buffer, GattWriteOption.WriteWithoutResponse);

                if (status == GattCommunicationStatus.Success)
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                log(e.StackTrace, "DFUService");
                log("Error: [sendImageSize]" + e.Message, "DFUService");
            }
            return(false);
        }
Ejemplo n.º 5
0
        private string GetStatusString(GattCommunicationStatus status, byte?protocolError)
        {
            string raw = "";

            switch (status)
            {
            case GattCommunicationStatus.AccessDenied:
                raw = $"BLE: ERROR: Access is denied";
                break;

            case GattCommunicationStatus.ProtocolError:
                if (protocolError.HasValue)
                {
                    raw = $"BLE: Protocol error {protocolError.Value}\n";
                }
                else
                {
                    raw = $"BLE: Protocol error (no protocol error value)\n";
                }
                break;

            case GattCommunicationStatus.Unreachable:
                raw = $"BLE: ERROR: device is unreachable\n";
                break;
            }
            return(raw);
        }
        // Write function for adding control points to a server
        private async Task HandleSensorControlPoint(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {
                // Get current service from base class.
                var service = await GetService();

                // Get current characteristic from current service using the selected values from the base class.
                var characteristic = service.GetCharacteristics(this.SelectedService.Guid)[this.SelectedIndex];

                //Create an instance of a data writer which will write to the relevent buffer.
                DataWriter writer  = new DataWriter();
                byte[]     toWrite = System.Text.Encoding.UTF8.GetBytes(data);
                writer.WriteBytes(toWrite);

                // Attempt to write the data to the device, and whist doing so get the status.
                GattCommunicationStatus status = await characteristic.WriteValueAsync(writer.DetachBuffer());

                // Displays a message box to tell user if the write operation was successful or not.
                if (status == GattCommunicationStatus.Success)
                {
                    MessageHelper.DisplayBasicMessage("Sensor control point has been written.");
                }
                else
                {
                    MessageHelper.DisplayBasicMessage("There was a problem writing the sensor control value, Please try again later.");
                }
            }
        }
Ejemplo n.º 7
0
        private async void WriteCharacteristicValue_Click(object sender, RoutedEventArgs args)
        {
            WriteCharacteristicValueButton.IsEnabled = false;
            try
            {
                var heartRateControlPointCharacteristic = HeartRateService.Instance.Service.GetCharacteristics(
                    GattCharacteristicUuids.HeartRateControlPoint)[0];

                DataWriter writer = new DataWriter();
                writer.WriteByte(2);

                GattCommunicationStatus status = await heartRateControlPointCharacteristic.WriteValueAsync(
                    writer.DetachBuffer());

                if (status == GattCommunicationStatus.Success)
                {
                    rootPage.NotifyUser("Expended Energy successfully reset.", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("Your device is unreachable, most likely the device is out of range, " +
                                        "or is running low on battery, please make sure your device is working and try again.",
                                        NotifyType.StatusMessage);
                }
            }
            catch (Exception e)
            {
                rootPage.NotifyUser("Error: " + e.Message, NotifyType.ErrorMessage);
            }
            WriteCharacteristicValueButton.IsEnabled = true;
        }
Ejemplo n.º 8
0
        private async Task ConfigureServiceForNotificationsAsync()
        {
            try
            {
                _characteristic = _service.GetCharacteristics(CHARACTERISTIC_UUID)[CHARACTERISTIC_INDEX];
                _characteristic.ProtectionLevel = GattProtectionLevel.EncryptionRequired;
                _characteristic.ValueChanged   += Characteristic_ValueChanged;

                var currentDescriptorValue = await _characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();

                if ((currentDescriptorValue.Status != GattCommunicationStatus.Success) || (currentDescriptorValue.ClientCharacteristicConfigurationDescriptor != CHARACTERISTIC_NOTIFICATION_TYPE))
                {
                    GattCommunicationStatus status = await _characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE);

                    if (status == GattCommunicationStatus.Unreachable)
                    {
                        StartDeviceConnectionWatcher();
                    }
                }
            }
            catch (Exception e)
            {
                LoggerWrapper.Instance.WriteToLogFile(e);
            }
        }
Ejemplo n.º 9
0
        private async Task <bool> ClearDevice(string deviceId)
        {
            BluetoothLEDevice curDevice;

            lock (lockObj)
            {
                if (!_devices.TryGetValue(deviceId, out curDevice))
                {
                    return(false);
                }
                _devices.Remove(deviceId);
            }
            GattCommunicationStatus gcs = GattCommunicationStatus.Success;
            var charsToRemove           = _characteristics.Where(x => x.Key.StartsWith(deviceId)).ToArray();

            for (int i = 0; i < charsToRemove.Count(); i++)
            {
                var curChar = charsToRemove.ElementAt(i);
                _characteristics.Remove(curChar);
                gcs = gcs | await curChar.Value.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);
            }
            var servicesToRemove = _services.Where(x => x.Key.StartsWith(deviceId)).ToArray();

            for (int i = 0; i < servicesToRemove.Count(); i++)
            {
                var curSrv = servicesToRemove.ElementAt(i);
                _services.Remove(curSrv);
                curSrv.Value.Dispose();
                gcs = gcs | GattCommunicationStatus.Success;
            }

            curDevice.Dispose();
            return(gcs == GattCommunicationStatus.Success);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Registers characteristic handlers for the device driver module service.
        /// </summary>
        /// <param name="service"></param>
        private async Task RegisterDeviceModuleDriverServiceCharacteristicsAsync(GattDeviceService service)
        {
            //Getting the characteristics of the service.
            GattCharacteristicsResult results = await service.GetCharacteristicsAsync();

            if (results.Status == GattCommunicationStatus.Success)
            {
                foreach (GattCharacteristic characteristic in results.Characteristics)
                {
                    if (characteristic.Uuid == DEVICE_BATTERY_WRITE_CHARACTERISTIC_UUID)
                    {
                        //Caching the device module driver
                        deviceModuleDriverReadWriteCharacteristic = characteristic;

                        //Registering block state changed indicator.
                        GattCommunicationStatus commStatus = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                        if (commStatus == GattCommunicationStatus.Success)
                        {
                            characteristic.ValueChanged += OnDeviceBatteryInfoUpdated;
                            Console.WriteLine("Successfully registered notify for battery read.");
                        }
                        else
                        {
                            OnConnectionError(commStatus);
                        }
                    }
                }
            }
            else
            {
                OnConnectionError(results.Status);
            }
        }
Ejemplo n.º 11
0
        // ping the device to verify if is still reachable
        private async void PingDevice()
        {
            GattCommunicationStatus status = GattCommunicationStatus.ProtocolError;

            // repeat the notify request
            if (IsMiBand2)
            {
                status = await miBand.HeartRate.SetRealtimeHeartRateMeasurement(MiBand2SDK.Enums.RealtimeHeartRateMeasurements.ENABLE);
            }
            else
            {
                status = await HRReaderCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
            }

            if (status == GattCommunicationStatus.Success)
            {
                if (DeviceConnected == false)
                {
                    DeviceConnected = true;//the device is reachable
                    AddLog("Device \"" + ChosenDevice.Name + "\" is reachable again.", AppLog.LogCategory.Info);
                }
            }
            else
            {
                if (DeviceConnected == true)
                {
                    DeviceConnected = false; //the device is not reachable
                    AddLog("Device \"" + ChosenDevice.Name + "\" is NOT reachable. Is it still nearby?", AppLog.LogCategory.Warning);
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Registers characteristic handlers for the device data service.
        /// </summary>
        /// <param name="service"></param>
        private async Task RegisterDataServiceCharacteristicsAsync(GattDeviceService service)
        {
            //Getting the characteristics of the service.
            GattCharacteristicsResult results = await service.GetCharacteristicsAsync();

            if (results.Status == GattCommunicationStatus.Success)
            {
                foreach (GattCharacteristic characteristic in results.Characteristics)
                {
                    if (characteristic.Uuid == DEVICE_DATA_READ_CHARACTERISTIC_UUID)
                    {
                        //Registering block state changed indicator.
                        GattCommunicationStatus commStatus = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                        if (commStatus == GattCommunicationStatus.Success)
                        {
                            characteristic.ValueChanged += OnBlockStateInfoUpdate;
                            Console.WriteLine("Successfully registered notify for data read.");
                        }
                        else
                        {
                            OnConnectionError(commStatus);
                        }
                    }
                }
            }
            else
            {
                OnConnectionError(results.Status);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 设置特征对象为接收通知对象
        /// </summary>
        /// <param name="characteristic"></param>
        /// <returns></returns>
        public async Task EnableNotifications(GattCharacteristic characteristic)
        {
            string msg = "收通知对象=" + CurrentDevice.ConnectionStatus;

            ValueChanged(MsgType.NotifyTxt, msg);

            characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE).Completed = async(asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    GattCommunicationStatus status = asyncInfo.GetResults();
                    if (status == GattCommunicationStatus.Unreachable)
                    {
                        msg = "设备不可用";
                        ValueChanged(MsgType.NotifyTxt, msg);
                        if (CurrentNotifyCharacteristic != null && !asyncLock)
                        {
                            await EnableNotifications(CurrentNotifyCharacteristic);
                        }
                    }
                    asyncLock = false;
                    msg       = "设备连接状态" + status;
                    ValueChanged(MsgType.NotifyTxt, msg);
                }
            };
        }
Ejemplo n.º 14
0
        private async Task <bool> SubscribeToNotificationsInternal(Action <DateTimeOffset, byte[]> readBufferCallback, bool sync)
        {
            var task = new Func <Task <bool> >(async() =>
            {
                if (!await IsHm1xCompatibleDeviceInternal(sync: false))
                {
                    return(false);
                }
                GattCommunicationStatus status = await _characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                if (status != GattCommunicationStatus.Success)
                {
                    throw new Exception($"Failed to subscribe to GATT characteristic {_characteristic.Uuid}: {status}.");
                }

                _externalReadCallback         = readBufferCallback ?? throw new ArgumentNullException(nameof(readBufferCallback));
                _characteristic.ValueChanged += OnCharacteristicValueChanged;
                return(true);
            });

            if (sync)
            {
                await _deviceSemaphore.WaitAsync();
            }
            try
            {
                return(await Task.Run(task));
            }
            finally
            {
                if (sync)
                {
                    _deviceSemaphore.Release();
                }
            }
        }
Ejemplo n.º 15
0
        async void SubscribeBateryLevelService()
        {
            // initialize status
            GattCommunicationStatus status = GattCommunicationStatus.Unreachable;
            var cccdValue = GattClientCharacteristicConfigurationDescriptorValue.None;

            if (BateryLevelCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
            {
                cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
            }
            else if (BateryLevelCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
            {
                cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Notify;
            }

            // BT_Code: Must write the CCCD in order for server to send indications.
            // We receive them in the ValueChanged event handler.
            status = await BateryLevelCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(cccdValue);

            if (status == GattCommunicationStatus.Success)
            {
                AddValueBateryLevelChangedHandler();
                SendConnectionStatusmessageToMCC("Successfully subscribed");
                NotifyStatusMessage?.Invoke("Successfully subscribed for BateryLevel changes");
            }
            else
            {
                SendConnectionStatusmessageToMCC($"Error registering for value changes: {status}");
                NotifyStatusMessage?.Invoke($"Error registering for value changes: {status}", 1);
            }
        }
Ejemplo n.º 16
0
        public async Task <bool> WriteToCharacteristic(string uuid, byte[] message)
        {
            GattCharacteristic characteristic = GetCharacteristic(uuid);

            if (characteristic == null)
            {
                return(false);
            }


            DataWriter writer = new DataWriter();

            // WriteByte used for simplicity. Other common functions - WriteInt16 and WriteSingle
            writer.WriteBytes(message);

            GattCommunicationStatus result = await characteristic.WriteValueAsync(writer.DetachBuffer());

            if (result == GattCommunicationStatus.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 17
0
        private async Task OnGattServicesRefreshed(GattCommunicationStatus status)
        {
            try
            {
                if (status != GattCommunicationStatus.Success)
                {
                    _subjectRefreshed.OnNext(false);
                }
                else
                {
                    await DoRefresh(status);
                }
            }
            catch (Exception e)
            {
                const string message = "Failed to refresh Gatt services";

                _logger.Error(e,
                              message);

                _errorManager.PublishForMessage(message);

                _subjectRefreshed.OnNext(false);
            }
        }
Ejemplo n.º 18
0
        private async Task InitializeGattStreamServiceCharateristics(BluetoothLEDeviceDisplay deviceInfoDisp)
        {
            var _gattStreamService = await GattDeviceService.FromIdAsync(deviceInfoDisp.Id);

            Debug.WriteLine("\n" + _gattStreamService + ":   " + _gattStreamService.Device.Name + "\n");
            this.NotifyUser("Getting GATT Services", NotifyType.StatusMessage);



            // Get the Tx characteristic - We will get data from this Characteristics
            var _characteristicsStreamTx = GetCharacteristics(_gattStreamService, UuidDefs.GATT_STREAM_TX_CHARACTERISTIC_UUID);

            Debug.Assert(_characteristicsStreamTx != null);


            // Set the Client Characteristic Configuration Descriptor to "Indicate"
            GattCommunicationStatus status = await _characteristicsStreamTx[0].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);

            // Get the Rx characteristic - We will send data to this Characteristics
            var _characteristicsStreamRx = GetCharacteristics(_gattStreamService, UuidDefs.GATT_STREAM_RX_CHARACTERISTIC_UUID);

            Debug.Assert(_characteristicsStreamRx != null);

            //Debug_ListCharacteristics();

            // This is the ValueChanged handler: Set an handler to the characteristicsTx
            // _characteristicsStreamTx[0].ValueChanged += CharacteristicsTx_ValueChanged;
        }
        // Notify operation which handles creating a value changed event.
        private async Task HandleHeartRateMeasurment(bool handleNotofication)
        {
            // Get service object from base class.
            var service = await GetService();

            // Get current characteristic from current service using the selected values from the base class.
            var characteristic = service.GetCharacteristics(this.SelectedService.Guid)[this.SelectedIndex];

            // Check to see if we are attching or detatching event.
            if (handleNotofication)
            {
                // Attach a listener and assign a pointer to a function which will handle the data as it comes into the application.
                characteristic.ValueChanged += Characteristic_ValueChanged;

                // Tell the device we want to register for the indicate updates, and return the staus of the registration.
                GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                // Check to see if the registration was successful by checking the status, if not display a message telling the user.
                if (status == GattCommunicationStatus.Unreachable)
                {
                    MessageHelper.DisplayBasicMessage("Your device is currently unavailible, please try again later.");
                }
            }
            else
            {
                // Remove the pointer to the local function to stop processing updates.
                characteristic.ValueChanged -= Characteristic_ValueChanged;
                ReturnResult("");
            }
        }
Ejemplo n.º 20
0
        private async void ConnectMenuItem_Click(object sender, EventArgs e)
        {
            if (this.NotificationConsumer == null)
            {
                if (this.BluetoothConnectDialog == null)
                {
                    this.BluetoothConnectDialog = new BluetoothConnectDialog();
                }

                if (this.BluetoothConnectDialog.Visible)
                {
                    this.BluetoothConnectDialog.Activate();
                    this.BluetoothConnectDialog.Focus();
                }
                else
                {
                    this.BluetoothConnectDialog.ShowDialog();
                }
            }
            else
            {
                GattCommunicationStatus communicationStatus = GattCommunicationStatus.Unreachable;

                try
                {
                    communicationStatus = await this.NotificationConsumer.SubscribeAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (communicationStatus == GattCommunicationStatus.Success)
                {
                    this.ConnectMenuItem.Visible    = false;
                    this.DisconnectMenuItem.Visible = true;

                    // Minimal Toast notification telling the user we are connected
                    // Get a toast XML template
                    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                    // Fill in the text elements
                    XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
                    stringElements[0].AppendChild(toastXml.CreateTextNode("Connected"));
                    stringElements[1].AppendChild(toastXml.CreateTextNode("You are now connected to " + this.NotificationConsumer.DeviceService.Device.DeviceInformation.Name));

                    ToastNotification toastNotification = new ToastNotification(toastXml);
                    toastNotification.ExpirationTime = DateTime.Now.AddSeconds(5);
                    toastNotification.Tag            = "connected";
                    toastNotification.Group          = "-1";

                    ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toastNotification);
                }
                else
                {
                    MessageBox.Show("Failed to connect", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 设置特征对象为接收通知对象
        /// </summary>
        /// <param name="characteristic"></param>
        /// <returns></returns>
        public async Task EnableNotifications(GattCharacteristic characteristic)
        {
            if (CurrentDevice.ConnectionStatus != BluetoothConnectionStatus.Connected)
            {
                this.MessAgeLog(MsgType.NotifyTxt, "蓝牙未连接!");
                return;
            }

            characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE).Completed = async(asyncInfo, asyncStatus) =>
            {
                Console.WriteLine("asyncStatus:" + asyncStatus);
                if (asyncStatus == AsyncStatus.Completed)
                {
                    GattCommunicationStatus status = asyncInfo.GetResults();

                    asyncLock = false;
                    string msg = "Notify(" + characteristic.Uuid.ToString() + "):" + status;
                    this.MessAgeLog(MsgType.NotifyTxt, msg);
                }
                else
                {
                    Console.WriteLine(asyncInfo.ErrorCode.ToString());
                }
            };
        }
Ejemplo n.º 22
0
        public async Task <GattCommunicationStatus> StartNotify(GattCharacteristic characteristic, TypedEventHandler <GattCharacteristic, byte[]> callback)
        {
            // initialize status
            GattCommunicationStatus status = GattCommunicationStatus.Unreachable;
            var cccdValue = GattClientCharacteristicConfigurationDescriptorValue.None;

            if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
            {
                cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
            }

            else if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
            {
                cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Notify;
            }

            status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(cccdValue);

            if (status == GattCommunicationStatus.Success)
            {
                // Server has been informed of clients interest.
                try
                {
                    this.callbacks[characteristic.Uuid] = callback;
                    characteristic.ValueChanged        += Characteristic_ValueChanged;
                }
                catch (UnauthorizedAccessException ex)
                {
                    // This usually happens when a device reports that it support indicate, but it actually doesn't.
                    // TODO: Do not use Indicate? Return with Notify?
                    return(GattCommunicationStatus.AccessDenied);
                }
            }
            return(status);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Write the image trunks to the packet characteristic
        /// </summary>
        /// <param name="trunks"></param>
        /// <param name="limitation"></param>
        private async void WriteImage2(byte[][] trunks, int limitation)
        {
            while (sentTimes < limitation)
            {
                if (sentTimes > trunks[sentTimes].Length)
                {
                    log("sentTimes:" + sentTimes + " trunks:" + trunks[sentTimes].Length, "Exception");
                    throw new ApplicationArgumentException();
                }

                /*
                 * var buffer = deviceFirmwareUpdateControlPointCharacteristics.
                 * PartialOfFirmwareImage(trunks, sentTimes);
                 */

                var     temp   = trunks[sentTimes];
                IBuffer buffer = temp.AsBuffer();

                GattCommunicationStatus status = await packet.WriteValueAsync(buffer, GattWriteOption.WriteWithoutResponse);

                sendedBytes += trunks[sentTimes].Length;
                if (status == GattCommunicationStatus.Success)
                {
                    log("Trunk:" + sentTimes + " of " + limitation + " Bytes:" + sendedBytes, "Status");
                }
                else
                {
                    log("Trunk:" + sentTimes + " Unreacheable", "Status");
                }

                sentTimes++;
            }
        }
        public async void sendMode(TAPInputMode overrideMode = null)
        {
            if (this.isReady && this.IsConnected)
            {
                TAPInputMode mode = overrideMode == null ? this.InputMode : overrideMode;
                mode = mode.makeCompatibleWithFWVersion(this.fw);
                if (mode.isValid)
                {
                    byte[] data = mode.getBytes();
                    Debug.WriteLine("[{0}]", string.Join(", ", data));
                    DataWriter writer = new DataWriter();
                    writer.WriteBytes(data);
                    GattCommunicationStatus result = await rx.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);



                    //if (mode != TAPInputMode.Null)
                    //{

                    //    if (mode == TAPInputMode.Controller_With_MouseHID && this.fw < 010615) {
                    //        Debug.WriteLine("NOT SUPPORTED");
                    //        mode = TAPInputMode.Controller;
                    //    }

                    //    DataWriter writer = new DataWriter();

                    //    byte[] data = { 0x3, 0xc, 0x0, (byte)mode };
                    //    writer.WriteBytes(data);
                    //    TAPManagerLog.Instance.Log(TAPManagerLogEvent.Info, String.Format("TAP {0} ({1}) Sent mode ({2})", this.Name, this.Identifier, mode.ToString()));
                    //    GattCommunicationStatus result = await rx.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
                    //}
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// This method writes data to microcontroller over bluetooth low energy protocol.
        /// </summary>
        /// <param name="msg">The message in string to send. Max 20 characters.</param>
        private async void WriteData(string msg)
        {
            if (_currentDevice == null)
            {
                return;
            }

            var writer = new DataWriter();

            // WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle
            writer.WriteString(msg);
            GattCommunicationStatus status = GattCommunicationStatus.Unreachable;

            if (_txCharacteristic != null)
            {
                status = await _txCharacteristic.WriteValueAsync(writer.DetachBuffer());
            }

            if (status == GattCommunicationStatus.Success)
            {
                // Successfully wrote to device
            }
            writer.Dispose();
            _notDone = true;
        }
        internal async void Vibrate(int[] durations)
        {
            if (durations == null || this.uiCommands == null || !this.isReady || !this.IsConnected)
            {
                return;
            }
            byte[] data = new byte[20];
            data[0] = 0;
            data[1] = 2;
            for (int i = 0; i < data.Length - 2; i++)
            {
                if (i < durations.Length)
                {
                    data[i + 2] = (byte)((double)durations[i] / (double)10.0);
                }
                else
                {
                    data[i + 2] = 0;
                }
            }
            DataWriter writer = new DataWriter();

            writer.WriteBytes(data);

            GattCommunicationStatus result = await this.uiCommands.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
        }
        /* Method */
        public async void InitializeDevice()
        {
            /*** Get a list of devices that match desired service UUID  ***/
            Guid selectedService = new Guid("0000AA10-0000-1000-8000-00805F9B34FB");
            var  devices         = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(selectedService));

            /*** Create an instance of the eTDS device ***/
            DeviceInformation eTdsDevice = devices[0];              // Only one device should be matching the eTDS-specific service UUID

            Console.WriteLine("Device Name: {0}", eTdsDevice.Name); // Display the name of the device

            /*** Create an instance of the specified eTDS service ***/
            GattDeviceService myService = await GattDeviceService.FromIdAsync(eTdsDevice.Id);

            Console.WriteLine("Service UUID: {0}", myService.Uuid.ToString());

            /*** Create an instance of the characteristic of the specified service ***/
            Guid               selectedCharacteristic = new Guid("0000AA11-0000-1000-8000-00805F9B34FB");
            const int          CHARACTERISTIC_INDEX   = 0;
            GattCharacteristic myCharacteristic       = myService.GetCharacteristics(selectedCharacteristic)[CHARACTERISTIC_INDEX];

            myCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;  // Set security level to "No encryption"

            /*** Create an event handler when the characteristic value changes ***/
            myCharacteristic.ValueChanged -= myCharacteristic_ValueChanged;
            GattCommunicationStatus disableNotifStatus = await myCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);

            Console.WriteLine("Disable Notification Status: {0}", disableNotifStatus);

            myCharacteristic.ValueChanged += myCharacteristic_ValueChanged;
            GattCommunicationStatus enableNotifStatus = await myCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            Console.WriteLine("Enable Notification Status: {0}", disableNotifStatus);
        }//end method InitializeDevice
Ejemplo n.º 28
0
        //function that handles write event
        private async void WriteBtn_Click(object sender, EventArgs e)
        {
            if (currentSelectedService != null && currentSelectedCharacteristic != null)
            {
                GattCharacteristicProperties properties = currentSelectedCharacteristic.CharacteristicProperties;
                if (properties.HasFlag(GattCharacteristicProperties.Write))
                {
                    var writer       = new DataWriter();
                    var startCommand = Encoding.ASCII.GetBytes(InputTxtBox.Text);
                    writer.WriteBytes(startCommand);

                    GattCommunicationStatus result = await currentSelectedCharacteristic.WriteValueAsync(writer.DetachBuffer());

                    if (result == GattCommunicationStatus.Success)
                    {
                        Respond("message sent successfully");
                    }
                    else
                    {
                        Respond("Error encountered on writing to characteristic!");
                    }
                }
                else
                {
                    Respond("No write property for this characteristic!");
                }
            }
            else
            {
                Respond("Please connect to a device first!");
            }
        }
Ejemplo n.º 29
0
        public async Task <bool> SetPosition(byte position, byte speed)
        {
            try
            {
                if (!await Initialize())
                {
                    return(false);
                }

                GattWriteOption option = SendCommandsWithResponse
                    ? GattWriteOption.WriteWithResponse
                    : GattWriteOption.WriteWithoutResponse;

                IBuffer buffer = GetBuffer(position, speed);
                GattCommunicationStatus result = await _writeCharacteristics.WriteValueAsync(buffer, option);

                return(result == GattCommunicationStatus.Success);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                OnDisconnected(e);
                return(false);
            }
        }
Ejemplo n.º 30
0
        public async void sendMode(TAPInputMode overrideMode = TAPInputMode.Null)
        {
            TAPInputMode mode = overrideMode == TAPInputMode.Null ? this.InputMode : overrideMode;

            if (mode != TAPInputMode.Null)
            {
                if (this.isReady && this.IsConnected)
                {
                    if (mode != TAPInputMode.Null)
                    {
                        if (mode == TAPInputMode.Controller_With_MouseHID && this.fw < 010615)
                        {
                            Debug.WriteLine("NOT SUPPORTED");
                            mode = TAPInputMode.Controller;
                        }

                        DataWriter writer = new DataWriter();

                        byte[] data = { 0x3, 0xc, 0x0, (byte)mode };
                        writer.WriteBytes(data);
                        TAPManagerLog.Instance.Log(TAPManagerLogEvent.Info, String.Format("TAP {0} ({1}) Sent mode ({2})", this.Name, this.Identifier, mode.ToString()));
                        GattCommunicationStatus result = await rx.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
                    }
                }
            }
        }