private void WriteLighMode(uint lightMode)
        {
            Task.Run(async() =>
            {
                OnewheelBoard onewheel = OnewheelConnectionHelper.INSTANCE.GetOnewheel();
                if (onewheel is null)
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => ShowInfo("Updating light mode failed - not connected!", 5000));
                }
                else
                {
                    GattWriteResult result = await onewheel.WriteShortAsync(OnewheelCharacteristicsCache.CHARACTERISTIC_LIGHTING_MODE, (short)lightMode);

                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        if (result != null && result.Status == GattCommunicationStatus.Success)
                        {
                            ShowInfo("💡 Light mode updated!", 5000);
                        }
                        else
                        {
                            ShowInfo("Failed to update light mode: " + (result == null ? "characteristic not found" : result.Status.ToString()), 5000);
                        }
                    });
                }
            });
        }
예제 #2
0
        public async Task <GattWriteResult> DoWriteString(string str)
        {
            GattWriteOption writeOption = PreferredWriteOption();
            var             bytes       = Encoding.UTF8.GetBytes(str);
            const int       MAXBYTES    = 20;

            if (bytes.Length > MAXBYTES)
            {
                GattWriteResult status = null;

                for (int i = 0; i < bytes.Length; i += MAXBYTES)
                {
                    // So many calculations and copying just to get a slice
                    var maxCount   = Math.Min(MAXBYTES, bytes.Length - i);
                    var subcommand = new ArraySegment <byte>(bytes, i, maxCount).ToArray().AsBuffer();
                    status = await Characteristic.WriteValueWithResultAsync(subcommand, writeOption);
                }
                return(status);
            }

            else
            {
                var data   = bytes.AsBuffer();
                var status = await Characteristic.WriteValueWithResultAsync(data, writeOption);

                return(status);
            }
        }
예제 #3
0
        /// <inheritdoc />
        public IGattWriteResultWrapper Create(GattWriteResult result)
        {
            Guard.ArgumentNotNull(result,
                                  nameof(result));

            return(_factory.Invoke(result));
        }
예제 #4
0
        protected override async Task StartUpdatesNativeAsync()
        {
            this._nativeCharacteristic.ValueChanged += this.OnCharacteristicValueChanged;
            GattWriteResult result =
                await this._nativeCharacteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.Notify);

            //output trace message with status of update
            if (result.Status == GattCommunicationStatus.Success)
            {
                Trace.Message("Start Updates Successful");
            }
            else if (result.Status == GattCommunicationStatus.AccessDenied)
            {
                Trace.Message("Incorrect permissions to start updates");
            }
            else if (result.Status == GattCommunicationStatus.ProtocolError && result.ProtocolError != null)
            {
                Trace.Message("Start updates returned with error: {0}", this.parseError(result.ProtocolError));
            }
            else if (result.Status == GattCommunicationStatus.ProtocolError)
            {
                Trace.Message("Start updates returned with unknown error");
            }
            else if (result.Status == GattCommunicationStatus.Unreachable)
            {
                Trace.Message("Characteristic properties are unreachable");
            }
        }
        public GattWriteResultWrapper([JetBrains.Annotations.NotNull] GattWriteResult result)
        {
            Guard.ArgumentNotNull(result,
                                  nameof(result));

            _result = result;
        }
예제 #6
0
        public async Task Send(IBuffer buffer)
        {
            if (WriteableCharacteristics != null)
            {
                GattWriteResult result = await WriteCharacteristic.WriteValueWithResultAsync(buffer);

                Console.WriteLine(result);
            }
        }
예제 #7
0
        /// <summary>
        /// Write a value into a GATT characteristic
        /// </summary>
        /// <param name="characteristic">GATT characteristic</param>
        /// <param name="value">Value</param>
        /// <returns>true if the operation succeeded, false otherwise</returns>
        public async Task <bool> WriteValueAsync(BleGattCharacteristic characteristic, BleValue value)
        {
            bool ret = false;

            GattCharacteristic gatt_characteristic = characteristic.Context as GattCharacteristic;
            IBuffer            buffer = CryptographicBuffer.CreateFromByteArray(value.Value);
            GattWriteResult    result = await gatt_characteristic.WriteValueWithResultAsync(buffer, GattWriteOption.WriteWithResponse);

            if (result.Status == GattCommunicationStatus.Success)
            {
                ret = true;
            }

            return(ret);
        }
예제 #8
0
        public async Task <bool> StopQueryingLineSensor()
        {
            GattWriteResult result = await this.responseCharacteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.None)
                                     .AsTask()
                                     .ConfigureAwait(false);

            if (result.Status != GattCommunicationStatus.Success)
            {
                this.logger.Error($"failed to disable notification for '{RESPONSE_CHARACTERISTICS_GUID}' charactersitic for '{SERVICE_GUID}' " +
                                  $"service on BLE device with id = '{this.bluetoothLeDevice.DeviceId}', result = '{result.Status}', protocol error = '{result.ProtocolError}'");
                return(false);
            }

            return(true);
        }
예제 #9
0
        public async Task <GattCommunicationStatus> WriteCharacteristicValueAsync(GattCharacteristic characteristic, byte[] data, bool withResponse)
        {
            var writer = new DataWriter();

            writer.WriteBytes(data);
            if (withResponse)
            {
                GattWriteResult result = await characteristic.WriteValueWithResultAsync(writer.DetachBuffer());

                return(result.Status);
            }
            else
            {
                return(await characteristic.WriteValueAsync(writer.DetachBuffer()));
            }
        }
예제 #10
0
        protected override async Task <Boolean> WriteNativeAsync(Byte[] data, CharacteristicWriteType writeType)
        {
            //print errors if error and write with response
            if (writeType == CharacteristicWriteType.WithResponse)
            {
                GattWriteResult result =
                    await this._nativeCharacteristic.WriteValueWithResultAsync(
                        CryptographicBuffer.CreateFromByteArray(data));

                if (result.Status == GattCommunicationStatus.Success)
                {
                    Trace.Message("Write successful");
                    return(true);
                }

                if (result.Status == GattCommunicationStatus.AccessDenied)
                {
                    Trace.Message("Incorrect permissions to stop updates");
                }
                else if (result.Status == GattCommunicationStatus.ProtocolError && result.ProtocolError != null)
                {
                    Trace.Message("Write Characteristic returned with error: {0}",
                                  this.parseError(result.ProtocolError));
                }
                else if (result.Status == GattCommunicationStatus.ProtocolError)
                {
                    Trace.Message("Write Characteristic returned with unknown error");
                }
                else if (result.Status == GattCommunicationStatus.Unreachable)
                {
                    Trace.Message("Characteristic write is unreachable");
                }
                return(false);
            }

            GattCommunicationStatus status =
                await this._nativeCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data),
                                                                 GattWriteOption.WriteWithoutResponse);

            if (status == GattCommunicationStatus.Success)
            {
                return(true);
            }
            return(false);
        }
예제 #11
0
        private async Task<int> send_command_async (string command, bool use_send_characteristic = true)
        {
            if (ganglion_device == null)
            {
                return (int) CustomExitCodes.GANGLION_IS_NOT_OPEN_ERROR;
            }
            if (send_characteristic == null)
            {
                return (int) CustomExitCodes.SEND_CHARACTERISTIC_NOT_FOUND_ERROR;
            }

            var writer = new Windows.Storage.Streams.DataWriter ();
            writer.WriteString (command);
            try
            {
                GattWriteResult result = null;
                if (use_send_characteristic)
                {
                    result = await send_characteristic.WriteValueWithResultAsync (writer.DetachBuffer ()).AsTask ().TimeoutAfter (timeout);
                }
                else
                {
                    result = await disconnect_characteristic.WriteValueWithResultAsync (writer.DetachBuffer ()).AsTask ().TimeoutAfter (timeout);
                }
                if (result.Status == GattCommunicationStatus.Success)
                {
                    return (int) CustomExitCodes.STATUS_OK;
                }
                else
                {
                    return (int) CustomExitCodes.STOP_ERROR;
                }
            }
            catch (TimeoutException e)
            {
                return (int) CustomExitCodes.TIMEOUT_ERROR;
            }
            catch (Exception e)
            {
                return (int) CustomExitCodes.GENERAL_ERROR;
            }
            return (int) CustomExitCodes.STATUS_OK;
        }
예제 #12
0
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--


        #endregion
        //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
        #region --Misc Methods (Public)--
        public async Task <GattWriteResult> ChangeBoardNameAsync(ChangeBoardNameDialogContext context)
        {
            if (context.MODEL.Accepted)
            {
                GattWriteResult result = await OnewheelConnectionHelper.INSTANCE.GetOnewheel().WriteStringAsync(OnewheelCharacteristicsCache.CHARACTERISTIC_CUSTOM_NAME, context.MODEL.CustomName);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    Logger.Info("Successfully update the custom name to: " + context.MODEL.CustomName);
                }
                else
                {
                    Logger.Error("Failed with " + result.Status + " to update the custom name to: " + context.MODEL.CustomName);
                }

                return(result);
            }
            return(null);
        }
예제 #13
0
        private async Task _writeToUart(byte[] value)
        {
            GattCharacteristic c = GetCharacteristic(new Guid(BTValues.rxCharacteristic));

            if (c == null)
            {
                return;
            }
            GattWriteResult result = null;

            try {
                result = await c.WriteValueWithResultAsync(WindowsRuntimeBufferExtensions.AsBuffer(value));
            } catch (Exception e) {
            }
            if (result?.Status == GattCommunicationStatus.Success)
            {
                callback.onUartDataSent(value);
            }
        }
예제 #14
0
        public async Task <GattWriteResult> WriteBytesAsync(Guid uuid, byte[] data)
        {
            CHARACTERISTICS.TryGetValue(uuid, out GattCharacteristic c);
            if (c != null)
            {
                IBuffer         buffer = CryptographicBuffer.CreateFromByteArray(data);
                GattWriteResult result = await c.WriteValueWithResultAsync(buffer);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    // Convert to little endian:
                    CACHE.AddToDictionary(uuid, data);
                }
                return(result);
            }
            else
            {
                Logger.Warn("Failed to write to write bytes to: " + uuid.ToString() + " - not loaded.");
            }
            return(null);
        }
예제 #15
0
        private async void ReleaseSPIFlash()
        {
            try
            {
                Console.WriteLine(tag, "ReleaseSPIFlash");
                GattDeviceService service = await GetServiceAsync(Constants.SUOTA_SERVICE_UUID);

                GattCharacteristic characteristic = await GetCharacteristicAsync(Constants.SUOTA_CTRL_UUID, service);

                byte[]          buff   = { 1 };
                GattWriteResult result = await characteristic.WriteValueWithResultAsync(buff.AsBuffer());

                if (result.Status != GattCommunicationStatus.Success)
                {
                    throw (new Exception("ReleaseSPIFlash. =>" + result.Status));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(tag, "Exception while ReleaseSPIFlash. " + ex.Message);
            }
        }
예제 #16
0
        /// <summary>
        /// Register to notifications from a GATT characteristic
        /// </summary>
        /// <param name="characteristic">GATT characteristic</param>
        /// <param name="listener">Method which will be called on each value notification</param>
        /// <returns>true if the operation succeeded, false otherwise</returns>
        public async Task <bool> RegisterValueNotificationAsync(BleGattCharacteristic characteristic, Action <BleGattCharacteristic, BleValue> listener)
        {
            bool ret = false;

            GattCharacteristic gatt_characteristic = characteristic.Context as GattCharacteristic;
            GattClientCharacteristicConfigurationDescriptorValue value;

            if (gatt_characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
            {
                value = GattClientCharacteristicConfigurationDescriptorValue.Notify;
            }
            else if (gatt_characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
            {
                value = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
            }
            else
            {
                value = GattClientCharacteristicConfigurationDescriptorValue.None;
            }
            if (value != GattClientCharacteristicConfigurationDescriptorValue.None)
            {
                if (!_ble_notification_listeners.ContainsKey(characteristic))
                {
                    GattWriteResult result = await gatt_characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(value);

                    if (result.Status == GattCommunicationStatus.Success)
                    {
                        lock (_ble_notification_listeners)
                        {
                            _ble_notification_listeners.Add(characteristic, listener);
                        }
                        gatt_characteristic.ValueChanged += OnCharacteristicNotification;
                        ret = true;
                    }
                }
            }

            return(ret);
        }
예제 #17
0
        private async Task <byte[]> readData(Int32 startAddr)
        {
            try
            {
                GattDeviceService service = await GetServiceAsync(Constants.SUOTA_SERVICE_UUID);

                GattCharacteristic characteristic = await GetCharacteristicAsync(Constants.SUOTA_CTRL_UUID, service);

                Int32           endAddr     = startAddr + 0x100;
                byte[]          retVar      = null;
                byte[]          requestBuff = new byte[] { 3, (byte)(BitConverter.GetBytes(startAddr)[0] & 0xFF), (byte)(BitConverter.GetBytes(startAddr)[1] & 0xFF), (byte)(BitConverter.GetBytes(startAddr)[2] & 0xFF), (byte)(BitConverter.GetBytes(startAddr)[3] & 0xFF), (byte)(BitConverter.GetBytes(endAddr)[0] & 0xFF), (byte)(BitConverter.GetBytes(endAddr)[1] & 0xFF), (byte)(BitConverter.GetBytes(endAddr)[2] & 0xFF), (byte)(BitConverter.GetBytes(endAddr)[3] & 0xFF) };
                GattWriteResult result      = await characteristic.WriteValueWithResultAsync(requestBuff.AsBuffer());

                if (result.Status != GattCommunicationStatus.Success)
                {
                    throw (new Exception("readData. =>" + result.Status));
                }


                characteristic = await GetCharacteristicAsync(Constants.SUOTA_READ_UUID, service);

                var ReadResult = await characteristic.ReadValueAsync();

                if (ReadResult.Status != GattCommunicationStatus.Success)
                {
                    throw (new Exception("readDataResult =>" + ReadResult.Status));
                }

                retVar = ReadResult.Value.ToArray();
                return(retVar);
            }
            catch (Exception ex)
            {
                Console.WriteLine(tag, "Exception while readData. " + ex.Message);
                return(null);
            }
        }
예제 #18
0
        private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            if (args.Advertisement.LocalName.Contains("HMSoft"))
            {
                BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();

                if (result.Status == GattCommunicationStatus.Success)
                {
                    var services = result.Services;
                    foreach (var service in services)
                    {
                        if (!foundServices.Contains(service))
                        {
                            Dispatcher.Invoke(() =>
                            {
                                tb.Text += service.Uuid;
                                tb.Text += Environment.NewLine;
                                foundServices.Add(service);
                            });
                        }
                        if (!service.Uuid.ToString().StartsWith("0000ffe0"))
                        {
                            continue;
                        }
                        GattCharacteristicsResult characteristicsResult = await service.GetCharacteristicsAsync();

                        if (characteristicsResult.Status == GattCommunicationStatus.Success)
                        {
                            var characteristics = characteristicsResult.Characteristics;
                            foreach (var characteristic in characteristics)
                            {
                                if (!foundCharacters.Contains(characteristic))
                                {
                                    Dispatcher.Invoke(() =>
                                    {
                                        tb.Text += characteristic.Uuid;
                                        tb.Text += Environment.NewLine;
                                        foundCharacters.Add(characteristic);
                                    });
                                }

                                if (!characteristic.Uuid.ToString().StartsWith("0000ffe1"))
                                {
                                    continue;
                                }
                                GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
                                if (properties.HasFlag(GattCharacteristicProperties.Indicate))
                                {
                                    GattWriteResult status =
                                        await characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);

                                    return;
                                }

                                if (properties.HasFlag(GattCharacteristicProperties.Notify))
                                {
                                    GattCommunicationStatus status =
                                        await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                                            GattClientCharacteristicConfigurationDescriptorValue.Notify);

                                    if (status == GattCommunicationStatus.Success)
                                    {
                                        characteristic.ValueChanged += Characteristic_ValueChanged;
                                    }
                                }

                                if (properties.HasFlag(GattCharacteristicProperties.Read))
                                {
                                    GattReadResult gattResult = await characteristic.ReadValueAsync();

                                    if (gattResult.Status == GattCommunicationStatus.Success)
                                    {
                                        var    reader = DataReader.FromBuffer(gattResult.Value);
                                        byte[] input  = new byte[reader.UnconsumedBufferLength];
                                        reader.ReadBytes(input);
                                        Dispatcher.Invoke(() =>
                                        {
                                            tb.Text += "connected: ";
                                            tb.Text += Encoding.ASCII.GetString(input);
                                            tb.Text += Environment.NewLine;
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
 public static void ThrowIfError(this GattWriteResult result, [CallerMemberName] string tag = null)
 => result.Status.ThrowIfError(tag, result.ProtocolError);